MYSQLI - 每次运行增量查询WHERE值

时间:2017-12-10 15:38:18

标签: php mysql mysqli auto-increment

我希望看看是否可以增加 $tid每次{1}},因此$tid = 1, 2, 3, 4, 5, etc...

$tid将计算表的行数,因此$tid=1将回显第1行信息,$tid=2将回显第2行信息,依此类推。虽然我可能觉得这不是最好的解决方案,但如果有人能提出一个更优先的替代方法来做到这一点,那就太好了。

TL:DR :我只想找到一种方法,我可以使用下面的代码示例循环遍历s_id = $tid的所有行

$tid = 1;

$query2 = "SELECT * FROM `SALE` 
 LEFT JOIN `SALE_ROW` 
   ON `SALE_ROW`.s_id=`SALE`.s_id 
 WHERE `SALE_ROW`.s_id = {$tid}";
$results2 = mysqli_query($dbconnection, $query2);
while ($row = mysqli_fetch_array($results2)) {

    echo '<div class="pphhold">';

    echo '<div class="pcdtstlye">Previous Details</div>';

    echo  '<div> s_id: ' . $row['s_id'] .'</div>';
    echo  '<div> p_id: ' . $row['p_id'] .'</div>';
    echo  '<div> sr_qty: ' . $row['sr_qty'] .'</div>';
    echo  '<div> s_total: ' . $row['s_total'] . '</div>';
    echo  '<div> s_date: ' . $row['s_date'] . '</div>';

    echo '</div>';

};

2 个答案:

答案 0 :(得分:1)

在您的代码中,您正在循环外执行MySQL查询。它将执行一次然后循环结果。如果要更改查询(我假设$tid是查询的参数)并且想要获取已更改查询的输出,则必须再次执行查询。如果您知道$tid的所有可能值,则可以采用以下方式:

$tids = [1, 2, 3];
foreach($tids as $tid) {
  $query2 = "SELECT * FROM `SALE` LEFT JOIN `SALE_ROW` ON `SALE_ROW`.s_id=`SALE`.s_id WHERE `SALE_ROW`.s_id = {$tid}";
  $results2 = mysqli_query($dbconnection, $query2);
  $row = mysqli_fetch_array($results2);

  echo '<div class="pphhold">';

  echo '<div class="pcdtstlye">Previous Details</div>';

  echo  '<div> s_id: ' . $row['s_id'] .'</div>';
  echo  '<div> p_id: ' . $row['p_id'] .'</div>';
  echo  '<div> sr_qty: ' . $row['sr_qty'] .'</div>';
  echo  '<div> s_total: ' . $row['s_total'] . '</div>';
  echo  '<div> s_date: ' . $row['s_date'] . '</div>';

  echo '</div>';
}

但这并不好,因为你必须多次执行查询。所以只需使用IN

$tids = [1, 2, 3];
$query2 = "SELECT * FROM `SALE` LEFT JOIN `SALE_ROW` ON `SALE_ROW`.s_id=`SALE`.s_id WHERE `SALE_ROW`.s_id IN(" . implode(',', $tids) . ")";
$results2 = mysqli_query($dbconnection, $query2);
while($row = mysqli_fetch_array($results2)) {
  echo '<div class="pphhold">';

  echo '<div class="pcdtstlye">Previous Details</div>';

  echo  '<div> s_id: ' . $row['s_id'] .'</div>';
  echo  '<div> p_id: ' . $row['p_id'] .'</div>';
  echo  '<div> sr_qty: ' . $row['sr_qty'] .'</div>';
  echo  '<div> s_total: ' . $row['s_total'] . '</div>';
  echo  '<div> s_date: ' . $row['s_date'] . '</div>';

  echo '</div>';
}

答案 1 :(得分:-1)

使用此函数通过此

获取行数
 $query2 = "SELECT * FROM `SALE` LEFT JOIN `SALE_ROW` ON `SALE_ROW`.s_id=`SALE`.s_id WHERE `SALE_ROW`.s_id = {$tid}";

$results2 = mysqli_query($dbconnection, $query2);
$count=mysqli_num_rows($results2);

现在count有结果计数

从查询中查找获取计数值:

$result = mysqli_query($dbconnection,"select count(1) FROM table");
$row = mysqli_fetch_array($result);

$count = $row[0];