面向对象php中mysql类的创建

qxsslcnc  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(282)
<?php
 // Selects 1
$stmt = $db->prepare("SELECT * FROM mainInfo WHERE type='1' ORDER BY name");
$stmt->execute();
$resultSet = $stmt->get_result();
$result_1 = $resultSet->fetch_all();

// Selects 2
$stmt = $db->prepare("SELECT * FROM mainInfo WHERE type='2' ORDER BY name");
$stmt->execute();
$resultSet = $stmt->get_result();
$result_2 = $resultSet->fetch_all();

// Selects 3
$stmt = $db->prepare("SELECT * FROM mainInfo WHERE type='3' ORDER BY name");
$stmt->execute();
$resultSet = $stmt->get_result();
$result_3 = $resultSet->fetch_all();

我有3个seperate select语句,其中只有“type”更改。返回的值稍后在其他代码中使用。我是否可以创建一个类,其中所有3种类型只有一个语句,并在后面的中使用:

<?php foreach($result_1 as $item){
    echo '
      <div class="col-md-3">
        <div class="square">
          <input name="cb_id[]" class="checkBox" type="checkbox" 
    value="'.$item[0].'">
          <p>'.$item[0].' <br> ' . $item[1] .' <br> ' . $item[2] . 
    '$<br>Size: ' .$item[4] . ' MB</p>
        </div>
       </div>';}
  ?>

<?php foreach($result_2 as $item){
    echo '
      <div class="col-md-3">
        <div class="square">
          <input name="cb_id[]" class="checkBox" type="checkbox" 
 value="'.$item[0].'">
          <p>'.$item[0].' <br> ' . $item[1] .' <br> ' . $item[2] . 
 '$<br>Weight: ' .$item[5] . ' KG</p>
        </div>
      </div>';}
  ?>

  <?php foreach($result_3 as $item){
      echo '
        <div class="col-md-3">
          <div class="square">
            <input name="cb_id[]" class="checkBox" type="checkbox" 
   value="'.$item[0].'">
            <p>'.$item[0].' <br> ' . $item[1] .' <br> ' . $item[2] . 
   '$<br>Dim: ' .$item[6] . 'X' .$item[7] . 'X' .$item[8] . '</p>
          </div>
        </div>';}
    ?>

我自己对此感到困惑,所以任何帮助都是感激的

1cosmwyk

1cosmwyk1#

第一种方法。使用循环:

$results = [];
for ($i = 1; $i <= 10; $i++) {
  $stmt = $db->prepare("SELECT * FROM mainInfo WHERE type='$i' ORDER BY name");
  $stmt->execute();
  $resultSet = $stmt->get_result();
  array_push($results, $resultSet->fetch_all());
}

第二种方法。使用函数:

function returnResult($type){
  $stmt = $db->prepare("SELECT * FROM mainInfo WHERE type='$type' ORDER BY name");
  $stmt->execute();
  $resultSet = $stmt->get_result();
  return $resultSet->fetch_all();
}
$result1 = returnResult(1);
$result2 = returnResult(2);
$result3 = returnResult(2);

第三种方法oo-php

class Foo { 

  public function returnResult($type){
    $stmt = $db->prepare("SELECT * FROM mainInfo WHERE type='$type' ORDER BY name");
    $stmt->execute();
    $resultSet = $stmt->get_result();
    return $resultSet->fetch_all();)
  }
} 
$SomeObject = new Foo;
$result1 = $SomeObject->returnResult(1);
$result2 = $SomeObject->returnResult(2);
$result3 = $SomeObject->returnResult(3);

我确实在这里写了代码。没有测试。如果我是你,我会用第一种方法
当然,你必须在这三种方法中指定$db。

相关问题