Weird MySQL error

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
Dingbats
Forum Commoner
Posts: 25
Joined: Fri Dec 05, 2003 10:53 am

Weird MySQL error

Post 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?:|
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post 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
Dingbats
Forum Commoner
Posts: 25
Joined: Fri Dec 05, 2003 10:53 am

Post by Dingbats »

Thanks!
Dingbats
Forum Commoner
Posts: 25
Joined: Fri Dec 05, 2003 10:53 am

Post by Dingbats »

Nope, doesn't work...:(
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

echo your $sql variable before passing it to mysql_query function. It would be better to see entire query passed.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

BTW, from is reserved word as well ;)
Post Reply