php mysqli 循环太多结果

标签 php mysql mysqli

我在循环数据库检索结果时遇到了一个小问题,我明白为什么会遇到这个问题,但不太确定如何实现该解决方案,因为我的 PHP 不是最好的。 我浏览了论坛,但找不到任何可以解决我的问题的内容。

从下面我的输出会给我 12 个结果,而我只想要 6 个结果,每个结果 2 个:每个循环计算数组中的 12 个项目,这是有意义的,所以它会输出 12 次,给我每个结果的重复项。我该如何最好地处理这个问题。

    MyTable1:                          myTable2:
    |   ID   |  Name  |           | NameID   |       Details     |   
    |--------|--------|           |----------|-------------------|
    |   0    | bob    |           |   0      | lives in the city |
    |   1    | david  |           |   1      | lives in a caravan|
    -------------------           --------------------------------

我的 MSQLI 查询:

     $qryRandom   =  "SELECT  MyTable1.ID,  MyTable2.Details
                      FROM  MyTable1
                      INNER JOIN  MyTable2
                      ON MyTable1.ID=MyTable2.NameID 
                      ORDER BY RAND()
                      LIMIT 6;";

我的 PHP(一般示例)。

    $resultR= $con->query($qryRandom) or die($mysqli->error.__LINE__);
    while($row = mysqli_fetch_array($resultR, MYSQL_ASSOC))
    {
    foreach ( $row as $key=>$value ){ // loops 12 times here as there is 6 items x 2 values
    echo $key.": ".$value."<br>";

    }

 }

结果输出:

    bob lives in city
    bob lives in city
    David lives in caravan
    David lives in caravan
    john lives in the car 
    john lives in the car  // doubles of each entry is my issue
   // hope I was thorough and provided enough info for my scenario. 

最佳答案

我想出的解决方案有效,但我仍然不满意;

   while($row = mysqli_fetch_array($resultR, MYSQL_ASSOC))
   {
    for ($i = 0; $i<1;$i++){
    echo $row['name'].$row['details']."<br>";
    }
    }

我更加确定有更好的方法来解决这个问题。

关于php mysqli 循环太多结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19743255/

相关文章:

php - PHP 中的 mysql_query 包含返回 mysql 错误的变量

php - 正在合并单独的电子邮件

javascript - Ajax - 在搜索字段清空后重新加载 div 中的先前数据

MySQL:从函数调用存储过程

php - MySQL num_rows 不返回值(SELECT INTO)

尝试创建过程时 MySQL 抛出错误 "Statement is incomplete expecting if"

mysql - 我应该标准化这些字段吗?

php - php中的对象问题

php - XAMPP mailtodisk 功能

PHP Regex 将单词列表与字符串匹配