【问题标题】:How to display images from the database using prepared statments in PHP?如何使用 PHP 中的预处理语句显示数据库中的图像?
【发布时间】:2018-09-03 03:59:42
【问题描述】:

我正在构建一个博客应用程序,用户可以在其中发布博客和上传图片。而博客的特点之一是在标题中显示数据库中当前用户的个人资料图像。我正在使用 PHP 的程序样式和准备好的语句来显示图像,但我得到的是一个损坏的图像链接而不是图像本身。 这是我使用 SELECT 语句和准备好的语句获取图像的代码:

<?php 
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];

$stmt = mysqli_prepare($connection, "SELECT user_image FROM users WHERE user_name = ?");
mysqli_stmt_bind_param($stmt, "s", $profile_picture);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $profile_picture);
mysqli_stmt_fetch($stmt);
while (mysqli_stmt_fetch($stmt)) {
    $profile_picture = $stmt['user_image'];
}
mysqli_stmt_close($stmt);
}
 ?>

这是我在其中显示在数据库中选择的用户图像的代码:

<img width='30' class='img-responsive; img-circle' src='../images/<?php echo $profile_picture; ?>'>

我的问题是如何使用程序样式 PHP 使用准备好的语句正确显示数据库中的图像?我在使用准备好的语句和遇到一些挫折方面很陌生。我了解并知道如何使用 INSERT 语句使用准备好的语句,但在 SELECT 语句中使用它时遇到问题。

【问题讨论】:

    标签: php prepared-statement


    【解决方案1】:

    在行中 mysqli_stmt_bind_param($stmt, "s", $profile_picture); 您应该将变量 $profile_picture 替换为 $username

    【讨论】:

    • 您还可以将 $profile_picture 变量初始化为默认图片,以防数据库没有返回任何内容
    • 谢谢。我得到了它的工作。我的愚蠢错误,在发布问题之前没有注意到它。再次感谢@guy ribak...
    猜你喜欢
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多