0

我有一些 PHP 代码:

$categories = mysql_query("SELECT category_id, category_name AS categories FROM categories");

while ($row = mysql_fetch_assoc($categories)){
        $columnvalues[] = $row['categories'];
}

$catlist = $columnvalues[0];

$catchq = mysql_query("SELECT message AS message FROM box WHERE LOWER(message) LIKE '".$catlist."'");
$catchr = mysql_fetch_array($catchq);
$catchx = $catchr['message'];
echo $catchx."\n";

上面的代码按预期工作,但仅适用于 [0] 匹配并且消息包含 [0] 的类别名称。我想要完成的是让第二个查询查找在第一个查询中找到的四个类别中的任何一个。

我如何将它与 [1]、[2]、[3] 匹配?我尝试了 OR 运算符,但它不像我想的那样工作(例如$catlist = $columnvalues[0] or $columnvalues[1];

4

2 回答 2

3

你可以循环过去$columnvalues

$query = "SELECT message AS message FROM box WHERE LOWER(message)"
foreach ($columnvalues as $key => $value) {
    if ($key) {
        $query .= " OR ";
    }
    $query .= " LIKE '%$value%' ";
}
$catchq = mysql_query($query);

您的代码容易被注入。您应该对 PDO 或 mysqli 使用正确的参数化查询。

于 2013-05-14T19:23:34.643 回答
0

首先使用 MySQLi,因为 MySQL 已被弃用。这可以做你想做的事:

$mysqli = new mysqli($dbhost, $dbuname, $dbpass, $dbname);
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$categories = $mysqli->query("SELECT `category_id`, `category_name` AS `categories` FROM `categories`");

while ($row = $categories->fetch_array(MYSQLI_BOTH)){
        $columnvalues[] = $row['categories'];
}

$stmt = $mysqli->prepare("SELECT `message` FROM `box` WHERE LOWER(`message`) LIKE ?"); 
foreach($columnvalues as $value){
        $stmt->bind_param("s", $value);
        $stmt->execute();
        $stmt->bind_result($message);
        $stmt->fetch();
        printf("%s: %s<br>", $value, $message);
}
$stmt->close();
于 2013-05-14T19:32:27.830 回答