Page 1 of 1

Weird MySQL error

Posted: Tue May 18, 2004 12:31 pm
by Dingbats
I'm making a PM script, but MySQL think there are errors in it. Here it is (the code to add the PM do the database):

Code: Select all

<?php
	$sql = "SELECT name FROM users WHERE name = '".$_POST['to']."'";
	$result = mysql_query("$sql");
	$row = mysql_fetch_array($result);
	if($row["name"] == "")
	{
		header("location: pmwrite.php?msg=1");
	}
	
	$to = addslashes($_POST["to"]);
	/* FROM */
	$sql = "SELECT name FROM users WHERE name = '".$_COOKIE['user']."'";
	$result = mysql_query("$sql");
	$row = mysql_fetch_array($result);
	$from = $row["name"];
	/* ENDS HERE */
	$title = addslashes($_POST["title"]);
	$msg = nl2br(addslashes($_POST["msg"]));
	$date = date("Y-m-d");
	
	/* Insert into database */
	$sql = "INSERT INTO pms (to, from, title, msg, date) 
			VALUES ('".$to."', '".$from."', '".$title."', '".$msg."', '".$date."')";
	$result = mysql_query("$sql");
	
	$bajs = mysql_error();
?>
I have a form on another page with input boxes with the names I've written in the code, that isn't the problem. The database tables <i>is</i> called 'pms' and the columns in it are called what I've written in there. $bajs is echoed later on the page, and this is what it says:
"You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near 'to, from, title, msg, date) VALUES ('her', 'Dingbats', '12".
The title I filled in was '1234567890'. It seems that the SQL string is to long or something, though that seems weird since I have SQL strings that are way longer than that one.
Maybe I've done some simple n00b mistake in there, can someone please help me?:|

Posted: Tue May 18, 2004 12:42 pm
by Weirdan
to is reserved word in MySQL SQL dialect (may be in other dialects as well). To use it as field/table name you need to enclose it in backticks: `to`. For more information see http://dev.mysql.com/doc/mysql/en/Reserved_words.html

Posted: Tue May 18, 2004 12:43 pm
by Dingbats
Thanks!

Posted: Tue May 18, 2004 12:45 pm
by Dingbats
Nope, doesn't work...:(

Posted: Tue May 18, 2004 12:52 pm
by Weirdan
echo your $sql variable before passing it to mysql_query function. It would be better to see entire query passed.

Posted: Tue May 18, 2004 12:53 pm
by Weirdan
BTW, from is reserved word as well ;)