简体   繁体   English

PHP while 循环不起作用

[英]PHP while loop isn't working

I'm new to PHP and trying to produce numbers like this in a loop which is already being used in fetching the data from database table.我是 PHP 新手,并试图在循环中生成这样的数字,该循环已用于从数据库表中获取数据。

$i= 1;
while($row = $result1->fetch_assoc()) {
/////////////////other codes
<img src="$i.jpg">
$i++;}

I want to stop the loop as long there are rows in the table.只要表中有行,我就想停止循环。
Error:错误:
It produces two, three images according to the number of rows but all images have source 1.jpg它根据行数生成两个、三个图像,但所有图像都有源 1.jpg

Sorry this isn't an answer to your problem, but it's the only answer possible at the moment:抱歉,这不是您问题的答案,但这是目前唯一可能的答案:

This works for me:这对我有用:

<?php

$rows = [
    'item',
    'item',
    'item',
    'item'
];

function fetch() {
    global $rows;

    return count($rows) > 0 ? array_splice($rows,0,1)[0] : null;
    //Should match return behavior of fetch assoc according to: http://php.net/manual/en/mysqli-result.fetch-assoc.php
}

/**///Remove a star to toggle methods

$i = 1;
while($row = fetch()) {
    echo "$i<br>";
    $i++;
}

/*/

//Alternative method:

for ($i = 1; $row = fetch(); $i++)
    echo "Alt: $i<br>";

//*/

That outputs:输出:

1
2
3
4

So the issue isn't with the code you shared.所以问题不在于您共享的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM