sql查询和while循环,可以确定行数

时间:2018-02-21 13:03:40

标签: php mysql

我希望我知道从哪里开始实际发布查询和while循环示例;然而, 我以前从未做过这样的事情。

我有一个存储html所有信息的数据库  表

在while循环期间,我需要query / while循环来计算每个“width”列具有每个唯一值的次数,并按大小和厚度排序,以便它们按顺序一起显示。然后,在while循环中,我需要根据每个唯一值在数据库中的次数自动设置rowspan。

数据库

name    width   thickness    price
item1   2 x 2     .020        $25
item3   1 x 3     .030        $30
item2   2 x 2     .025        $28
item4   2 x 5     .040        $40

html视图

name   |  Width    |  Thickness     |  Price
--------------------------------------------------
item1  |           |   .020       |    $25
-------    2 x 2   -------------------------------
item2 |            |   .025       |    $28
--------------------------------------------------
item3 |    1 x 3   |  .030        |    $30
--------------------------------------------------
item4 |    2 x 5   |   .040       |    $40

注意在数据库中检测到宽度2 x 2两次,因此item1上的rowspan宽度设置为“2”

我最近开始在我的一些while循环中使用以下代码,也许这可以合并,并为某人如何做到这一点。

$firstoccurance = array();
if (!in_array($result['column'], $firstoccurance)) {
if (count($firstoccurance > 1)) { echo 'blah blah blah'; }
echo $result['column'];
$firstoccurance[] = $result['column'];
}

更新

我得到了@ADyson的含义。我喜欢在收集所有数据后设置变量并延迟表的构建直到while循环之后的想法;但是,我无法理解如何以这种方式建立这样做。这是一个伟大的概念;然而,我之前从未做过这样的事情,所以它有点过头了。每当我开始尝试构建变量时,我遇到了障碍,无法掌握如何通过它。如果有人能够根据问题中上面列出的例子来设计基础,我会很高兴。这既适用于学习,也适用于我目前正在进行的设计,因此我无法永远延迟这一点。关于如何设置它,我只是有点过头了。

<?php
$cp_query = $db1q->query("SELECT sku,size,length,thickness,quantity_per_carton,weight_per_carton,cost,margin,price FROM Corner_Protectors WHERE subcat=$subcat AND visibility='1' ORDER BY size,length,thickness") or die ('Unable to execute query. '. mysqli_error($db1q));
if ($cp_query->num_rows > 0) {

    $sizes = array();


    while ($cp = $cp_query->fetch_assoc()) {


// add sizes into array
if (!in_array($cp['size'], $sizes)) { $sizes[] = $cp['size']; }







    }
}



?>

1 个答案:

答案 0 :(得分:1)

我首先要按&#34; width&#34;来命令查询。列,然后行以与您想要显示它们相同的顺序出现。然后,您可以在循环中继续前进,直到宽度值从先前的值更改,然后决定是创建新单元格,还是添加rowspan。

为了帮助解决这个问题,您应该延迟完全构建最终的HTML字符串,直到您知道所有需要知道的内容。而是创建一个变量(或多个变量,根据需要)来存储HTML,然后使用逻辑来改变所创建的内容,并在最后将它们连接在一起,并回显最终字符串,而不是回显当你一起去。

这是一个解决方案。可能有更有效/更简洁的方法来做到这一点,但它是我能在短时间内得出的。请注意,我已使用示例虚拟数据替换了您的数据库代码,但原理是相同的。

<?php
//dummy data array instead of your database output, expanded a little to help with testing:
$data = array(
  array("name" => "item1", "size" => "2 x 2", "thickness" => ".020", "price" => "$25"),
  array("name" => "item2", "size" => "2 x 2", "thickness" => ".025", "price" => "$28"),
  array("name" => "item6", "size" => "2 x 2", "thickness" => ".080", "price" => "$50"),
  array("name" => "item3", "size" => "1 x 3", "thickness" => ".030", "price" => "$30"),
  array("name" => "item4", "size" => "2 x 5", "thickness" => ".040", "price" => "$40"),
  array("name" => "item5", "size" => "2 x 5", "thickness" => ".050", "price" => "$43")
);

$output = array(); //this is ready to hold the table cells
$prevSizeVal = null; //holds the size value from the previous row
$sizeStartRow = 0; //keep track of the row where a rowspanned size cell started

