当前位置:首页 > PHP教程 > php应用 > 列表

php7连接MySQL实现简易查询程序的方法

发布:smiling 来源: PHP粉丝网  添加日期:2022-03-28 11:50:49 浏览: 评论:0 

这篇文章主要给大家介绍了关于php7连接MySQL实现简易查询程序的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。

简易教程

假设我们制作的是分班情况查询程序,将使用PHP7的环境以PDO的方式连接MySQL。

通过学号和姓名查询自己所在班级。

先来介绍文件结构和数据库结构:

PHP:

config.php 存放数据库配置信息

cx.php 查询程序

index.html 用户界面

php7连接MySQL实现简易查询程序的方法

结构如图

MySQL:

表名:data

字段:1.Sid 2.name 3.class

php7连接MySQL实现简易查询程序的方法

结构如图

准备就绪,开始吧,现在!

首先构建用户界面(index.html),两个简单的编辑框加上一个简单的按钮:

  1. <!DOCTYPE html> 
  2. <html lang="cn"> 
  3. <head> 
  4.  <meta charset="UTF-8"> 
  5.  <title>分班查询系统</title> 
  6. </head> 
  7. <body> 
  8. <form action="cx.php" method="post"> 
  9.  <p>学号:<input type="text" name="xuehao"></p> 
  10.  <p>姓名: <input type="text" name="xingming"></p> 
  11.  <p><input type="submit" name="submit" value="查询"></p> 
  12. </form> 
  13. </body> 
  14. </html> 

好嘞,接下来配置数据库信息(config.php)吧

  1. <?php 
  2. $server="localhost";//主机的IP地址 
  3. $db_username="root";//数据库用户名 
  4. $db_password="123456";//数据库密码 
  5. $db_name = "data"; 

然后去编写我们的主程序(cx.php)

  1. <?php 
  2. header("Content-Type: text/html; charset=utf8"); 
  3. if(!isset($_POST["submit"])) 
  4. { 
  5.  exit("未检测到表单提交"); 
  6. }//检测是否有submit操作 
  7. include ("config.php"); 
  8. $Sid = $_POST['Sid'];//post获得学号表单值 
  9. $name = $_POST['name'];//post获得姓名表单值 
  10. echo "<table style='border: solid 1px black;'>"; 
  11. echo "<tr><th>学号</th><th>姓名</th><th>班级</th></tr>"; 
  12. class TableRows extends RecursiveIteratorIterator 
  13. { 
  14.  function __construct($it) 
  15.  { 
  16.   parent::__construct($it, self::LEAVES_ONLY); 
  17.  } 
  18.  
  19.  function current() 
  20.  { 
  21.   return "<td style='width:150px;border:1px solid black;'>" . parent::current() . "</td>"; 
  22.  } 
  23.  
  24.  function beginChildren() 
  25.  { 
  26.   echo "<tr>"; 
  27.  } 
  28.  
  29.  function endChildren() 
  30.  { 
  31.   echo "</tr>" . "\n"; 
  32.  } 
  33. } 
  34. try { 
  35.  $conn = new PDO("mysql:host=$server;dbname=$db_name", $db_username, $db_password); 
  36.  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
  37.  $stmt = $conn->prepare("SELECT Sid, name, class FROM data where Sid=$Sid and name='$name'"); 
  38.  $stmt->execute(); 
  39.  
  40.  // 设置结果集为关联数组 
  41.  $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 
  42.  foreach (new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k => $v) { 
  43.   echo $v; 
  44.  } 
  45. } catch (PDOException $e) { 
  46.  echo "Error: " . $e->getMessage(); 
  47. } 
  48. $conn = null; 
  49. echo "</table>"; 

到此程序就写完啦

来试试看吧

php7连接MySQL实现简易查询程序的方法

Tags: php7连接MySQL

分享到: