开发者

INSERT INTO not writing into database?

开发者 https://www.devze.com 2023-02-24 12:51 出处:网络
i\'m trying to write info into a db table and it\'s not wor开发者_如何学Goking at all. i\'ve been messing with it for hours. maybe if someone looks at the code they\'ll see something i missed.

i'm trying to write info into a db table and it's not wor开发者_如何学Goking at all. i've been messing with it for hours. maybe if someone looks at the code they'll see something i missed.

my logic is it connects to the db server, opens database mydb, goes to table mod, and writes to id, fname, and lname, then closes the connection.

also, id is set to auto_increment. from what i can tell it should work but it doesn't.

$con = mysql_connect("localhost","user","pass");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db('mydb', $con);

//assign
$query = "INSERT INTO 'mod' (id, fname, lname) VALUES ('', 'bill', 'smith')";
if (!$query){ 
dir ("Unable to create the record:" . mysql_error()); 
exit; 
}
mysql_query($query);
mysql_close($con);


There should be no quotes around 'mod'

//edit:
Also, the if (!query) part isn't really useful at that moment because it is checking the string, not the result. You should check the result of mysql_query() and if that failed you should output an error message.


Change your query to:

$query = "INSERT INTO mod (fname, lname) VALUES ('bill', 'smith')";

Your auto increment id will be added by the database automatically.

UPDATE

Your error code should look like this to work:

$query = "INSERT INTO mod (fname, lname) VALUES ('bill', 'smith')";
$result = mysql_query($query);
if (!$result) {
    die('Invalid query: ' . mysql_error());
}


you are making miskate in referencing the tablename. It should be `mod` instead of 'mod'. i.e ` [backtick] not '[single quote].

and second error is with your die statement...instead of dir it should be die....

INSERT INTO `mod` (id, fname, lname) VALUES ('', 'bill', 'smith');

Next you can also skip inserting value for id field which is autoincreament

so it can be

INSERT INTO `mod` (fname, lname) VALUES ('bill', 'smith');


You actually have to call mysql_query to execute query (to see the mysql_error).


You could also try:

$query = "INSERT INTO mod SET fname='bill', lname='smith'";

And the id column would autoincrement magically.

0

精彩评论

暂无评论...
验证码 换一张
取 消