//this is in place of your while loop, you won't need totalRows because the fetch_assoc function takes care of this for you. This is just for the mockup.
$counter = 0; 
$totalRows = count($data);

while ($counter < $totalRows) {
  $cp = $data[$counter]; //to get an equivalent row variable that the fetch_assoc loop gives you
  $row = array(); //create a new output row

  //get the boring ones out of the way
  $row[0] = "<td>".$cp["name"]."</td>";
  $row[2] = "<td>".$cp["thickness"]."</td>";
  $row[3] = "<td>".$cp["price"]."</td>";

  $sizeCol = "";

  //now for the fun part with the size column
  if ($prevSizeVal != $cp["size"]) {
      $sizeStartRow = $counter;
      $sizeCol = '<td rowspan="1">'.$cp["size"].'</td>';
  }
  else
  {
      //change the rowspan value at the start position, as we know it's increased
      $output[$sizeStartRow][1] = preg_replace('/rowspan="[\d]+"/', 'rowspan="'.($counter-$sizeStartRow +1).'"', $output[$sizeStartRow][1]);
  }

  $row[1] = $sizeCol;

  $output[$counter] = $row; //add the row to the output. We may change the rowspan of the size cell later.
  $prevSizeVal = $cp["size"]; //update the previous size value
  $counter++;
}

//now we've built the output array of cells, we can echo them into a table.
echo "<table>";
echo "<th>Name</th><th>Size</th><th>Thickness</th><th>Price</th>";
//loop the rows
for ($i = 0; $i < count($output); $i++) {
  echo "<tr>";
  //loop the cells within the current row
  for ($j = 0; $j < count($output[$i]); $j++)
  {
    $cell = $output[$i][$j];
    echo $cell; //some variables will be empty (because we didn't create them because we knew there was a row-spanned cell above them, so nothing will be echoed in those cases
  }
  echo "</tr>";
}
echo "</table>";
?>

有关工作演示,请访问https://eval.in/961226

需要说明的是,上述内容旨在提供一个有效的演示。要将其集成到原始代码中,请按如下所示进行编写(您可能需要更改某些字段名称以匹配,但不清楚哪些字段名称与示例输出表中的描述完全匹配):

$output = array(); 
$prevSizeVal = null; 
$sizeStartRow = 0; 
$counter = 0;

$cp_query = $db1q->query("SELECT sku,size,length,thickness,quantity_per_carton,weight_per_carton,cost,margin,price FROM Corner_Protectors WHERE subcat=$subcat AND visibility='1' ORDER BY size,length,thickness") or die ('Unable to execute query. '. mysqli_error($db1q)); 

if ($cp_query->num_rows > 0) { 
while ($cp = $cp_query->fetch_assoc()) {

  $row = array(); //create a new output row

  //get the boring ones out of the way
  $row[0] = "<td>".$cp["name"]."</td>";
  $row[2] = "<td>".$cp["thickness"]."</td>";
  $row[3] = "<td>".$cp["price"]."</td>";

  $sizeCol = "";

  //now for the fun part with the size column
  if ($prevSizeVal != $cp["size"]) {
      $sizeStartRow = $counter;
      $sizeCol = '<td rowspan="1">'.$cp["size"].'</td>';
  }
  else
  {
      //change the rowspan value at the start position, as we know it's increased
      $output[$sizeStartRow][1] = preg_replace('/rowspan="\d"/', 'rowspan="'.($counter-$sizeStartRow +1).'"', $output[$sizeStartRow][1]);
  }

  $row[1] = $sizeCol;

  $output[$counter] = $row; //add the row to the output. We may change the rowspan of the size cell later.
  $prevSizeVal = $cp["size"]; //update the previous size value
  $counter++;
}

//now we've built the output array of cells, we can echo them into a table.
echo "<table>";
echo "<th>Name</th><th>Size</th><th>Thickness</th><th>Price</th>";
//loop the rows
for ($i = 0; $i < count($output); $i++) {
  echo "<tr>";
  //loop the cells within the current row
  for ($j = 0; $j < count($output[$i]); $j++)
  {
    $cell = $output[$i][$j];
    echo $cell; //some variables will be empty (because we didn't create them because we knew there was a row-spanned cell above them, so nothing will be echoed in those cases
  }
  echo "</tr>";
}
echo "</table>";
}