PDA

View Full Version : Insert Failing


Albatross
2-21-06, 06:57 PM
I'm having problems getting MySQL INSERT to work. Here's the code block of PHP that does the inserting:

mysql_pconnect("mysql09.powweb.com", "foo", "foo") or die("Can't connect to MySQL Server");
mysql_select_db("news_database") or die("Can't find the MySQL database");

$insertquery = "INSERT INTO news_entries (entrydate, post) VALUES ($completedate, $completetext)";
$result = mysql_query($insertquery) or die("Couldn't add new post.");
$error = mysql_error();
print "$error";
mysql_close();


The table news_entries consists of three fields: entrydate (a date field), post (a text field), and id (an int). id is an auto-increment field and the primary key to guarantee uniqueness. In the example above, I don't try to set a value for id, but just let the auto-increment set it.

The connect and select_db goes fine, but when I try to run the query with mysql_query, I get my die message. mysql_error() returns nothing. Am I just making a syntax mistake here? The only thing I can think of is maybe the date field. I'm trying to insert a string into it (in the form (yyyy-mm-dd) and I'm not sure if MySQL converts it into a date or if I need to do it myself.

mitchind
2-21-06, 07:25 PM
First - mysql_pconnect won't generate a persistent connection at Powweb - just use mysql_connect.

Second - use quotation marks around your field values - and it can't hurt to use them around field names too. If you want to troubleshoot your queries, the best way is to echo the statement to the screen, and copy/paste it into phpMyAdmin for syntax errors.

Try:
$insertquery = "INSERT INTO news_entries ('entrydate', 'post') VALUES ('$completedate', '$completetext')";

foofoo
2-22-06, 12:36 PM
Second - use quotation marks around your field values - and it can't hurt to use them around field names too.


For proper use aren't you supposed to use the back quotes for table/field names? That would be the ` located under the ~ (tilde).

Isn't this proper?

SELECT * FROM `table` WHERE `id` = '$number';

mitchind
2-22-06, 12:41 PM
For proper use aren't you supposed to use the back quotes for table/field names? That would be the ` located under the ~ (tilde).

Isn't this proper?

SELECT * FROM `table` WHERE `id` = '$number';

Yes - you're correct. If table/fields have special names or use spaces or special characters you need to use the back quotes - otherwise nothing needs to surround their names.

Albatross
2-22-06, 06:20 PM
In the end, the syntax I had to use was:
$insertquery = "INSERT INTO `news_entries` (`entrydate`, `post`) VALUES ('$completedate', '$completetext')";

` marks around table name and table fields, ' marks around the values.