我有这个代码:
PHP的:
[CONNECT TO DATABASE OR DIE ( THIS WORKS )]
if(isset($_GET['search'])) // If it's submitted
{
$inp = Clean($_GET['inpname']); // Clean my input
$sQuery="SELECT name FROM user WHERE (id LIKE '%$inp%')"; // mySql query
$r = mysql_query($sQuery) or die(mysql_error());
if(mysql_affected_rows()===0) // If no match found
echo "{$inp} is not in our database.";
else
{
echo "<p>{$inp} was successfully searched.</p>"; // Yes, the query worked
while($row=mysql_fetch_array($r)) // Loop through the query results
echo "{$row[0]}<br>"; // Show the results
} // End of the else statement
} // End of the if statement
function Clean($str) // Clean my input
{
return mysql_real_escape_string(strip_tags(trim($sStr))); // Remove traces of injection
}
HTML:
<form name="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
<input name="inpname" type="text">
<input type="submit" name="search" value="Search">
</form>
我想按ID搜索数据库中的成员,但是当我搜索示例1时,没有结果:不在数据库中。 (/index.php?inpname=1&search=搜索)
如果我使用'%“。$ inp。”%'而不是'%$ inp%',则可以,但是它向我显示了数据库中的所有用户。
最佳答案
如果您检查php手册说:
int mysql_affected_rows ([ resource $link_identifier = NULL ] )
通过与link_identifier关联的最后一个INSERT,UPDATE,REPLACE或DELETE查询获取受影响的行数。
http://php.net/manual/en/function.mysql-affected-rows.php
因此,如果使用SELECT查询,则没有返回值。
像这样更改代码
if(isset($_GET['search'])) // If it's submitted
{
$inp = Clean($_GET['inpname']); // Clean my input
$sQuery="SELECT name FROM user WHERE id LIKE '%$inp%'"; // mySql query
$r = mysql_query($sQuery) or die(mysql_error());
if (mysql_num_rows($r))
{
while ($row=mysql_fetch_array($r))
{
echo $row['name']."<br>"; // Show the results
}
}
else
{
echo "{$inp} is not in our database.";
}
} // End of the if statement
如果只想要一行
if(isset($_GET['search'])) // If it's submitted
{
$inp = Clean($_GET['inpname']); // Clean my input
$sQuery="SELECT name FROM user WHERE id LIKE '%$inp%' LIMIT 1"; // mySql query
$r = mysql_query($sQuery) or die(mysql_error());
if (mysql_num_rows($r))
{
$row=mysql_fetch_array($r)
echo $row['name']."<br>"; // Show the results
}
else
{
echo "{$inp} is not in our database.";
}
} // End of the if statement
如果您想按确切的ID搜索
if(isset($_GET['search'])) // If it's submitted
{
$inp = Clean($_GET['inpname']); // Clean my input
$sQuery="SELECT name FROM user WHERE id = $inp LIMIT 1"; // mySql query
$r = mysql_query($sQuery) or die(mysql_error());
if (mysql_num_rows($r))
{
$row=mysql_fetch_array($r)
echo $row['name']."<br>"; // Show the results
}
else
{
echo "{$inp} is not in our database.";
}
} // End of the if statement
关于php - 搜索查询返回空结果集,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11555636/