PHP准备语句错误:无法准备选择

时间:2015-07-18 09:25:19

标签: php

我想从MYSQL数据库中选择数据。为此,我做了以下事情:

$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);

mysqli_set_charset($mysqli, "utf8");

date_default_timezone_set("Europe/Berlin");

session_name('User Session'); 
session_start(); 

$private_id = session_id(); 
$private_questions = get_questions($mysqli);

session_write_close(); 

    function get_questions($mysqli, $stmt_get_questions) { 
    $stmt = $mysqli->query($stmt_get_questions);

    $questions = array();

    while($question = $stmt->fetch_assoc()) {
        $questions[] = $question;   
    }

    $stmt->close();
    $mysqli->close();

    return $questions;
}

在HTML中调用我的变量:

<div class="container">

    <p>Private ID is <?=$private_id?></p>
    <p>Questions <?=$private_questions?></p>
</div>

但我收到内部服务器错误:

GET mywebsite/myhtml.html 500 (Internal Server Error)

我找不到问题。 MYSQL选择正确。

1 个答案:

答案 0 :(得分:2)

你对这个概念感到困惑。

您可以像这样运行SELECT语句:

$stmt_select = "SELECT A, B, C FROM MY_TABLE";
$stmt = $mysqli->query($stmt_select);

或者如果你想要防范MYSQL注入黑客,那么你可以使用这样的预备函数:(注意在准备好的语句中你必须有问号“?”然后使用bind_param()函数)

 if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {

/* bind parameters for markers */
$stmt->bind_param("s", $city);

/* execute query */
$stmt->execute();

/* bind result variables */
$stmt->bind_result($district);

/* fetch value */
$stmt->fetch();

printf("%s is in district %s\n", $city, $district);

/* close statement */
$stmt->close();
}

请阅读此链接以获得更多说明:

Mysql prepared statement

完整的答案如下:

 $mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);

 $mysqli_set_charset($mysqli, "utf8");

 date_default_timezone_set("Europe/Berlin");

 $stmt_get_questions = "SELECT A, B, C FROM MY_TABLE";

 session_name('User Session'); 
 session_start(); 

 $private_id = session_id(); 
 $private_questions = get_questions($mysqli);

 session_write_close(); 

 function get_questions($mysqli) { 
 // Execute the MYSQL statement
 $stmt = $mysqli->query($stmt_get_questions);

 // Get the result and iterate through it
 while($row = $stmt->fetch_assoc()) {
     // Do Something with the each row, Like reading a column:
     $column_one = $row['column_one'];  
 }

 $stmt->close();
 $mysqli->close();

 return $questions;
 }