在while语句中为图像添加alt

时间:2018-03-10 08:14:24

标签: php image alt

有人可以帮忙吗? 这是我的代码。我想为图片添加alt选项,但我尝试的一切都是抛出错误。 我曾尝试研究php手册,并尝试从其他问题复制代码,但到目前为止还没有运气。

<?php
$servername = "localhost";
$username = "logosewe_5";
$password = "password";
$dbname = "logosewe_5";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM mk2";

$sql = "SELECT * FROM mk2 WHERE brand='2786'";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo '<img src='$row['ming']'>';
    }
} else {
    echo "0 results";
}

$conn->close();
?>

3 个答案:

答案 0 :(得分:1)

您遇到string concatenation问题:

echo '<img src="' . $row['ming'] . '">';

将输出:<img src="myimage.jpg">

要添加alt属性,您可以执行以下操作:

echo '<img src="' . $row['ming'] . '" alt="' . $row['name'] . '">';

将输出类似

的内容
<img src="myimage.jpg" alt="image name">

答案 1 :(得分:0)

问题是你的echo语句中没有alt属性,第二个是你的串联错误引号错误。

while($row = $result->fetch_assoc()) {
echo '<img src=' . $row['ming'] .  'alt="Your alt message">';
}

答案 2 :(得分:0)

更改您的代码:

 <?php
    $servername = "localhost";
    $username = "logosewe_5";
    $password = "password";
    $dbname = "logosewe_5";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    } 

    $sql = "SELECT * FROM mk2"
    ;

    $sql = "SELECT * FROM mk2 WHERE brand='2786'";

    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
    echo '<img src="'.$row['ming'].'" alt="'.$altText.'">'; //change here
     }
    } else {
    echo "0 results";
    }
    $conn->close();
    ?>