使用mysqli prepared statement创建一个表

时间:2014-11-10 12:41:49

标签: php mysqli

`我在下面有一个非常简单的简单代码:

        $sql = "SELECT * FROM `alerte`";
    $result = $mysqli->query($sql);

if ($result->num_rows > 0) {    

    while ($row = $result->fetch_assoc()) {
        echo "<tr>";
        echo "<td>" . $row['nom_alerte'] . "</td>";
        echo "<td>" . $row['id_priorite'] . "</td>";
        echo "</tr>";   
    }

}   

我想使用准备好的声明,但我不知道如何。

$stmt = $mysqli -> prepare("SELECT * 
                                FROM `alerte`
                                WHERE `id_alerte` = ?");
$stmt->bind_param('i', $id_membre);                             
$stmt->execute(); 

while ($row = $stmt->fetch()) {
    echo "<tr>";
    echo "<td>" . $row['nom_alerte'] . "</td>";
    echo "<td>" . $row['id_priorite'] . "</td>";
    echo "</tr>"; } 

有人能指出我正确的方向吗?

解决方案,感谢您的评论! :

    $id_alerte = '5';
$stmt = $mysqli -> prepare("SELECT  `nom_alerte`, 
                                `id_priorite`
                            FROM `alerte`
                            WHERE `id_alerte` < ?");
$stmt->bind_param('i', $id_alerte);                             
$stmt->execute(); 

$stmt->bind_result($nom_alerte, $date_debut_alerte, $date_fin_alerte,      $description_alerte, $status, $id_equipe, $id_priorite);

while ($stmt->fetch()) {
echo "<tr>";
    echo "<td>" . $nom_alerte . "</td>";
    echo "<td>" . $id_priorite . "</td>";
echo "</tr>"; 
}   

1 个答案:

答案 0 :(得分:1)

有两种方法,如果您的系统上安装了mysqlnd,则可以使用->get_result()方法

如果不可用,则使用->bind_result()从预先准备好的语句中获取结果:

->get_result()版本:

$stmt = $mysqli->prepare("SELECT * FROM `alerte` WHERE `id_alerte` = ?");
$stmt->bind_param('i', $id_membre);                             
$stmt->execute(); 

$results = $stmt->get_result();
while ($row = $stmt->fetch_assoc()) {
    echo "<tr>";
        echo "<td>" . $row['nom_alerte'] . "</td>";
        echo "<td>" . $row['id_priorite'] . "</td>";
    echo "</tr>"; 
}

bind_result()版本:

$stmt = $mysqli->prepare("SELECT `nom_alerte`, `id_priorite` FROM `alerte` WHERE `id_alerte` = ?");
$stmt->bind_param('i', $id_membre);                             
$stmt->execute(); 

$stmt->bind_result($nom_alerte, $id_priorite);
while ($stmt->fetch()) {
    echo "<tr>";
        echo "<td>" . $nom_alerte . "</td>";
        echo "<td>" . $id_priorite . "</td>";
    echo "</tr>"; 
}