Home  >  Article  >  Backend Development  >  Tutorial on using parameterized query sql_PHP in pdo

Tutorial on using parameterized query sql_PHP in pdo

WBOY
WBOYOriginal
2016-07-21 15:25:03794browse

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.

Copy code The code is as follows:

$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:
Copy code The code is as follows:

$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:
Copy code The code is as follows:

// 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 =

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324178.htmlTechArticleThe methods bindParam() and bindValue() are very similar. The only difference is that the former uses a PHP variable to bind the parameter, while the latter uses a value. So using bindParam is the second parameter only...
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