Home Backend Development PHP Tutorial Related knowledge about PHP MySQL prepared statements

Related knowledge about PHP MySQL prepared statements

May 07, 2018 pm 02:08 PM
mysql php preprocessing

PHP MySQL prepared statements are very important in PHP. This article will learn about PHP MySQL prepared statements in detail.

Preprocessed statements and bound parameters

Preprocessed statements are used to execute multiple identical SQL statements with higher execution efficiency.

Preprocessing statements work as follows:

Preprocessing: Create a SQL statement template and send it to the database. Reserved values ​​are marked with the parameter "?". For example:

INSERT INTO MyGuests (firstname, lastname, email) VALUES(?, ?, ?)

Database parsing, compilation, query optimization on SQL statement templates, and storage The result is not output.

Execution: Finally, the application-bound value is passed to the parameter ("?" mark), and the database executes the statement. The application can execute the statement multiple times if the parameter values ​​are different.

Compared with directly executing SQL statements, prepared statements have two main advantages:

Preprocessed statements greatly reduce analysis time and only make one query (although the statement is executed multiple times) .

Bind parameters reduce server bandwidth, you only need to send the parameters of the query instead of the entire statement.

Preprocessed statements are very useful for SQL injection, because different protocols are used after the parameter values ​​are sent, ensuring the legality of the data.

MySQLi prepared statements

The following examples use prepared statements in MySQLi and bind corresponding parameters:

Examples (MySQLi uses prepared statements)

<?php$servername = "localhost";$username = "username";$password = "password";$dbname = "myDB"; 
// 创建连接$conn = new mysqli($servername, $username, $password, $dbname); 
// 检测连接if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);}
 // 预处理及绑定$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");$stmt->bind_param("sss", $firstname, $lastname, $email); 
// 设置参数并执行$firstname = "John";$lastname = "Doe";$email = "john@example.com";$stmt->execute(); 
$firstname = "Mary";$lastname = "Moe";$email = "mary@example.com";$stmt->execute(); 
$firstname = "Julie";$lastname = "Dooley";$email = "julie@example.com";$stmt->execute(); 
echo "新记录插入成功"; 
$stmt->close();$conn->close();?>
Copy after login

Parse each line of code in the following example:

"INSERT INTO MyGuests (firstname, lastname, email) VALUES(?, ?, ?)"

In the SQL statement , we used a question mark (?), where we can replace the question mark with integer, string, double float and boolean.

Next, let’s take a look at the bind_param() function:

$stmt->bind_param("sss", $firstname, $lastname, $email);

This function binds SQL parameters and tells the database the value of the parameters. The "sss" parameter column handles the data type of the remaining parameters. The s character tells the database that the parameter is a string.

The parameters have the following four types:

i - integer (integer type)

d - double (double precision floating point type)

s - string (string)

b - BLOB (binary large object: binary large object)

Each parameter needs to specify the type.

By telling the database the data type of the parameter, you can reduce the risk of SQL injection.



Note: If you want to insert other data (user input), validation of the data is very important.

Prepared statements in PDO

In the following examples, we use prepared statements and bind parameters in PDO:

Examples (PDO uses prepared statements)

<?php$servername = "localhost";$username = "username";$password = "password";$dbname = "myDBPDO"; 
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);    // 设置 PDO 错误模式为异常
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    // 预处理 SQL 并绑定参数
    $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) 
    VALUES (:firstname, :lastname, :email)");    $stmt->bindParam(&#39;:firstname&#39;, $firstname);    $stmt->bindParam(&#39;:lastname&#39;, $lastname);    $stmt->bindParam(&#39;:email&#39;, $email); 
    // 插入行
    $firstname = "John";    $lastname = "Doe";    $email = "john@example.com";    $stmt->execute(); 
    // 插入其他行
    $firstname = "Mary";    $lastname = "Moe";    $email = "mary@example.com";    $stmt->execute(); 
    // 插入其他行
    $firstname = "Julie";    $lastname = "Dooley";    $email = "julie@example.com";    $stmt->execute(); 
    echo "新记录插入成功";}catch(PDOException $e){
    echo "Error: " . $e->getMessage();}$conn = null;?>
Copy after login

This article explains in detail the relevant knowledge of PHP mysql preprocessing statements. For more learning materials, please pay attention to the PHP Chinese website.

Related recommendations:

How to insert multiple pieces of data through PHP MySQL

How to insert data through PHP MySQL

How to create a MySQL table through PHP

The above is the detailed content of Related knowledge about PHP MySQL prepared statements. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles