根据变量中的值显示不同的图像

时间:2013-08-12 17:59:13

标签: php mysql image variables

只是想确保我朝着正确的方向前进。如果变量的值为0/1,我有一个想要替换/更改的图像。所以这是来自服务器端的人的代码。

<?php
//Requires mysql_connect to create the connection

$link_state = 0;

//If you so wish you don't have to check for a connection, but may be a good idea leave this in.
if ($mysql_connection['connected'] == true) {
    $result = mysql_query("SELECT * FROM link");
    //The bit we are looking for should be the first row, and we should only get one row
    $count  = mysql_num_rows($result);
    if ($count <= 0) {
        //Interesting...
        $mysql_error['error']       = true;
        $mysql_error['description'] = "ERROR: No rows were returned from table 'link'";
    } else {
        //We should be ok to continue
        if ($count > 1) {
            $mysql_error['error']       = true;
            $mysql_error['description'] = "WARNING: Found more than one row in 'link' table!";
        }
        $row        = mysql_fetch_array($result);
        $link_state = intval($row['state']);
    }
} else {
    $mysql_error['error']       = true;
    $mysql_error['description'] = "ERROR: No mysql connection!";
}

/*
After the completion of this page, $link_state will be one of two things:

* 0 = offline
* 1 = online

Throws to $mysql_error:

1 Warning
2 Errors

*/
?>

好的,所以我假设只需要一点点代码,然后我就会在$ link_state中得到0或1的值。

那么我可以通过这样做一个简单的内联脚本来获取我的相关图像吗?

<img src="img/<?=($link_state=="0"?"off.jpg":($link_state=="1"?"on.jpg":))?>" />

任何见解都会很棒:)

提前致谢。

1 个答案:

答案 0 :(得分:1)

试试这个

<?php $img = ($link_state == "0") ? "off.jpg" : "on.jpg"; ?>

<img src="./img/<?php echo $img; ?>" />

也使用mysqli_*,因为mysql_*已弃用。