A Question For You PHP/SQL Pros Out There!?

shawnzabar

New member
I have an SQL table called "users" that has a row called "art styles" and I want to set a php echo that displays all records that contain a specific value from the art styles row.

I want to have a dropdown menu that has all possible values from the art styles row that will change what the query is pulling from for

$query = mysql_query("SELECT * FROM users WHERE artstyle = '[this would be the variable]' ORDER BY `id` DESC");

I am not sure how one would set a variable for that or if there is an easier way to accomplish this. I am relatively new to PHP and SQL .

Any ideas? Appreciated!
 
Hello!
<?php
$query = mysql_query( sprintf("SELECT artstyle FROM users WHERE artstyle='%s' ORDER BY id DESC",
mysql_real_escape_string ($variable_to_use));
//remove the space between string and ($variable_to_use));

while ($record = mysql_fetch_array($query)) {
echo $record[0]; //echo's the first column
echo $record[1]; //echo's the second column
}
?>

You want to use the function sprintf when creating sql queries to prevent against SQL Injection attacks. This works as such
$stuff = sprintf("your sql statement, placing %s wherever you want to put a variable",
mysql_real_escape_string ($first_variable),
mysql_real_escape_string ($second_variable));
in the above examples, you need to remove the space between "string" and "($first..."
%s is replaced by a "safer" version of the variable. They go in order, if you have 5 %s's, then you need 5 mysql_real_escape_string calls after it.

It is bad technique to use SELECT * FROM, it is always better to specify exactly which columns you will be requesting.

Make sure your id column is numbers and can be ordered.
Also look into mysqli. It is the newer version of mysql functions, and most websites *should* offer support for it.
 
Back
Top