我想在php中使用两个where条件从mysql获取数据

时间:2016-06-15 13:59:38

标签: php echo conditional-statements where

我的问题是:

<?php
    // Connect to database server
    mysql_connect("localhost", "root", "abcabc") or die (mysql_error ());

    // Select database
    mysql_select_db('iite') or die(mysql_error());

    // Get data from the database depending on the value of the id in the URL
    $strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"];
    $rs = mysql_query($strSQL);

    // Loop the recordset $rs
    while($row = mysql_fetch_array($rs)) {

        // Write the data of the person
        echo'<h1>'. $row['title'].'</h1>';
        echo'<h1>'. $row['price'].'</h1>';
    }

    // Close the database connection
    mysql_close();
?>

我想显示相关帖子,为此我需要插入此内容:

$sql = "SELECT * FROM table1 where title like '%keyword%' limit 5";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["price"]. " " . $row["title"]. "<br>";
    }
} else {
    echo "0 results";
}

所以如何在

附近插入相关的帖子部分
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"];

以及如何回应?

由于

3 个答案:

答案 0 :(得分:0)

您可以使用OR或AND在查询中组合不同的where条件(根据要求):

实施例

$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"] ." OR title like '%keyword%' limit 5";

答案 1 :(得分:0)

$strSQL = mysql_query(SELECT * FROM table1 WHERE id=" . $_GET["id"] ." OR title like '%keyword%' limit 5) or die(mysql_error());

$row_strSQL = mysql_fetch_assoc($strSQL );
$totalRows_strSQL = mysql_num_rows($strSQL );


if ($result->totalRows_strSQL > 0) {
    // output data of each row
    while($row_strSQL= $result->fetch_assoc()) {
        echo "id: " . $row_strSQL["id"]. " - Name: " . $row_strSQL["price"]. " " . $row_strSQL["title"]. "<br>";
    }
} else {
    echo "0 results";
}

答案 2 :(得分:0)

根本不需要两个单独的查询。只需在像Where id=" . $_GET['id']." or title like '%keyword%'

这样的ur where子句中使用OR运算符