PHP 基础
PHP 简介
PHP 入门
PHP 语法
PHP 变量
PHP 常量
PHP 输出和打印
PHP 数据类型
PHP 字符串
PHP 运算符
PHP If…Else
PHP Switch…Case
PHP 数组
PHP 数组排序
PHP 循环
PHP 函数
PHP 数学运算
PHP GET 和 POST
PHP 高级
PHP 日期和时间
PHP 包含文件
PHP 文件系统
PHP 解析目录
PHP 文件上传
PHP 文件下载
PHP Cookies
PHP Sessions
PHP 发送邮件
PHP 表单处理
PHP 表单验证
PHP 过滤器
PHP 错误处理
PHP 类和对象
PHP 魔术常量
PHP JSON 解析
PHP 正则表达式
PHP 异常处理
PHP 和 MySQL 数据库
PHP MySQL 简介
PHP MySQL 连接
PHP MySQL Create Database
PHP MySQL Create Table
PHP MySQL Insert
PHP MySQL Prepared
PHP MySQL Last Inserted ID
PHP MySQL Select
PHP MySQL Where
PHP MySQL Limit
PHP MySQL Order By
PHP MySQL Update
PHP MySQL Delete
PHP MySQL CRUD 应用
PHP MySQL Ajax 搜索
PHP MySQL 登录系统
PHP参考
PHP String Functions
PHP Array Functions
PHP File System Functions
PHP Date/Time Functions
PHP Calendar Functions
PHP MySQLi Functions
PHP Filters
PHP Error Levels
PHP常见问题解答
如何在 PHP 中编写注释
如何在 PHP 中删除字符串中的空格
如何在 PHP 中查找字符串中的字符数
如何在 PHP 中查找字符串中的单词数
如何在 PHP 中删除字符串中的特殊字符
如何在 PHP 中替换字符串中的一个单词
如何在 PHP 中对字符串前面追加
如何在 PHP 中对字符串后面追加
如何在 PHP 中从字符串中提取子串
如何在 PHP 中比较两个字符串
如何在 PHP 中获取当前页面的 URL
如何在 PHP 中通过连接数组值创建字符串
如何在 PHP 中将字符串拆分为数组
如何在 PHP 中合并两个字符串
如何在 PHP 中把字符串转换成小写字母
如何在 PHP 中把字符串转换成大写字母
如何在 PHP 中把字符串的第一个字母转换成大写字母
如何在 PHP 中把特殊的 HTML 实体转换回字符
如何在 PHP 中删除字符串开头的空格
如何在 PHP 中删除字符串结尾的空格
如何在 PHP 中新建一行
如何在 PHP 中查找字符串长度
如何在 PHP 中检查变量是否已设置
如何在 PHP 中检查变量是否为空
如何在 PHP 中检查变量是否为NULL
如何在 PHP 中反转字符串
如何在 PHP 中用另一个字符串替换字符串的一部分
如何在 PHP 中计算子串在字符串中出现的次数
如何在 PHP 中计算数组中的所有元素
如何在 PHP 中打印或回显数组的所有值
如何在 PHP 中显示数组的结构和值
如何在 PHP 中颠倒数组的顺序
如何在 PHP 中检查数组中是否存在值
如何在 PHP 中检查数组中是否存在键
如何在 PHP 中删除数组中的最后一个元素
如何从 PHP 数组中删除第一个元素
如何在 PHP 中为数组的开头添加元素
如何在 PHP 中为数组的末尾添加元素
如何在 PHP 中把两个或多个数组合并成一个数组
如何在 PHP 中按字母顺序对数组值排序
如何在 PHP 中删除数组中的重复值
如何在 PHP 中随机调整数组的顺序
如何在 PHP 中比较两个数组的值
如何在 PHP 中计算数组中数值的总和
如何在 PHP 中删除数组中的空值
如何在 PHP 中用数组值填充下拉列表
如何在 PHP 中获取关联数组的所有键值
如何在 PHP 中获取关联数组的所有值
如何在 PHP 中按键对关联数组排序
如何在 PHP 中按值对关联数组排序
如何在 PHP 中从数组中获取单个值
如何在 PHP 中循环浏览多维数组
如何在 PHP 中从数组中删除元素
如何在 PHP 中检查字符串是否包含特定单词
如何在 PHP 中获取当前日期和时间
如何在 PHP 中进行重定向
如何在 PHP 中删除字符串中的所有空格
如何用 PHP 获取当前年份
如何在 PHP 中将日期从 yyyy-mm-dd 转换为 dd-mm-yyyy 格式
如何在 PHP 中将字符串转换为数字
如何在 PHP 中获取数组的第一个元素
如何在 PHP 中将日期转换为时间戳
如何在 PHP 中为空数组添加元素
如何在 PHP 中把整数转换成字符串
如何用值而不是键删除 PHP 数组元素
如何在 PHP 中将键和值同时推入数组
如何使用 PHP 定期刷新页面
如何从 PHP 字符串中删除最后一个字符
如何从 PHP 脚本返回 JSON
如何让 PHP 显示错误
PHP MySQL Prepared - php7基础教程 - 笔下光年
网站首页
PHP MySQL Prepared
In this tutorial you will learn how to use prepared statements in MySQL using PHP. ## What is Prepared Statement A prepared statement (also known as parameterized statement) is simply a SQL query template containing placeholder instead of the actual parameter values. These placeholders will be replaced by the actual values at the time of execution of the statement. MySQLi supports the use of anonymous positional placeholder (`?`), as shown below: ```sql INSERT INTO persons (first_name, last_name, email) VALUES (?, ?, ?); ``` While, PDO supports both anonymous positional placeholder (`?`), as well as the named placeholders. A named placeholder begins with a colon (`:`) followed by an identifier, like this: ```php INSERT INTO persons (first_name, last_name, email) VALUES (:first_name, :last_name, :email); ``` The prepared statement execution consists of two stages: prepare and execute. - Prepare — At the prepare stage a SQL statement template is created and sent to the database server. The server parses the statement template, performs a syntax check and query optimization, and stores it for later use. - Execute — During execute the parameter values are sent to the server. The server creates a statement from the statement template and these values to execute it. Prepared statements is very useful, particularly in situations when you execute a particular statement multiple times with different values, for example, a series of `INSERT` statements. The following section describes some of the major benefits of using it. ## Advantages of Using Prepared Statements A prepared statement can execute the same statement repeatedly with high efficiency, because the statement is parsed only once again, while it can be executed multiple times. It also minimize bandwidth usage, since upon every execution only the placeholder values need to be transmitted to the database server instead of the complete SQL statement. Prepared statements also provide strong protection against [SQL injection](http://www.bixiaguangnian.com/manual/sql/3422.html "SQL injection"), because parameter values are not embedded directly inside the SQL query string. The parameter values are sent to the database server separately from the query using a different protocol and thus cannot interfere with it. The server uses these values directly at the point of execution, after the statement template is parsed. That's why the prepared statements are less error-prone, and thus considered as one of the most critical element in database security. The following example will show you how prepared statements actually work: ```php <?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", "", "demo"); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Prepare an insert statement $sql = "INSERT INTO persons (first_name, last_name, email) VALUES (?, ?, ?)"; if($stmt = mysqli_prepare($link, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "sss", $first_name, $last_name, $email); /* Set the parameters values and execute the statement again to insert another row */ $first_name = "Hermione"; $last_name = "Granger"; $email = "hermionegranger@mail.com"; mysqli_stmt_execute($stmt); /* Set the parameters values and execute the statement to insert a row */ $first_name = "Ron"; $last_name = "Weasley"; $email = "ronweasley@mail.com"; mysqli_stmt_execute($stmt); echo "Records inserted successfully."; } else{ echo "ERROR: Could not prepare query: $sql. " . mysqli_error($link); } // Close statement mysqli_stmt_close($stmt); // Close connection mysqli_close($link); ?> ``` As you can see in the above example we've prepared the `INSERT` statement just once but executed it multiple times by passing the different set of parameters. ## Explanation of Code (Procedural style) Inside the SQL `INSERT` statement (line no-12) of the example above, the question marks is used as the placeholders for the first_name, last_name, email fields values. The `mysqli_stmt_bind_param()` function (line no-16) bind variables to the placeholders (`?`) in the SQL statement template. The placeholders (`?`) will be replaced by the actual values held in the variables at the time of execution. The type definition string provided as second argument i.e. the "sss" string specifies that the data type of each bind variable is string. The type definition string specify the data types of the corresponding bind variables and contains one or more of the following four characters: - **b** — binary (such as image, PDF file, etc.) - **d** — double (floating point number) - **i** — integer (whole number) - **s** — string (text) The number of bind variables and the number of characters in type definition string must match the number of placeholders in the SQL statement template. ## Using Inputs Received through a Web Form If you remember from the previous chapter, we've created an HTML form to [insert data into database](http://www.bixiaguangnian.com/manual/php7/4004.html#h2-insert-data-into-a-database-from-an-html-form "insert data into database"). Here, we're going to extend that example by implementing the prepared statement. You can use the same HTML form to test the following insert script example, but just make sure that you're using the correct file name in the action attribute of the form. Here's the updated PHP code for inserting the data. If you see the example carefully you'll find we didn't use the `mysqli_real_escape_string()` to escape the user inputs, like we've done in the previous chapter example. Since in prepared statements, user inputs are never substituted into the query string directly, so they do not need to be escaped correctly. ```php <?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", "", "demo"); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Prepare an insert statement $sql = "INSERT INTO persons (first_name, last_name, email) VALUES (?, ?, ?)"; if($stmt = mysqli_prepare($link, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "sss", $first_name, $last_name, $email); // Set parameters $first_name = $_REQUEST['first_name']; $last_name = $_REQUEST['last_name']; $email = $_REQUEST['email']; // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ echo "Records inserted successfully."; } else{ echo "ERROR: Could not execute query: $sql. " . mysqli_error($link); } } else{ echo "ERROR: Could not prepare query: $sql. " . mysqli_error($link); } // Close statement mysqli_stmt_close($stmt); // Close connection mysqli_close($link); ?> ``` <div class="callout callout-info mb-3">Note: Though escaping user inputs is not required in prepared statements, you should always validate the type and size of the data received from external sources and enforces appropriate limits to protect against system resources exploitation.</div>
上一篇:
PHP MySQL Insert
下一篇:
PHP MySQL Last Inserted ID