Forum Moderators: coopster
I'm trying to write an SQL statement using a PHP variable as the column name - is this possible? It doesn't seem to work.
I'm using the following code:-
$result = $db->query("SELECT '$value' FROM date WHERE date = '$currentdate'");
$value is from an array (from checkboxes) and this statement is part of a loop that goes through the values of the ticked checkboxes.
In the database the first column ("date") is a list of dates. The other columns are university modules containing what teaching is taking place on each of these dates.
The form presented to the user lists all the modules in the database with checkboxes and the idea is for them to be able to tick 2 or more boxes; this will then present a table showing dates in the first column, and the other columns being made up of the modules ticked so that they can be compared.
I hope all this makes sense...!
Thanks in advance.
I would first do this in 2 steps
$colquery = "SELECT $value FROM date WHERE date = '$currentdate'";
$result = $db->query($colquery);
I also removed the single quotes around the column name.
the above would allow you to check your constructed query to see if it is correct. You can then see that you are getting the values from the form and that you have correctly formatted the date.
like so
$colquery = "SELECT $value FROM date WHERE date = '$currentdate'";
echo '<p>your query is:<br>',$colquery;
die();
$result = $db->query($colquery);
I always stick a die in after my query echo since I just want to look at it since it isn't working.
Have you gotten an error message that might shed some more light on the issue?
Anyway, the result I got was:
"your result is:
Object id#3"
So, the Object id#3 isn't what's in my database, but it's start anyway - have you any idea why that would be?
many thanks.
exactly
if you do the same with out using a class you would get a response something like 'Resource id#3' or something. You always need to extract the data as it is returned in an array or an object depending on what method you use for querying.
glad you got it sorted