Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a variable as the column name in a mysql query

Tags:

php

mysql

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());
like image 778
idlackage Avatar asked Jan 14 '23 00:01

idlackage


2 Answers

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

like image 189
Jakolcz Avatar answered Jan 19 '23 13:01

Jakolcz


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

Check to see if that works for you.

like image 21
PmanAce Avatar answered Jan 19 '23 11:01

PmanAce