for循环与if语句重写PHP

时间:2014-02-21 10:59:12

标签: php mysql

我有这段PHP代码:

for($i=0;$i<$rowsize;$i++) {

            if($i == $object_id) {

                if ($stmt = $mysqli->prepare('SELECT x, y, src FROM house_room1 INNER JOIN objects ON house_room1.object_id=objects.object_id WHERE ref_id = ?')) {

                /* Bind parametres */
                $stmt->bind_param('i', $ref_id);

                /* Insert the parameter values */
                $ref_id = $i;

                /* Execute the query */
                $stmt->execute();

                /* Bind resultatet */
                $stmt->bind_result($x, $y, $src);

                /* Close statement */
                $stmt->close();

                } else {
                /* Something went wrong */
                echo 'Something went terrible wrong'     . $mysqli->error;
                }
                echo '<img src="'.$src; echo '"class="item" style="position:relative; left:'.$x; echo 'px; top:'.$y; echo 'px;">';

            }
        }

此代码以for循环开始,循环遍历当前包含两行的数据库表。虽然它这样做,但它表示如果变量$i等于数据库中的对象id,则执行此查询,该查询从中查找srcxy数据库。之后,它会在图像中插入这些值,以使图像显示在页面上。然而,即使它必须经过两行,因此必须显示两个图像,它就像是覆盖第一个图像,因为只显示最后一个图像。我认为这与我的PHP逻辑有关,但我无法弄清楚如何在没有被覆盖的情况下显示两个图像。提前谢谢。

1 个答案:

答案 0 :(得分:1)

<?php
$stmt = $mysqli->stmt_init();
$stmt->prepare('SELECT x, y, src FROM house_room1 INNER JOIN objects ON house_room1.object_id=objects.object_id WHERE objects.object_id = ?'); 
$stmt->bind_param('i', $object_id);
if ($stmt->execute()) {
    $stmt->bind_result($x, $y, $src);
    while($stmt->fetch()) {
        echo '<img src="' . $src . '" class="item" style="position:relative; left:' . $x . ' px; top:' . $y . 'px;">';
    }
} else {
    echo 'Something went terrible wrong' . $mysqli->error;
}
$stmt->close();
?>