[英]Sql like query with variable?
I have this function: 我有这个功能:
function word($arg){
echo ''.$arg.'';
//echoes test
require ('config.php');
$requestSQL = mysql_query("SELECT * FROM db where eng LIKE '%$arg%' order by id ASC LIMIT 10", $connection);
while ($row = mysql_fetch_array($requestSQL))
{
echo ''.$row['id'].': '.$row['eng'].'<br>';
}
}
Gets triggered by: 通过以下方式触发:
$number = $explode[1];
word($number);
But doesn't echo values from the database, nothing at all. 但是不会从数据库中回显任何值,一点也没有。 If I echo $arg (in the function), it shows the value.
如果我在函数中回显$ arg,它将显示该值。 If I replace in my sql query: '%$arg%' with '%test%', it echoes the correct value.
如果我在sql查询中将“%$ arg%”替换为“%test%”,它将回显正确的值。
Is the '%$arg%' syntax wrong? '%$ arg%'语法错误吗?
您应该使用适当的连接器
"SELECT * FROM db where eng LIKE concat('%', '$arg', '%') order by id ASC LIMIT 10"
It's pretty simple, all you do is: LIKE %{$arg}%
. 很简单,您所要做的就是:
LIKE %{$arg}%
。 Because I am assuming that $arg
is a text value. 因为我假设
$arg
是一个文本值。 If a variable is a text value then you must do this to keep it working. 如果变量是文本值,则必须执行此操作以使其保持工作状态。 You wrap text variables in
{}
. 您将文本变量包装在
{}
。
Also, never . 另外,从不。 .
。 .
。 EVER use
mysql_*
, you should move to mysqli_*
or PDO/OOP. 永远使用
mysql_*
,您应该转到mysqli_*
或PDO / OOP。 It's just good practice. 这只是个好习惯。
You can't use variables within mysql_query("", $connection)
quotes. 您不能在
mysql_query("", $connection)
引号内使用变量。 Instead, do this: 相反,请执行以下操作:
$query = "SELECT * FROM db WHERE eng LIKE '%{$arg}%' ORDER BY id ASC LIMIT 10";
// then use this variable as a replacement for the quotes in the mysql_query().
$set = mysql_query($query, $connection); // like so . . .
// mysql_fetch_assoc() is the same as mysql_fetch_array().
while($row = mysql_fetch_assoc($set)) {
echo "".$row['id'].": ".$row['eng']."<br>";
}
I'm so stupid, actually $explode[1]; 我是如此愚蠢,实际上是$ explode [1]; was returning the correct value but had a blank line in the source code.
返回正确的值,但源代码中有空行。 So I had to use trim and now it works.
所以我不得不使用修剪,现在它可以工作了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.