mysql和php%like%查询。在phpmyadmin中工作,但在php中的结果不同
我有一些搜索字段可以在几个不同的表中查找 “display_name”表单字段和“last”表单字段显示不同的结果,然后直接将结果输入phpmyadmin 如果我在php脚本中回显mysql查询并将其粘贴到phpmyadmin中。它列出了正确的结果。然而,在php/html页面上,它并没有列出相同的内容 比如说。如果某人的全名是nathan spencer,我将spencer放入“last”表单字段,它将只显示1个或2个结果。然而,通过将其直接粘贴到phpmyadmin并运行它,实际上发现了5个结果 我已经和这件事斗争了很久,它让我发疯 以下是页面顶部的PHP:mysql和php%like%查询。在phpmyadmin中工作,但在php中的结果不同,php,mysql,Php,Mysql,我有一些搜索字段可以在几个不同的表中查找 “display_name”表单字段和“last”表单字段显示不同的结果,然后直接将结果输入phpmyadmin 如果我在php脚本中回显mysql查询并将其粘贴到phpmyadmin中。它列出了正确的结果。然而,在php/html页面上,它并没有列出相同的内容 比如说。如果某人的全名是nathan spencer,我将spencer放入“last”表单字段,它将只显示1个或2个结果。然而,通过将其直接粘贴到phpmyadmin并运行它,实际上发现了5个
<?php
// SEARCH
if(isset($_POST['submit'])) {
// define the list of fields
$fields = array('display_name', 'last', 'suburb', 'state', 'user_type', 'active');
$conditions = array();
// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && $_POST[$field] != '') {
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "`$field` LIKE '%".mysql_real_escape_string($_POST[$field])."%'";
}
}
// builds the query
$query = "SELECT display_name, first, last, suburb, state, user_type, active FROM nfw_users ";
// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= "WHERE " . implode (' AND ', $conditions) .""; // you can change to 'OR', but I suggest to apply the filters cumulative
}
else {
echo "No records found";
}
$result = mysql_query($query);
$score = mysql_fetch_assoc($result);
}
?>
如果我没有弄错您的代码,可能会出现以下问题:
在这里,您实际获取第一行
$result = mysql_query($query);
$score = mysql_fetch_assoc($result);
然后,您似乎只需跳过它并使用循环:
if(isset($score)){
while($score=mysql_fetch_assoc($result)){
你真正想做的是:
$result = mysql_query($query);
if (!$result) {
//TODO: Query error handling
}
// This is how you check for results count
if (mysql_num_rows($result) == 0) {
while ($score = mysql_fetch_assoc($result)) {
//Here you go with result
}
}
您也可以检查作为参考
接下来要检查的是,从查询中获取确切的字符串,然后从phpMyAdmin中尝试。在执行查询时,请确保使用与代码相同的用户
还有一件事,你使用的扩展时间很长,你应该考虑切换到/< /P>,你可以在<代码> $结果= MySQL查询($查询)之前提供<代码> $查询<代码>的值;code>string?string(142)“选择display_name、first、last、country、user_type、activefrom nfw_用户,其中
display_name
类似于“%nick%”和last
类似于“%smith%”可能重复的内容似乎是您做了错误的检查并循环了结果走开,吃了晚饭。回来后,看了看我的代码和你的解决方案,5分钟就搞定了。非常感谢你的帮助。全部固定:)
if(isset($score)){
while($score=mysql_fetch_assoc($result)){
$result = mysql_query($query);
if (!$result) {
//TODO: Query error handling
}
// This is how you check for results count
if (mysql_num_rows($result) == 0) {
while ($score = mysql_fetch_assoc($result)) {
//Here you go with result
}
}