4

I'm trying to turn this:

"SELECT username FROM $table WHERE username='$newName'"

Into this:

"SELECT $column FROM $table WHERE $column='$newName'"

But when I use or die() on it, I get an error saying that there is incorrect syntax near WHERE username='someNameHere'. What is the correct way to substitute the column name, assuming that's what's wrong?

Edit: Code is just this. The values should be correct as I don't see any mispellings in the error.

$sql = "SELECT $column FROM $table WHERE $column='$newName'";
$result = mysql_query($sql) or die( mysql_error());
5
  • 1
    Show us your code, i don't get you about 'when i use or die() on it'. Commented Jul 3, 2013 at 13:14
  • 1
    That should work. Are you sure your variables contain expected values? Commented Jul 3, 2013 at 13:14
  • 1
    What does echo $sql; show? Commented Jul 3, 2013 at 13:17
  • 2
    Please, stop using the Deprecated mysql_* extension, switch to PDO or mysqli_*, and start using prepared statements, and make sure there are no spaces, quotes or backticks in the variables Commented Jul 3, 2013 at 13:17
  • 1
    @RocketHazmat Ah, thank you, it was the $table part that got overwritten some lines before this but I just kept concentrating on the $column part. Commented Jul 3, 2013 at 13:24

2 Answers 2

8

Make your query like this

$sql = "SELECT ".$column." FROM ".$table." WHERE ".$column."='".$newName."'"

BTW this is SQLinjection vulnerable code. You should check the variables before using them in query. Also you should start using mysqli and prepared statements

Sign up to request clarification or add additional context in comments.

Comments

1
"SELECT ".$column." FROM ".$table." WHERE ".$column."=".$newName;

Check to see if that works for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.