This article will introduce to you how to connect php7 to MySQL to create a simple query program. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Simple Tutorial
Assume that we are making a class status inquiry program and connect the environment using PHP7 in the form of PDO MySQL.
Check your class by student number and name.
Let’s first introduce the file structure and database structure:
PHP:
config.php stores database configuration information
cx. php query program
index.html User interface

The structure is as shown in the figure
MySQL:
Table name: data
Fields: 1.Sid 2.name 3.

##The structure is as shown in the figure
Prepare Ready, get started, now!
First build the user interface (index.html), two simple edit boxes plus a simple button:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!DOCTYPE html>
<html>
<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>
|
Copy after login
Okay, then configure the database information (config. php)
1 2 3 4 5 | <?php
$server = "localhost" ;
$db_username = "root" ;
$db_password = "123456" ;
$db_name = "data" ;
|
Copy after login
Then write our main program (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 ( "未检测到表单提交" );
}
include ( "config.php" );
$Sid = $_POST ['Sid'];
$name = $_POST ['name'];
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>" ;
|
Copy after login
This program is finished
Let’s try it


Recommended learning:
php video tutorial
The above is the detailed content of How to create a simple query program to connect MySQL with php7. For more information, please follow other related articles on the PHP Chinese website!