drm16022 2014-04-08 16:09
浏览 136
已采纳

Php for循环和mysql查询

I'm running a second database search using mysql inside a for loop but I can't get it show the correct amount of rows:

Original search:

    $topicemailsql = "select se.id as id, se.users as users, se.topic as topic, se.body as body, se.postID as postID, DATE_FORMAT(se.sent, '%d.%m.%Y %H:%i:%s' ) as sent, (SELECT u.email from users u where u.users_id in (se.users)) as emails from sentEmail se LEFT OUTER JOIN topics t on (t.ID = se.theader_) where t.ID = '$topicID'";
$topicemailsqlquery = mysql_query($topicemailsql)or die(mysql_error());

$numrows = mysql_num_rows($topicemailsqlquery);

php for loop:

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

    $sqlarray = mysql_fetch_array($topicemailsqlquery);
    $users = $sqlarray['users'];
    $sqlemail = ('select email from users where users_id in ("'.$users.'")');
    //echo $sqlemail;
    $emailsqlquery = mysql_query($sqlemail)or die(mysql_error());
    $amountofusers = mysql_num_rows($emailsqlquery);
    $sqlarrayemail = mysql_fetch_array($emailsqlquery);
    echo $amountofusers;
//echo $sqlarrayemail['email'];

    for ($a=0; $a < $amountofusers ; $a++){
        if($a == 0){
         $email = $sqlarrayemail['email'];
    }
        else if($a < $amountofusers){
        $email = $sqlarrayemail['email'].','.$sqlarrayemail['email'];
        }
        }
}

So based on this the $amountofusers should return more than 1 row but now it always return only one row. When I echo the $sqlemail it should return 2 rows because it looks like this: select email from users where users_id in ("4,82") --> this should return 2 rows and a count of 2 but it only returns one row.

Where does it go wrong?

Br, Toby

  • 写回答

1条回答 默认 最新

  • dongye6377 2014-04-08 16:45
    关注

    I think, it's a very bad idea to store multiple values in one field. Furthermore I wouldn't fire up queries in a loop, if I can avoid it. Better fetch the data in one go and let PHP do the rest. If you try your query i.e. with PHPAdmin you would use

    SELECT email 
    FROM users 
    WHERE users_id IN (4, 82)
    

    The IN operator needs a comma separated list of arguments. You give one single value

    "4,82"
    

    That's a huge difference. MySQL would accept ("4","82") too (other DBMS are not as tolerant) and handle the not needed conversion for you.

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

报告相同问题?

悬赏问题

  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型