dqk77945 2014-11-26 20:21
浏览 63
已采纳

在PHP中调用(循环)MySQL行列表会产生意外结果

Two snippets of PHP code:

The first one works fine, giving values from different rows sequentially.

while ($row = mysql_fetch_assoc($rst)) {
...
$link1 = $row['audio1'];
    if ($link1) {
    $link1 = $link1;
    }
...
}

The second one outputs the value from the first row and applies it to every subsequent row.

while ($row = mysql_fetch_assoc($rst)) {
...
if ($row['audio1']) {
    $link1 = $row['audio1'];
    }
...
}

I.e. where the first code sample generates

Audio1.mp3
Audio2.mp3
Audio3.mp3

the second one would generate

Audio1.mp3
Audio1.mp3
Audio1.mp3

The question is why those two similar implementations differ in output.

Another test case with ...s removed (clean loop code) yields a different picture: the first example only outputs one line (the first one), the second example's output is the same which is repeating lines.

MySQL table that is being used has the following structure: One table, INT (id), CHAR, SMALLINT, TINYTEXT, TEXT, TEXT, TINYTEXT (audio1). All of the rows are fully populated except for the last one (audio1) which is mostly empty and has non-NULL values somewhere in the middle (if we sort by id field). Replacing the 'audio1' with another column name yields correct results (for that field) in both cases.

Another addition is that I do indeed place a SELECT statement initially in mysql_query that filters out rows. Depending on the number of rows being returned the picture for the second example may be slightly different, like 3 non-repeating values followed by a repetition of the third value until the end.

  • 写回答

1条回答 默认 最新

  • dongnaigu2052 2014-12-05 22:40
    关注

    I fixed it. Long story short - it was really obvious: between loop cycles $link1 variable didn't change in case if wasn't true. What I needed to do was to put $link1 = ""; or unset ($link); right after while and in that case if I ever encountered an empty value for $row['audio1'] it would stay truly empty instead of reusing the old value for every new row.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算