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

吾爱主题 阅读:130 2021-10-27 13:38:00 评论:1

简易教程

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

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

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

PHP:

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

cx.php 查询程序

index.html 用户界面

结构如图

MySQL:

表名:data

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

结构如图

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

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

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

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

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

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

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

到此程序就写完啦

来试试看吧


总结

到此这篇关于php7连接MySQL实现简易查询程序的文章就介绍到这了,更多相关php7连接MySQL简易查询程序内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_33681342/article/details/109024846

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容