WHERE var = "$name" AND var = "$name"
I am trying to select stories for my mysql database Where the author variable is equal to a list of names.
I basically have a list of names t开发者_高级运维hat I want use in determining what stories to pull.
$names = "name1 name2 name3 name4"
$get_stories = mysql_query("SELECT * FROM glnce_stories WHERE author = '$names' ORDER BY id DESC");
I know that this isn't the right way to do but I was looking for some solutions on how I might be able to break that list up so I can have it pull from the authors in that $names
variable.
Thanks!
If you aren't able to change the format of the $names
variable, this should work:
$names = 'name1 name2 name3 name4';
$names = '"' . implode('","', explode(' ', $names)) . '"';
$get_stories = mysql_query('SELECT * FROM glnce_stories WHERE author IN(' . $names . ') ORDER BY id DESC');
comma separate the names and then use "WHERE author in (" . $names . ")";
You should use WHERE field in (list)
like this:
$names = "'name1', 'name2', 'name3', 'name4'";
$get_stories = mysql_query("SELECT * FROM glnce_stories WHERE author in ($names) ORDER BY id DESC");
So, your query should look something like this: SELECT * FROM glnce_stories WHERE author in ('Bob', 'Steve', 'Andrey', 'Mike', 'Jenna')
Rewrite your code as follows:
$names = "name1 name2 name3 name4";
$names = "'".implode ("','", array_map('mysql_real_escape_string', explode(' ', $names))."'";
$get_stories = mysql_query("SELECT * FROM glnce_stories WHERE author in ($names)");
You can use FIND_IN_SET()
for that if you want to be lazy. You will just have to turn your names list into a comma-separated string:
$names = "name1,name2,name3,name4";
mysql_query("SELECT * FROM stories WHERE FIND_IN_SET(author, '$names')"
That's maybe easier than a list of OR
conditions or preparing a proper string list for an IN
clause. (You can _real_escape_string the whole comma separated list, instead of each name.)
精彩评论