PHP MySQL query returning NULL
I have a MySQL table that looks like this:
index | tag | posts
-------------------------
1 | cats | 9,10
2 | a cat | 9,10
3 | kitty | 9,10
4 | meow | 9,10
I am trying to just return the row that matches a search query. I passed the search parameter using a simple ?search=cats
. This is the PHP that I'm using:
$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);
However the mysql_num_rows($query)
prints 0 and the $print
returns NULL. I can check it with ($print == "")
, it evaluates to TRUE and mysql_num_rows($query)
returns 4. I tried setting the search query to something that wasn't in the table and it retuned FALSE as expected. I also tried removing the WHERE tag = '$search'
and it returns the table like it should.
Is there something I'm overlooking?
Edit
Took everyone's advice and the code I'm using now is:
$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
Still have the same problem. The mysql_query
is retuning NULL instead of the row or FALSE if it doesn't match.
(in the future I will use the mysqli
API, but I would like to finnish this project in mysql
. thanks for your suggestions and advice)
Ok so after referring to the above edit you made, here is the solution
Use "LIKE" instead of "=" when using wildcard "%"
So your query now should be
$queryText = "SELECT * FROM tags WHERE tag LIKE '%" . $search . "%'";
[I created the exact same db on my local system and ran the same code you gave, After making the above changes, It runs as expected]
Try this code now.
Remeber when you want to debug something in PHP the faster way is var_dump not echo. Also you should avoid mysql_api because they are deprecated, use PDO instead PDO on PHP.net
var_dump($_GET); // Just for debuggin if as something
$search = $_GET['search'];
$query = mysql_query("SELECT * FROM tags WHERE tag = '".mysql_real_escape_string($search)."'");
// echo(mysql_num_rows($query));
$result = mysql_fetch_array($query);
var_dump($result);
//$print = $result['posts'];
//echo($print);
$search = $_GET['search'];
echo $select_query="SELECT * FROM tags WHERE tag = '".mysql_real_escape_string($search)."'";
$query = mysql_query($select_query);
echo(mysql_num_rows($query));
while($result = mysql_fetch_array($query))
{
print_r($result);
}
链接地址: http://www.djcxy.com/p/58870.html
上一篇: 所有的PHP类型都返回一个布尔值吗?
下一篇: PHP MySQL查询返回NULL