案例1:查询select
使用php连接数据库class9,
获取数据库的表student中的信息,
然后输出到页面上(用表格套住)
1 <?php 2 header("Content-type:text/html; charset=utf-8"); 3 // 建立mysql的链接 4 // 参数:主机名,用户,密码,需要的数据库 5 /* 6 在PHP函数方法前面加@符号,表示忽略警告 7 */ 8 $conn =@mysqli_connect("localhost","root","","lanou0322"); 9 // 判断数据库链接是否成功 10 /*if($conn){ 11 echo "成功了!"; 12 }else{ 13 echo "失败了!"; 14 } 15 */ 16 if(!$conn){ 17 echo "失败"; 18 // 终止 19 exit; 20 } 21 $conn->query('set names utf8'); 22 $sql ="SELECT * FROM student"; 23 $result = $conn->query($sql); 24 // 5.判断 25 // mysqli_num_rows 返回的条数 26 // echo mysqli_num_rows($result); 27 if(mysqli_num_rows($result)>0){ 28 echo "<table border=1>"; 29 echo "<tr> 30 <th>id</th> 31 <th>name</th> 32 <th>sex</th> 33 <th>age</th> 34 </tr>"; 35 while($row = $result -> fetch_assoc()){ 36 echo "<tr> 37 <td style='width:20'>{$row['id']}</td> 38 <td style='width:80; text-align:center;'>{$row['name']}</td> 39 <td style='width:20'>{$row['sex']}</td> 40 <td style='width:20'>{$row['age']}</td> 41 </tr>"; 42 } 43 echo "</table>"; 44 //如果想在一个页面输出同样的两个数据库表格那么可以在执行一次$conn->query($sql);然后打印 45 echo "<hr/>"; 46 $result = $conn->query($sql); 47 echo "<table border=1>"; 48 echo "<tr> 49 <th>id</th> 50 <th>name</th> 51 <th>sex</th> 52 <th>age</th> 53 </tr>"; 54 while($row = $result -> fetch_assoc()){ 55 echo "<tr> 56 <td style='width:20'>{$row['id']}</td> 57 <td style='width:80; text-align:center;'>{$row['name']}</td> 58 <td style='width:20'>{$row['sex']}</td> 59 <td style='width:20'>{$row['age']}</td> 60 </tr>"; 61 } 62 echo "</table>"; 63 } 64 // 关闭数据库 65 $conn->close();//关闭数据库 66 67 ?>
效果: