douyinjiao9351 2011-06-10 14:28
浏览 57

对mysql查询的每个单独结果使用while语句

I'm unsure whether to use 'while' or 'for each' for this code.

I have a mysql query that will bring back more then one result.

I then, for each result, want to do a certain thing if $row[number] is empty or not

I have this:

$sql = "SELECT * FROM $tbl_name WHERE username=\"$myusername\"";
$result=mysql_query($sql);
$numResults = mysql_num_rows($result);
if ($numResults = 0) {
header ("Location: /sms_error.php?error=no_adders");
}
while($row = mysql_fetch_array($result)) {
$number1=$row["number"];
if (!empty($number1)) {


}

if (empty($number1)) {


}

This is coming up with completely blank for $number1 (even though there is data on the db).

Everything up to that is correct, $myusername and the mysql query doesn't return empty.

So should it be mysql-fetch-assoc or -array and should it be while or for each??

thanks, Niall

  • 写回答

2条回答 默认 最新

  • douxiong2999 2011-06-10 14:34
    关注

    First, you have problem in this line of code:

    if ($numResults = 0) {
        header ("Location: /sms_error.php?error=no_adders");
    }
    

    This is always false - you are not comparing, you are assigning 0 to $numResults. Change that to == and see if you are having any rows pulled out with your query.

    while($row = mysql_fetch_array($result)) {
    $number1=$row["number"];
    //...
    }
    

    This is a valid syntax, as I can see. Try to call var_dump($row) to see contents of $row array.

    Edit:

    Oh, yeah - instead of this:

    $result=mysql_query($sql);
    

    do this:

    $result=mysql_query($sql) or die(mysql_error());
    

    One more suggestion - you should always call exit(); after header("Location: ..."); to prevent executing code after redirect line in your script, because header only asks user browser to redirect.

    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么