围绕 SELECT 语句中的一个特定结果添加代码


Add code around one particular result from SELECT statement

我有以下代码从数据库中的"课程"表中选择标题和图像。

<?php
    $username = 'REMOVED';
    $password = 'REMOVED';
    try {
        $conn = new PDO('mysql:host=localhost;dbname=REMOVED', $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    
        $stmt = $conn->prepare('SELECT Title, Image FROM Courses');
        $stmt->execute();
        while($row = $stmt->fetch()) {
            print_r($row);
        }
    }
    catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
?>

我怎样才能使标题周围有一个标题标签,并且图像位于图像 src=" 内?

根据您的PDO设置,结果可能会以关联数组的形式返回(这将是最常见的默认设置):

while($row = $stmt->fetch()) {
    echo '<img src="' . $row["Image"] . '" title="' . $row["Title"] . '">';
}

更新:要强制获取关联数组,只需将$stmt->fetch()替换为$stmt->fetch((PDO::FETCH_ASSOC)

将 while 循环替换为以下代码:

$string="<header>";
$imagesrc="";
While($row=$stmt->fetch()){
  $string+=$row['Title'];
  $imagesrc=$row['Image'];
}
$string+="</header>";
$stringImage="<img src='".$imagesrc."' />";