这是我在class.php中的代码:
public function select(){
$stmt = $this->conn->prepare("SELECT country FROM `country`") or die($this->conn->error);
if($stmt->execute()){
$result = $stmt->get_result();
return $result;
}
}
public function read(){
$stmt = $this->conn->prepare("SELECT segment FROM `segments`") or die($this->conn->error);
if($stmt->execute()){
$result = $stmt->get_result();
return $result;
}
}
现在在index.php中我这样做了:
<th class="text-center">country</th>
<th class="text-center">segments</th>
</thead>
<tbody>
<?php
require 'class.php';
$conn = new db_class();
$read = $conn->select();
$test = $conn->read();
while($fetch = $read->fetch_array(MYSQLI_ASSOC)&& $fetch1 = $test->fetch_array(MYSQLI_ASSOC)){
foreach ($fetch1 as $field => $values) {
foreach($fetch as $field=>$value){
echo '<tr><td>' . $value . '</td>'
. '<td>'. $values .'</td>';
}
}
}
?>
</tbody>
</table>
我只是试图从2个表中获取数据并将它们放在一个html表中
我得到这个错误6次:
Warning: Invalid argument supplied for foreach() in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\segments\countrySegment.php on line 59
答案 0 :(得分:1)
这是因为数组指针问题
foreach ($fetch1 as $field => $values) {
foreach($fetch as $field=>$value){
echo '<tr><td>' . $value . '</td>'
. '<td>'. $values .'</td>';
}
}
第一次第二次foreach打印下一次没有任何值的东西它超出了值..
因此您需要使用重置
重置阵列foreach ($fetch1 as $field => $values) {
reset($fetch)
foreach($fetch as $field=>$value){
echo '<tr><td>' . $value . '</td>'
. '<td>'. $values .'</td>';
}
}
或者您可以将其保存为临时变量
foreach ($fetch1 as $field => $values) {
$fetchtmp = $fetch;
foreach($fetchtmp as $field=>$value){
echo '<tr><td>' . $value . '</td>'
. '<td>'. $values .'</td>';
}
}