多个数组导致变量

时间:2013-05-14 19:18:36

标签: php mysql arrays variables

我有一些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];

2 个答案:

答案 0 :(得分: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正确参数化查询。

答案 1 :(得分: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();