简体   繁体   中英

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. If I replace in my sql query: '%$arg%' with '%test%', it echoes the correct value.

Is the '%$arg%' syntax wrong?

您应该使用适当的连接器

"SELECT * FROM db where eng LIKE concat('%', '$arg', '%') order by id ASC LIMIT 10"

It's pretty simple, all you do is: LIKE %{$arg}% . Because I am assuming that $arg is a text value. 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. It's just good practice.

Update


You can't use variables within mysql_query("", $connection) quotes. 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]; was returning the correct value but had a blank line in the source code. So I had to use trim and now it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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