简体   繁体   English

LIKE运算子无法在MYSQL中运作

[英]LIKE operator not working in MYSQL

this is my code when i run it 这是我运行时的代码

$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))

it shows error on this line help me to fix this 它在此行显示错误,帮助我解决此问题

It is because You are not sending Query matched with your datatype of the name field. 这是因为您没有发送与名称字段的数据类型匹配的查询。

Try below syntax with '' 使用''尝试以下语法

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

IF you still getting the same error then try this code 如果仍然出现相同的错误,请尝试以下代码

$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")); }

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

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

You need to open a connection to your database. 您需要打开与数据库的连接。 Something like: 就像是:

<?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);
?>

Also if you are going to use "LIKE" in your sql, you don't use "=". 另外,如果要在SQL中使用“ LIKE”,则不要使用“ =”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM