<?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个单独的select语句,其中只有“ type”改变。 返回的值稍后将在其他代码中使用。 我可以上所有3种类型只有1条陈述的课程吗? 稍后在:
中使用<?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>';}
?>
我本人对此感到困惑,因此不胜感激
答案 0 :(得分:1)
第一种方法。使用循环:
$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);
我确实在这里编写了代码。没有测试。如果我是你,我会使用第一种方法
PS。当然,您必须在所有三种方法中都指定$ db。