我有一个如下所示的 MySQL 表:
index | tag | posts
-------------------------
1 | cats | 9,10
2 | a cat | 9,10
3 | kitty | 9,10
4 | meow | 9,10
我试图只返回与搜索查询匹配的行。我使用简单的?search=cats
. 这是我正在使用的 PHP:
$search = $_GET['search'];
$query = mysql_query("SELECT * FROM tags WHERE tag = '$search'");
echo(mysql_num_rows($query));
$result = mysql_fetch_array($query);
$print = $result['posts'];
echo($print);
但是mysql_num_rows($query)
打印 0 并$print
返回 NULL。我可以用 来检查它($print == "")
,它的计算结果为 TRUE 并mysql_num_rows($query)
返回 4。我尝试将搜索查询设置为表中没有的内容,它按预期重新调整了 FALSE。我还尝试删除WHERE tag = '$search'
它,它会按原样返回表格。
有什么我忽略的吗?
编辑
听取了大家的建议,我现在使用的代码是:
$search = mysql_real_escape_string($_GET['search']);
var_dump($search); //prints string(4) "cats" just like it should
$queryText = "SELECT * FROM tags WHERE tag = '%".$search."%'";
echo($queryText); //SELECT * FROM tags WHERE tag = '%cats%'
$query = mysql_query($queryText) or die(mysql_error()); //no error
$rows = mysql_num_rows($query); //this returns 0 and I know it should match 1 row
echo('rows: '.$rows);
$result = mysql_fetch_array($query);
$print = $result['posts'];
echo($print); //empty
仍然有同样的问题。mysql_query
如果不匹配,则重新调整 NULL 而不是行或 FALSE 。
(将来我会使用mysqli
API,但我想在. 中完成这个项目mysql
。感谢您的建议和建议)