PHP MySQLi预准备语句不工作[重复]

kupeojn6  于 2023-02-07  发布在  Mysql
关注(0)|答案(2)|浏览(135)
    • 此问题在此处已有答案**:

Enclosing prepared statement placeholders in single quotes(1个答案)
Build SELECT query with dynamic number of LIKE conditions as a mysqli prepared statement(2个答案)
2小时前关门了。
我尝试使用MySQLi创建一个预准备语句并对数据库运行它,目前,我正在获取列名和结果元数据,但没有将任何结果打印到HTML表中,并且mysqli_stmt_num_rows($statement)返回0。我运行了一些测试回显,$value确实从文本框中获得了正确的值,当我在数据库上运行查询时,直接替换?它确实返回一些数据。知道为什么我没有将数据发送到MySQLi吗?"

function Get_Data($value,$radio){

    //gets data if the blank option was not selected
    if($value != ""){
    //create connection
    $con= mysqli_connect("localhost","root","password","world");
    // Check connection
    if (!$con) {
        echo "<p>Error: Unable to connect to MySQL." . PHP_EOL."</p>";
        echo "<p>Debugging errno: " . mysqli_connect_errno() . PHP_EOL."</p>";
        echo "<p>Debugging error: " . mysqli_connect_error() . PHP_EOL."</p>";
        exit;
    }

switch ($radio) {
    case 0:
        if(htmlspecialchars($value) != ""){
         $query = "SELECT * FROM City WHERE name LIKE '?%'";

         }
        else{
            echo "<p>Your search text was invalid</p>";
        }

        break;
    default:
        break;
}

    $statement = mysqli_stmt_init($con);
if (mysqli_stmt_prepare($statement, $query)) {

        /* bind parameters for markers */
        mysqli_stmt_bind_param($statement, "s", $value);

        /* execute query */
        mysqli_stmt_execute($statement);
        mysqli_stmt_bind_result($statement,$id, $name, $code, $district,$population);

       $result = mysqli_stmt_result_metadata($statement);

}else{
    echo "<p>Error".mysqli_stmt_errno()."</p>";
}
    echo "<p>Number of Rows:".mysqli_stmt_num_rows($statement)."</p>";
    // Get number of columns from result
    $fieldinfo=mysqli_fetch_fields($result);
    //create table
    echo "<table  class='table table-hover'><thead>";
    //create the header for each column
    foreach ($fieldinfo as $value) {
        echo "<th>".$value->name."</th>";
    }
    echo "</thead><tbody>";
    //get each row
    while (mysqli_stmt_fetch($statement)) {
        echo "<tr><td>".$id."</td><td>".$name."</td><td>".$code."</td><td>".$district."</td><td>".$population."</td></tr>";
    }
    echo  "</tbody></table>";


    //free result
    mysqli_free_result($result);
    //close mysql connection
    mysqli_close($con);
    }

}

?>`
6jjcrrmo

6jjcrrmo1#

不要引用占位符,绑定会为您做这件事:
用途

$query = "SELECT * FROM City WHERE name LIKE ?";

并将通配符%包含在要绑定的变量中,而不是包含在预准备语句中
并且由于mysqli_stmt_bind_param()需要通过引用传递参数,因此需要在绑定之前附加%

$value .= '%';
mysqli_stmt_bind_param($statement, "s", $value);
xqk2d5yq

xqk2d5yq2#

引号内的占位符不会被替换。您可以使用CONCAT附加通配符。

$query = "SELECT * FROM City WHERE name LIKE CONCAT(?, '%')";

相关问题