PHP数组mysql检索每条记录(第2部分)

时间:2015-01-13 07:17:21

标签: php mysql

  • 数据库(书表)
    serialID价格
    0001 10.00
    0001 30.00
    技术15.00
    0004(A)9.00
    0004(B)5.00
    0005 3.00
    (注:0003无记录)

  • 代码

    $serialID = array("0001","0002","0003","0004","0005");
    
    //DB Connection
    for($i = 0; $i < count($serialID); $i++)
    {
        $q = "select * from book where serial like \"$serialID[$i]%\" limit 1";
        $r = mysqli_query($dbc,$q);
    
        while($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
        {
              $serial[$i] = $row['serial'];
              $price[$i] = $row['price'];
              echo $serial[$i].' '.$price[$i];
        }
    }
    
    //pass db value into array
    for($j = 0; $j < count($serialID); $j++)
    {
         $data[$j] = array($serialID[$j],$price[$j]); 
    }
    
  • 这次我的问题是如何跳过serialID 0003 值?

  • 我的预期输出:(echo $ serial [$ i]。''。$ price [$ i])
    0001 10.00
    技术15.00
    0003
    0004(A)9.00
    0005 3.00

4 个答案:

答案 0 :(得分:0)

只需在for循环中检查它。使用以下代码

   $serialID = array("0001","0002","0003","0004","0005");

//DB Connection
for($i = 0; $i < count($serialID); $i++)
{
    $q = "select * from book where serial like \"$serialID[$i]%\" limit 1";
    $r = mysqli_query($dbc,$q);

    while($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
    {
          $serial[$i] = $row['serial'];
if($serialID=="0003"){
          $price[$i] = $row['price'];
    }
          echo $serial[$i].' '.$price[$i];
    }
}

//pass db value into array
for($j = 0; $j < count($serialID); $j++)
{
     $data[$j] = array($serialID[$j],$price[$j]); 
}

希望这有助于你

答案 1 :(得分:0)

将上一个循环修改为

for($j = 0; $j < count($serialID); $j++)
{
if(null != $price[$j]){
     $data[$j] = array($serialID[$j],$price[$j]); 
    }
}

但我的问题是,在循环中查询某些内容并不是自杀?也许你应该使用“IN”声明?还是“或”? 例如:

foreach($serialId as $id){
  $string.= ' %'.$serialId. ' % OR '; //of course you should check if this is first or last cell in array. So you don’t add unnecessary OR or space
}
select * from book where serial like \"$string\" limit 1

答案 2 :(得分:0)

我认为此代码可以更好地满足您的需求:

$serialID = array("0001", "0002", "0003", "0004", "0005");

//DB Connection
foreach ($serialID as $serialItem) {
    $q = "select * from book where serial like \"$serialItem%\" limit 1";
    $r = mysqli_query($dbc, $q);

    while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
        if (count($row) > 0) {
            echo $row['serial'] . ' ' . $row['price'];

            //pass db value into array
            $data[] = array(
                'serial' => $row['serial'],
                'price'  => $row['price']
            );
        }
    }
}

// debug output
print_r($data);

答案 3 :(得分:0)

$serialID = array("0001","0002","0003", "0004","0005");

$preparing = [];
foreach($serialID as $value) {
 $preparing[] = "'" . $value . "'";
}

$sql = "select * from book where serial IN (" . implode(',', $preparing) . ")";
$query = mysqli_query($sql);

$data = mysqli_fetch_all($query, MYSQLI_ASSOC);