LIKE运算符不在MYSQL中工作

时间:2017-03-11 05:24:28

标签: php mysql

这是我运行时的代码

$name=$_GET['name'];
$strSQL = "SELECT * FROM category WHERE name LIKE =" .$name;

$rs = mysql_query($strSQL);

// Loop the recordset $rs
$response = array();
while($row = mysql_fetch_array($rs)) {


    $product = array();
    $product["id"] = $row["id"];
    $product["name"] = $row["name"];
    array_push($response, $product);
}

echo json_encode($response);
}
error:mysql_fetch_array() expects parameter 1 to be resource, boolean given in while($row = mysql_fetch_array($rs))

它显示此行的错误有助于我解决此问题

3 个答案:

答案 0 :(得分:0)

这是因为您没有发送与名称字段的数据类型匹配的查询。

使用''

尝试以下语法
$strSQL = "SELECT * FROM category WHERE name LIKE '" .$name . "'";

如果您仍然遇到相同的错误,请尝试使用此代码

$name=$_GET['name'];
$strSQL = "SELECT * FROM category WHERE name LIKE '" .$name . "'";

$rs = mysql_query($strSQL);
if(mysql_num_rows($rs) > 0){
// Loop the recordset $rs
$response = array();
while($row = mysql_fetch_array($rs)) {


    $product = array();
    $product["id"] = $row["id"];
    $product["name"] = $row["name"];
    array_push($response, $product);
}

echo json_encode($response);
}
}
else{ echo json_encode(array('msg'=>"No records found")); }

答案 1 :(得分:0)

您插入了错误的语法....使用此

 $strSQL = "SELECT * FROM category WHERE name LIKE '%$name'";

答案 2 :(得分:0)

您需要打开与数据库的连接。类似的东西:

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$name=$_GET['name'];
$strSQL = "SELECT * FROM category WHERE name LIKE '%" .$name . "%'";
// $strSQL = "SELECT * FROM category WHERE name = '" .$name . "'";

$rs = mysql_query($strSQL, $conn);

// Loop the recordset $rs
$response = array();
while($row = mysql_fetch_array($rs)) {


    $product = array();
    $product["id"] = $row["id"];
    $product["name"] = $row["name"];
    array_push($response, $product);
}

echo json_encode($response);
?>

此外,如果您打算使用&#34; LIKE&#34;在你的SQL中,你不能使用&#34; =&#34;。