PHP准备和执行

Tom*_*ena 0 php mysql

我使用以下代码在数据库中执行查询:

$sql = "SELECT * FROM cc_topchoices  WHERE location='$location' ORDER BY position asc";
$result = mysqli_query($conn, $sql);
Run Code Online (Sandbox Code Playgroud)

我已阅读,这种方式使查询是不安全的,所以我想使用的语句prepare(),并execute()在PHP现在我的代码如下所示:

$sql = "SELECT * FROM cc_topchoices WHERE location=:location ORDER BY position asc";
$stmt = $conn->prepare($sql);
$stmt->execute(array(":location" => $location));

$result = mysqli_query($conn, $stmt);
Run Code Online (Sandbox Code Playgroud)

但这给了我这个错误:

致命错误:在布尔值上调用成员函数execute()

任何的想法?

编辑

现在我的代码看起来像这样:

// Create connection
$conn = new PDO("mysql:host=$servername;dbname=$dbname", "$username", "$password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("set names utf8"); //BECAUSE I NEED TO WORK WITH CHINESE LANGUAGE

$sql = "SELECT * FROM cc_topchoices WHERE location=? ORDER BY position asc";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':location', $location);
$stmt->execute(array($location));           
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

if ($result > 0) {
    // output data of each row
    while($row = $stmt->fetch()) {
        echo "<li><div><a href='". $row["rest_url"] ."'><img src='images/top_choices/". $row["image"] ."' alt='". $row["alt_desc"]. "' /></a></div></li>";
    }
} else {
    echo "0 results";
}
Run Code Online (Sandbox Code Playgroud)

正在工作:)只需要知道这是一个好的和安全的做法

Ama*_*dan 5

PDO支持命名参数.MySQLi没有.$stmtfalse告诉你,你试图准备的SQL在语法上是错误的.用?而不是:location.查看MySQLi手册以了解使用MySQLi的正确方法.或者,交替切换到PDO.