簡易教程
假設(shè)我們制作的是分班情況查詢程序,將使用PHP7的環(huán)境以PDO的方式連接MySQL。
通過學(xué)號和姓名查詢自己所在班級。
先來介紹文件結(jié)構(gòu)和數(shù)據(jù)庫結(jié)構(gòu):
PHP:
config.php 存放數(shù)據(jù)庫配置信息
cx.php 查詢程序
index.html 用戶界面
![](/d/20211017/0d11d0a273fa025979574169f9b07342.gif)
結(jié)構(gòu)如圖
MySQL:
表名:data
字段:1.Sid 2.name 3.class
![](/d/20211017/35a02b0baf3ad3219685e2658b83f8b9.gif)
結(jié)構(gòu)如圖
準備就緒,開始吧,現(xiàn)在!
首先構(gòu)建用戶界面(index.html),兩個簡單的編輯框加上一個簡單的按鈕:
!DOCTYPE html>
html lang="cn">
head>
meta charset="UTF-8">
title>分班查詢系統(tǒng)/title>
/head>
body>
form action="cx.php" method="post">
p>學(xué)號:input type="text" name="xuehao">/p>
p>姓名: input type="text" name="xingming">/p>
p>input type="submit" name="submit" value="查詢">/p>
/form>
/body>
/html>
好嘞,接下來配置數(shù)據(jù)庫信息(config.php)吧
?php
$server="localhost";//主機的IP地址
$db_username="root";//數(shù)據(jù)庫用戶名
$db_password="123456";//數(shù)據(jù)庫密碼
$db_name = "data";
然后去編寫我們的主程序(cx.php)
?php
header("Content-Type: text/html; charset=utf8");
if(!isset($_POST["submit"]))
{
exit("未檢測到表單提交");
}//檢測是否有submit操作
include ("config.php");
$Sid = $_POST['Sid'];//post獲得學(xué)號表單值
$name = $_POST['name'];//post獲得姓名表單值
echo "table style='border: solid 1px black;'>";
echo "tr>th>學(xué)號/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();
// 設(shè)置結(jié)果集為關(guān)聯(lián)數(shù)組
$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>";
到此程序就寫完啦
來試試看吧
![](/d/20211017/444c7ccd0d0adbf0c9c196f454d70bc7.gif)
![](/d/20211017/58232ffad8f8f30f682e386ba40cb3fa.gif)
總結(jié)
到此這篇關(guān)于php7連接MySQL實現(xiàn)簡易查詢程序的文章就介紹到這了,更多相關(guān)php7連接MySQL簡易查詢程序內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- Android和PHP MYSQL交互開發(fā)實例
- Mac M1安裝mnmp(Mac+Nginx+MySQL+PHP)開發(fā)環(huán)境
- PHP加MySQL消息隊列深入理解
- PHP+Mysql分布式事務(wù)與解決方案深入理解
- PHP連接MySQL數(shù)據(jù)庫三種實現(xiàn)方法
- 深入理解PHP+Mysql分布式事務(wù)與解決方案
- Aliyun Linux 編譯安裝 php7.3 tengine2.3.2 mysql8.0 redis5的過程詳解
- PHP之mysql位運算案例講解