实现对输入的数据进行保存数据库的操作:
index.html
<html lang="en">
<head>
<meta charset="utf-8">
<title>MySQL在PHP中的使用</title>
</head>
<body>
<h1>使用Demo</h1>
<form action="result.php" method="post">
Choose Search Type: <br/>
<select >
<option value="author">Author</option>
<option value="title">Title</option>
<option value="isbn">ISBN</option>
</select>
<br/>
Enter Search Term: <br/>
<input >
<br/><br/><br/>
<input type="submit" >
</form>
</body>
</html>
result.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta
content="width=device-width, user-sca>
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<?php
$searchType = $_POST["searchtype"];
$searchTerm = $_POST["serachterm"];
if (!$searchTerm || !$searchType) {
echo "请输入和选择" . '<br/>';
exit;
}
// 存入数据库
// 1.连接数据库
$servername = "localhost";
$username = "root";
$password = "pengsi";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password);
// 检测连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error) . '<br/>';
exit;
}
echo "连接成功" . '<br/>';
// 2.创建数据库
$sql = "CREATE DATABASE if Not Exists myDB";
if ($conn->query($sql) === TRUE) {
echo "数据库创建成功" . '<br/>';
// select database
$conn->select_db($dbname);
// 3.创建一个表
// 使用 sql 创建数据表
$sql = "CREATE TABLE if Not Exists MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
searchType VARCHAR(30) NOT NULL,
searchTerm VARCHAR(30) NOT NULL
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully" . '<br/>';
// 4.插入数据
$sql = "INSERT INTO MyGuests (searchType, searchTerm)
VALUES ('$searchType', '$searchTerm')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功" . '<br/>';
} else {
echo "Error: " . $sql . "<br>" . $conn->error . '<br/>';
}
$conn->close();
} else {
echo "创建数据表错误: " . $conn->error . '<br/>';
}
} else {
echo "Error creating database: " . $conn->error . '<br/>';
}
?>
</body>
</html>
Comments | NOTHING