Forum Moderators: coopster

Message Too Old, No Replies

MySQL syntax error

         

ztjuh

6:56 am on Jun 20, 2011 (gmt 0)

10+ Year Member



I'm getting this error when I try to pull some values out of my database:
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 ''a\'' at line 1


This is the code of the script:
if(isset($_POST['user'])&&trim($_POST['user'])!="")
{
echo "SELECT * FROM login_data WHERE userid='".mysql_real_escape_string($_POST['user'])."'";
if(mysql_query("SELECT * FROM login_data WHERE userid='".mysql_real_escape_string($_POST['user'])."'") or die(mysql_error()))
$errors[] = "Account with given user code already exists";
}


It takes in a string from a form input. I had input "a" to test.

I set it to output the query and get:
SELECT * FROM login_data WHERE name='a'

coopster

12:50 pm on Jun 20, 2011 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, ztjuh.

It is odd to me that the output is showing name where as your query there is using userid. Are you certain you are looking at the right query here? It doesn't match up.

ztjuh

8:17 am on Jun 21, 2011 (gmt 0)

10+ Year Member



oh, right. this is my name query (which is exactly the same):

if(isset($_POST['name'])&&trim($_POST['name'])!="")
{
echo "SELECT * FROM login_data WHERE name='".mysql_real_escape_string($_POST['name'])."'";
if(mysql_query("SELECT * FROM login_data WHERE name='".mysql_real_escape_string($_POST['name']."'")) or die(mysql_error()))
$errors[] = "Account with given name already exists";
}

coopster

2:21 pm on Jun 21, 2011 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I would break up your code into pieces and start troubleshooting there. Define your query once, test it, set it to die() or exit() if you have an error during testing. You'll find troubleshooting much easier this way.
if (isset($_POST['name']) && trim($_POST['name']) != "") { 
$name = mysql_real_escape_string(trim($_POST['name']));
$sql = "SELECT * FROM login_data WHERE name='{$name}'";
$rows = mysql_query($sql) or die(mysql_error());
if (... handle your logic from here ...) {
// etc etc etc
}
}