PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

介绍php7连接MySQL制作简易查询程序

coldplay.xixi
coldplay.xixi 转载
2021-03-25 10:01:04 1535浏览

简易教程
假设我们制作的是分班情况查询程序,将使用PHP7的环境以PDO的方式连接MySQL。
通过学号和姓名查询自己所在班级。

推荐(免费):php7/" target="_blank">PHP7
先来介绍文件结构和数据库结构:
PHP:
config.php 存放数据库配置信息
cx.php 查询程序
index.html 用户界面在这里插入图片描述
结构如图

MySQL:
表名:data
字段:1.Sid 2.name 3.class
在这里插入图片描述
结构如图

准备就绪,开始吧,现在!
首先构建用户界面(index.html),两个简单的编辑框加上一个简单的按钮:

nbsp;html>
    <meta>
    <title>分班查询系统</title>
    

学号:

    

姓名: 

    

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

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

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

<?phpheader ("Content-Type: text/html; charset=utf8");if(!isset($_POST["submit"])){
    exit("未检测到表单提交");}//检测是否有submit操作include ("config.php");$Sid = $_POST[&#39;Sid&#39;];//post获得学号表单值$name = $_POST[&#39;name&#39;];//post获得姓名表单值echo "<table style=&#39;border: solid 1px black;&#39;>";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>" . 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 "";

到此程序就写完啦
来试试看吧
在这里插入图片描述
在这里插入图片描述

声明:本文转载于:CSDN,如有侵犯,请联系admin@php.cn删除