在 PHP 中执行多个 MySQL 查询

Habdul Hazeez 2023年1月30日
  1. 在 PHP 中使用准备好的语句执行多个 SQL 查询
  2. 在 PHP 中使用 Multi_query 执行多个 SQL 查询
在 PHP 中执行多个 MySQL 查询

本教程将教你在 PHP 中执行多个 SQL 查询。我们将讨论两种方法来展示如何做到这一点。

第一种方法使用 PHP prepared statements,而第二种方法将使用 PHP multi_query 函数。

在 PHP 中使用准备好的语句执行多个 SQL 查询

为了演示如何使用准备好的语句执行多个 SQL 查询,我们需要三样东西:HTML 表单、MySQL 数据库和执行查询的 PHP 代码。让我们从数据库开始。

使用 MySQL 创建数据库和数据库表

要创建数据库,我们将使用带有 XAMPP 的本地 MySQL 数据库。从他们的官方网站下载并安装 XAMPP

下载完成后,启动 XAMPP 控制面板。然后使用以下命令启动 MySQL shell。

# This login command assumes that the
# password is empty, and the user is "root"
mysql -u root -p

创建一个名为 fruit_database 的数据库并使用它。

CREATE database fruit_database;
USE fruit_database;

输出:

Query OK, 1 row affected (0.002 sec)
Database changed

在数据库中创建一个名为 fruits 的表。

CREATE TABLE fruits
(id INT NOT NULL AUTO_INCREMENT,
 name VARCHAR(20) NOT NULL,
 PRIMARY KEY (id))
 ENGINE = InnoDB;

输出:

Query OK, 0 rows affected (0.028 sec)

创建 HTML 表单

我们将在 HTML 表单中使用两个表单输入和一个提交按钮。表单输入将采用我们将插入数据库的两个字符串。

这是表单的 HTML。

<main>
	<form action="multi-sql.php" method="post">
		<div class="form-row">
			<label
				for="first-color">
				First Color
			</label>
			<input
				type="text"
				placeholder="Enter the first color"
				name="first-color"
				id="first-color"
				required
			>
		</div>
		<div class="form-row">
			<label
				for="second-color">
				Second Color
			</label>
			<input
				type="text"
				placeholder="Enter the second color"
				name="second-color"
				id="second-color"
				required
			>
		</div>
		<div class="form-row flex-center">
			<button
				type="submit"
				name="submit"
			>
				Submit Colors
			</button>
		</div>
	</form>
</main>

创建 PHP 代码

PHP 代码将处理表单输入,然后将其值提交到数据库。

我们清理用户提交的字符串。然后我们将这些字符串用作 SQL 查询的一部分。

之后,我们将查询存储在一个数组中。为了提交它们,我们使用准备好的语句。

将以下 PHP 代码保存为 multi-sql.php

<?php
    if (isset($_POST['submit'])) {
        // Connect to the database
        $connection_string = new mysqli("localhost", "root", "", "fruit_database");

        // Sanitise the input strings
        $firstColor = mysqli_real_escape_string($connection_string, trim(htmlentities($_POST['first-color'])));
        $secondColor = mysqli_real_escape_string($connection_string, trim(htmlentities($_POST['second-color'])));

        // If there is a connection error, notify
        // the user, and Kill the script.
        if ($connection_string->connect_error) {
            echo "Failed to connect to Database";
            exit();
        }

        // Check string length, empty strings and
        // non-alphanumeric characters.
         if ( $firstColor === "" || !ctype_alnum($firstColor) ||
                strlen($firstColor) <= 3
            ) {
                echo "The first color value is invalid.";
                exit();
        }

         if ( $secondColor === "" || !ctype_alnum($secondColor) ||
                strlen($secondColor) <= 3
            ) {
                echo "The second color value is invalid.";
                exit();
        }

        $queries = [
            "INSERT into fruits (name) VALUES ('$firstColor')",
            "INSERT into fruits (name) VALUES ('$secondColor')"
        ];

        // Execute the multiple SQL queries
        foreach ($queries as $query) {
            $stmt = $connection_string->prepare($query);
            $stmt->execute();
        }

        if ($stmt->affected_rows === 1) {
            echo "Data inserted successfully";
        }
    } else { // The user accessed the script directly

        // Kill the script.
        echo "That is not allowed!";
        exit();
    }
?>

输出(如果成功):

Data inserted successfully

输出(如果输入有错误):

The first color value is invalid.

在 PHP 中使用 Multi_query 执行多个 SQL 查询

你可以使用 PHP 中的内置函数 multi_query 执行多个 SQL 查询。SQL 查询应该在一个带引号的字符串中,以便使用 multi_query 进行多个查询,但每个 SQL 应该用分号分隔。

对于 HTML 和 CSS,你可以使用与上一节相同的 HTML 和 CSS 代码。

下一个 PHP 代码将使用 multi_query 将数据插入数据库。将其保存为 multi-sql-v2.php

相应地更新你的 HTML。

<?php
    if (isset($_POST['submit'])) {
        // Connect to the database
        $connection_string = new mysqli("localhost", "root", "", "fruit_database");

        // Sanitise the input strings
        $firstColor = mysqli_real_escape_string($connection_string, trim(htmlentities($_POST['first-color'])));
        $secondColor = mysqli_real_escape_string($connection_string, trim(htmlentities($_POST['second-color'])));

        // If there is a connection error, notify
        // the user, and Kill the script.
        if ($connection_string->connect_error) {
            echo "Failed to connect to Database";
            exit();
        }

        // Check string length, empty strings
        // and non-alphanumeric characters.
         if ($firstColor === "" || !ctype_alnum($firstColor) ||
                strlen($firstColor) <= 3
        ) {
            echo "The first color value is invalid.";
            exit();
        }

        if ( $secondColor === "" || !ctype_alnum($secondColor) ||
                strlen($secondColor) <= 3
        ) {
            echo "The second color value is invalid.";
            exit();
        }

        // Prepare the SQL queries for MySQL
        // multi queries
        $sql = "INSERT into fruits (name) VALUES ('$firstColor');
                INSERT into fruits (name) VALUES ('$secondColor')";

                // Execute the queries with multi_query
        if ($connection_string->multi_query($sql) === TRUE) {
            echo "Data inserted successfully";
        }
    } else { // The user accessed the script directly

        // Kill the script.
        echo "That is not allowed!";
        exit();
    }
?>

输出(如果成功):

Data inserted successfully

输出(如果输入有错误):

The first color value is invalid.

创建 CSS 代码来设置 HTML 表单的样式

下面的 CSS 代码将为本文中创建的 HTML 表单设置样式。

* {
	box-sizing: border-box;
	padding: 0;
	margin: 0;
}

body {
	display: grid;
	align-items: center;
	place-items: center;
	height: 100vh;
}

main {
	display: flex;
	justify-content: center;
	width: 60%;
	border: 5px solid #1a1a1a;
	padding: 1em;
}

form {
	font-size: 1.2em;
	width: 100%;
}

input,
label {
	width: 50%;
	font-size: 1em;
	padding: 0.2em;
}

button {
	padding: 0.2em;
	font-size: 1em;
}

.form-row {
	display: flex;
	justify-content: space-between;
	margin-bottom: 0.5em;
	padding: 0.2em;
}

.flex-center {
	display: flex;
	justify-content: center;
}
作者: Habdul Hazeez
Habdul Hazeez avatar Habdul Hazeez avatar

Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.

LinkedIn

相关文章 - PHP MySQL