search
HomeBackend DevelopmentPHP TutorialRelated knowledge about PHP MySQL prepared statements

Related knowledge about PHP MySQL prepared statements

May 07, 2018 pm 02:08 PM
mysqlphppreprocessing

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();?>

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;?>

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
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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function