如何在连接数据库 connected/not 时使用 MySQL/PHP 显示不同的图像?

How do I display different images using MySQL/PHP when database connected/not connected?

我是 PHP 和 MYSQL 的新手,我有一个我认为相对简单的问题。

我的objective是连接数据库时显示一张图片(绿灯快闪),没有数据库连接时显示另一张图片(红灯快闪)

我想这应该是一个简单的变体:

<?php
$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
?>

但是,如果我尝试将图像添加到回显的位置 "Connected successfully",我会收到错误消息。

我正在尝试添加这样的图片:

<?php
$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("<img src="Red_Light.gif" style="width:10px;height:10px;"> " . $conn->connect_error);
} 
echo "<img src="Green_Light.gif" style="width:10px;height:10px;">";
?>

我的语法可能完全错误,但如有任何帮助,我们将不胜感激。

非常感谢, 莱夫

if ($conn->connect_error) {
    die("<img src=\"Red_Light.gif\" style=\"width:10px;height:10px;\"> " . $conn->connect_error);
} 
echo "<img src=\"Green_Light.gif\" style=\"width:10px;height:10px;\">";

整个问题似乎与不转义引号有关。

您可以使用 Janno answer 或者您可以使用这个(通过将 " 更改为 ':-

if ($conn->connect_error) {
die("<img src='Red_Light.gif' style='width:10px;height:10px;'> " . $conn->connect_error);
} 
echo "<img src='Green_Light.gif' style='width:10px;height:10px;'>";