views:

29

answers:

4

I am trying to learn mysql and having some problem with updating/adding data to the table

this is my code and after running this page when I go to phpmyadmin to see if the new data showed up, i dont see it there.

<?php

$conn = mysql_connect($dbhost, $dbuser, $dbpass); 

if(!$conn) {  die("Could not connect");   }
$dbname = "test";
mysql_select_db($dbname, $conn);

mysql_query("INSERT INTO 'test'.'table1' 
               ('A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8') 
             VALUES  
               ('test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7', 'test8')"); 

mysql_close($conn);

?>

Can anyone tell me whats wrong with this ?

A: 

First of all, make sure that database was selected fine:

mysql_select_db($dbname, $conn) or die('Could not select the database');

There are chances that there is some error in your query, a reason why data is not added, try adding or die(mysql_error()) after this mysql_query function to see the possible error:

mysql_query("your query....") or die(mysql_error()); 

Also no need to specify the database name:

'test'.'table1'

Just use table1 in your query.

Turning on error reporting is also useful:

ini_set('display_errors', true);
error_reporting(E_ALL);
Sarfraz
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use"Can you please tell me whats wrong with the query?
Kartik
A: 

Here is a tip for you in general when working with MYSQL (Or any SQL DB). If you don't know how to do something, or you are getting things wrong. Use the GUI tools provided for you to do the job, then check the resulting code.

Enter PHPMyAdmin, Do an insert, and then copy and paste the code to see what you are doing wrong.

Pyronaut
thats how I got the query code but doesnt seem to work
Kartik
+1  A: 

Be sure to do error checking to see if the mysql connection is having trouble too:

if(!mysql_select_db($dbname, $conn)) {
   echo  mysql_error($conn);
}else {

    if(!mysql_query("INSERT INTO  'test'.'table1' ('A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8') VALUES ('test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7', 'test8')")) {
      echo  mysql_error($conn);
   } 
}
cdburgess
A: 

The problem is the quotes around the field names. MySQL doesn't allow single-quoted field names. They either have to be bare (A1), or within backticks (`A1`), so your query should be rewritten as:

INSERT INTO table1 (A1, A2, A3, A4, A5, A6, A7, A8)
VALUES ('test1', 'test2', 'test3', 'test4', etc.....);
Marc B