使用foreach获取数据列表的全部信息

先把代码列出来:(在admin/listAdmin.php中)

                      <?php foreach($rows as $row):?>  //注意,这里的foreach($rows as $row)后面的是冒号不是逗号
                            <tr>
                                <!--这里的id和for里面的c1 需要循环出来-->
                                <td><input type="checkbox" id="c1" class="check"><label for="c1" class="label"><?php echo $row['id'];?></label></td>
                                <td>x</td>
                                <td>x</td>
                                <td align="center"><input type="button" value="修改" class="btn" ><input type="button" value="删除" class="btn"  ></td>
                            </tr>
                        <?php endforeach ?>  

通过foreach()函数,将后台管理员的的所有用户都列出来了

而$rows是一个函数:(在admin/listAdmin.php中)

<?php
include '../include.php';
$rows=getAllAdmin();
if(!$rows) {
	alertMes("sorry,没有管理员,请添加!","addAdmin.php");
	exit;
}

?>

 getAllAdmin()函数为:(core/admin.inc.php中)

function getAllAdmin() {
	$sql="select id,username,email from imooc_admin";
	$rows=fetchAll($sql);
	return $rows;	
}

 fetchAll()的函数为:(在lib/mysql.func.php中)

function fetchAll($sql,$result_type=MYSQL_ASSOC){
	$result=mysql_query($sql);
	while(@$row=mysql_fetch_array($result,$result_type)){
		$rows[]=$row;
	}
	return $rows;
}
alertMes()函数:(在lib/common.func.php中)
<?php

function alertMes($mes,$url) {
	echo "<script>alert('{$mes}');</script>";
	echo "<script>window.location='{$url}';</script>";
}


?>


 <?php if($rows>$pageSize):?>
       <tr>
         <td colspan="4"><?php echo showPage($page,$totalPage); ?></td>
       <tr>
 <?php endif;?>

 这里与上面无关,唯一有关的是<?php if($rows>$pageSize):?>中if($rows>$pageSize)后面的也是冒号

这是在学习慕课网中的《手把手叫你做电商后台网站开发》中看到的,老师的代码逻辑性的确非常好。

原文地址:https://www.cnblogs.com/jacson/p/4242758.html