MySQL搜索与两行的条件

时间:2019-01-27 11:16:35

标签: php mysqli

在表中搜索时引入了一个条件

 $sql = "SELECT id,email  FROM employee WHERE email LIKE ?"; 

在代码中需要添加一个条件id ='12'

更多代码,请同时查看以下代码

if(isset($_REQUEST["term"])){
// Prepare a select statement
$sql = "SELECT id,email FROM employee WHERE id='12' AND email LIKE ?";

if($stmt = mysqli_prepare($link, $sql)){
    // Bind variables to the prepared statement as parameters
    mysqli_stmt_bind_param($stmt, "s", $param_term);

    // Set parameters
    $param_term = '%'. $_REQUEST["term"] . '%';

    // Attempt to execute the prepared statement
    if(mysqli_stmt_execute($stmt)){
        $result = mysqli_stmt_get_result($stmt);

        // Check number of rows in the result set
        if(mysqli_num_rows($result) > 0){
            // Fetch result rows as an associative array
            while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
                echo "<p>" . $row["email"] . "</p>";
            }
        } else{
            echo "<p>No matches found</p>";
        }
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }
}

// Close statement
mysqli_stmt_close($stmt);

}

3 个答案:

答案 0 :(得分:1)

尝试一下

$sql = "SELECT id,email  FROM employee WHERE id='12' AND email LIKE ?";

更改代码

// Set parameters first of all
$param_term = '%'. $_REQUEST["term"] . '%';
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_term);

答案 1 :(得分:0)

只是尝试

$sql = "SELECT id,email FROM employee WHERE email = ? AND id = '12' "; 

答案 2 :(得分:0)

您需要更改要绑定到查询的参数的数量和类型。

if(isset($_REQUEST["term"])){
$id_param = 12; // Parameter One - ID - INT
$param_term = $_REQUEST['term'] . "%"; // Parameter Two - EMAIL LIKE - STRING
// Prepare a select statement
$sql = "SELECT id,email FROM employee WHERE id = ? AND email LIKE ?";

if($stmt = mysqli_prepare($link, $sql)){
    // Bind variables to the prepared statement as parameters
    mysqli_stmt_bind_param($stmt, "is", $id_param, $param_term); //The IS represents INT then STRING  types to be expected, and you follow it up by providing them in that order.

    // Attempt to execute the prepared statement
    if(mysqli_stmt_execute($stmt)){
        $result = mysqli_stmt_get_result($stmt);

        // Check number of rows in the result set
        if(mysqli_num_rows($result) > 0){
            // Fetch result rows as an associative array
            while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
                echo "<p>" . $row["email"] . "</p>";
            }
        } else{
            echo "<p>No matches found</p>";
        }
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }
}

// Close statement
mysqli_stmt_close($stmt);
}