使用准备好的语句从SQL表中进行SELECT * [英] SELECT * from SQL table using prepared statement

查看:90
本文介绍了使用准备好的语句从SQL表中进行SELECT *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用从MySQL表到SELECT *的准备好的语句,并且不确定如何使用while($row = mysqli_fetch_array($stmt))循环并从结果数组中选择项目.这是我的代码,我在做什么错了?

I'm using a prepared statement to SELECT * from a MySQL table and I'm not sure how to use while($row = mysqli_fetch_array($stmt)) to loop through and select items from the result array. This is my code, what am I doing wrong?

    $link = mysqli_connect($host, $username, $password, $db);
    $query = "SELECT * from `wp_posts` WHERE ID=? ";
    //$result = mysqli_query($link, $query);
    $stmt = mysqli_prepare($link, $query);
    if($stmt){
        mysqli_stmt_bind_param($stmt, "i", $pid);
        mysqli_stmt_bind_result($stmt, $dbpid);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_fetch($stmt);
    }
    while($row = mysqli_fetch_array($stmt)){
        ?>
    <h2 align="center"> <?php echo $row['post_title']; ?> </h2><br>
    <div class="paracenter">

        <p id="cont"><?php echo $row['post_content']; ?></p>
        <hr color="black" width="10%">

    </div>
    <?php } ?>

推荐答案

达尔文的答案没错,但想指出

Nothing wrong with Darwin's answer, but wanted to point out PDO as an alternative with much lighter syntax:

<?php
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
$link = new PDO("mysql:host=$host;dbname=$db", $username, $password, $options);
$stmt = $link->prepare("SELECT * from `wp_posts` WHERE ID=?");
$stmt->execute([$pid]);
$result = $stmt->fetchAll();

// Now you have a plain array to work with, database work is over
foreach ($result as $row):
?>

<h2 style="text-align:center;margin:0 auto">
    <?=$row["post_title"]?>
</h2>
<br/>
<div class="paracenter">
    <p id="cont">
        <?=$row["post_content"]?>
    </p>
    <hr style="color:black;width:10%"/>
</div>

<?php endforeach;?>

根本不需要任何绑定,就我个人而言,使用它要容易得多.

No need for any binding at all, and personally I find it much easier to work with.

这篇关于使用准备好的语句从SQL表中进行SELECT *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