Tutorial on using parameterized query sql_PHP in pdo
The methods bindParam() and bindValue() are very similar.
The only difference is that the former uses a PHP variable to bind parameters, while the latter uses a value.
So when using bindParam, the second parameter can only use variable names, not variable values, while bindValue can only use specific values.
$stm = $pdo->prepare("select * from users where user = :user");
$user = "jack";
//Correct
$stm->bindParam(":user",$user);
//Wrong
/ /$stm->bindParam(":user","jack");
//Correct
$stm->bindValue(":user",$user);
//Correct
$stm->bindValue(":user","jack");
In addition, in the stored procedure, bindParam can be bound to an input/output variable, as shown below:
$stm = $pdo->prepare("call func(:param1)");
$param1 = "abcd";
$stm->bindParam(":param1",$param1); //Correct
$stm->execute();
The results after the stored procedure is executed can be directly reflected in the variables.
For those large data block parameters in memory, for performance reasons, the former should be used first.
-------------------------------------------------- ---
http://zh.wikipedia.org/wiki/%E5%8F%83%E6%95%B8%E5%8C%96%E6%9F%A5%E8%A9%A2
Parameterized Query
Parameterized Query (Parameterized Query or Parameterized Statement) refers to using parameters (Parameter) to give values where values or data need to be filled in when designing to connect to the database and access data. This method It is currently regarded as the most effective defense method to prevent SQL injection attacks (SQL Injection). Some developers may think that using parameterized queries will make the program more difficult to maintain, or it will be very inconvenient to implement some functions [source request]. However, the additional development costs caused by using parameterized queries are usually They are far less than the heavy losses caused by attacks due to the discovery of SQL injection attack vulnerabilities.
In addition to security factors, parameterized queries often have performance advantages compared to SQL statements that concatenate strings. Because parameterized queries allow different data to reach the database through parameters, thereby sharing the same SQL statement. Most databases cache the bytecode generated by interpreting SQL statements to save the overhead of repeated parsing. If you adopt an SQL statement that concatenates strings, unnecessary overhead will be incurred by repeatedly interpreting a large number of SQL statements because the operation data is part of the SQL statement and not part of the parameters.
Table of Contents
* 1 Principle
* 2 Method of writing SQL instructions
o 2.1 Microsoft SQL Server
o 2.2 Microsoft Access
o 2.3 MySQL
o 2.4 PostgreSQL/SQLite
* 3 Client program writing methods
o 3.1 ADO.NET
o 3.2 PDO
o 3.3 JDBC
o 3.4 Cold Fusion
[edit] Principle
Using parameterized queries In this case, the database server will not treat the content of the parameters as part of the SQL command. Instead, it will apply the parameters after the database completes the compilation of the SQL command. Therefore, even if the parameters contain destructive commands, It will not be run by the database.
[edit] How to write SQL instructions
When writing SQL instructions, use parameters to represent the values that need to be filled in, for example:
[edit] Microsoft SQL Server
The parameter format of Microsoft SQL Server is It is formed by adding the "@" character to the parameter name. SQL Server also supports the anonymous parameter "?".
SELECT * FROM myTable WHERE myID = @myID
INSERT INTO myTable (c1, c2, c3, c4) VALUES (@c1, @c2, @c3, @c4)
[edit] Microsoft Access
Microsoft Access does not support named parameters and only supports anonymous parameters "?".
UPDATE myTable SET c1 = ?, c2 = ?, c3 = ? WHERE c4 = ?
[edit] MySQL
The parameter format of MySQL is composed of the "?" character plus the parameter name.
UPDATE myTable SET c1 = ?c1, c2 = ?c2, c3 = ?c3 WHERE c4 = ?c4
[edit] PostgreSQL/SQLite
The parameter format of PostgreSQL and SQLite is preceded by ":" The parameter name is formed. Of course, Access-like anonymous parameters are also supported.
UPDATE "myTable" SET "c1" = :c1, "c2" = :c2, "c3" = :c3 WHERE "c4" = :c4
[edit] Client program writing method
in Write code that uses parameters in the client code, for example:
[edit] ADO.NET
ADO.NET is used within ASP.NET.
SqlCommand sqlcmd = new SqlCommand("INSERT INTO myTable (c1, c2, c3, c4) VALUES (@c1, @c2, @c3, @c4)", sqlconn);
sqlcmd.Parameters.AddWithValue( "@c1", 1); // Set the value of parameter @c1.
sqlcmd.Parameters.AddWithValue("@c2", 2); // Set the value of parameter @c2.
sqlcmd.Parameters.AddWithValue("@c3", 3); // Set the value of parameter @c3.
sqlcmd.Parameters.AddWithValue("@c4", 4); // Set the value of parameter @c4.
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
[edit] PDO
PDO is used within PHP. When using the PDO driver, the method of using parameter query is generally:
// Instantiate the data abstraction layer object
$db = new PDO('pgsql:host=127.0.0.1;port=5432;dbname=testdb');
// For SQL statements Execute prepare and get the PDOStatement object
$stmt = $db->prepare('SELECT * FROM "myTable" WHERE "id" = :id AND "is_valid" = :is_valid');
// Binding Parameter
$stmt->bindValue(':id', $id);
$stmt->bindValue(':is_valid', true);
// Query
$stmt- >execute();
//Get data
foreach($stmt as $row) {
var_dump($row);
}
[code]
For MySQL Specific drivers can also be used like this:
$db = new mysqli("localhost", "user", "pass", "database");
$stmt = $mysqli -> prepare("SELECT priv FROM testUsers WHERE username=? AND password=?");
$stmt -> bind_param("ss", $user, $pass);
$stmt -> execute();
Worth Note that although the following method can effectively prevent SQL injection (thanks to the escaping of the mysql_real_escape_string function), it is not a true parameterized query. Its essence is still a SQL statement that concatenates strings.
[code]
$query = sprintf("SELECT * FROM Users where UserName='%s' and Password='%s'",
mysql_real_escape_string($Username),
mysql_real_escape_string($ Password));
mysql_query($query);
[edit] JDBC
JDBC is used in Java.
java.sql.PreparedStatement prep = connection.prepareStatement(
"SELECT * FROM `users` WHERE USERNAME = ? AND PASSWORD = ?");
prep.setString(1, username);
prep.setString(2, password);
prep.executeQuery();
[edit] Cold Fusion
SELECT *
FROM COMMENTS
WHERE COMMENT_ID =

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment