Table of Contents
I got a big rub-PDO (2), rub-pdo
Home Backend Development PHP Tutorial I have a big problem-PDO (2), wipe-pdo_PHP tutorial

I have a big problem-PDO (2), wipe-pdo_PHP tutorial

Jul 12, 2016 am 09:03 AM
3 two roommate yesterday have

I got a big rub-PDO (2), rub-pdo

 hi

It was 213 again yesterday. Although it was objectively affected by the fact that my roommate didn’t go to bed until after 3 o’clock, the fundamental reason was that I didn’t want to study last night. Start it today. I plan to finish learning PDO and AJAX within 3 or 4 days. I hope everyone will come and scold me if they have nothing to do, so that I won't be lazy again.

1. PDO

2. Use of PDO objects (2)

2.2 Error message

errorCode()——error number;

errorInfo()——error message;

Give me a chestnut

/*
* PDO error message
*/

$pdo=new PDO('mysql:host=localhost;dbname=imooc','root','');

$pdo->exec('use imooc_pdo');
$resultd=$pdo->exec('delete from user where id=13');
var_dump($resultd);
$insert='insert user(username,password,email) values("Knga","'.md5('king').'","shit@shit.com")';
$result1= $pdo->exec($insert);
var_dump($result1);

if ($result1==false) {
echo "An error occurred";
echo $pdo->errorCode();
print_r($pdo->errorInfo());
}

Look at the error message

Array ( [0] => 23000 [1] => 1062 [2] =>

0 is the error type, 1062 is the code, and 2 is the error message; (This is because the username is set to a unique key, but the ID number is still growing).

2.3 query() to implement query

Execute a statement and return a PDOstatement object.

--Give me a chestnut

/*

* PDOquery
*/

$pdo=new PDO('mysql:host=localhost;dbname=imooc','root','');

$pdo->exec('use imooc_pdo');

$insert='select * from user';

$result1=$pdo->query($insert);

var_dump($result1); //View statement object
foreach ($result1 as $row){ //View the output results (according to the return situation) print_r($row);
}
if ($result1== false) {
echo "An error occurred";
echo $pdo->errorCode();
print_r($pdo->errorInfo());
}

If there is a problem with the sql statement, the statement object is false, and the subsequent output is also an error message;

If the sql statement is correct but the content of the query does not exist, then the statement object is OK and the output is empty.

Of course it will look better this way:

foreach ($result1 as $row){ //View the output results (according to the return situation)

// print_r($row);echo "
";
echo 'number: '.$row['id'];echo "
";
echo 'Username:'.$row['username'];echo "
";
echo 'Password:'.$row['password'];echo "
";
echo 'Email:'.$row['email'];echo "
";
echo "


";
}

Of course, it is no problem to add, delete or modify the query.

2.4 prepare() and execute() methods to implement query

The recommended query method can realize conditional query.

prepare()——Prepare the SQL statement to be executed and return the PDOstatement object;

execute()——Execute a prepared statement,

return true or false;

So the above is a pair.

--give an example

/*
* PDOprepare&execute method
*/

$pdo=new PDO('mysql:host=localhost;dbname=imooc','root','');

$pdo->exec('use imooc_pdo');

$insert='select * from user where username="king"';


$result=$pdo->prepare($insert);var_dump($result) ;

$result1=$result->execute();//Execution is for prepared statementsvar_dump($result1);

print_r($result->fetchAll());//The result can only be output for the statement object

if ($result1==false) {

echo "An error occurred";
echo $pdo->errorCode();
print_r($pdo->errorInfo());
}

Be careful to pre-handle this special situation here, and it will be easier to figure out who the target is.

--Select the output format

To associate array output or all or index arrays, there are two different methods: parameters and methods.

header('content-type:text/html;charset=utf-8');
try{
$pdo=new PDO('mysql:host=localhost; dbname=imooc','root','root');
$sql='select * from user';
$stmt=$pdo->prepare($sql);
$res= $stmt->execute();
// if($res){
// while($row=$stmt->fetch(PDO::FETCH_ASSOC)){//only Associative array output is required
// print_r($row);
// echo '


';
// }
// }
// $rows=$stmt->fetchAll(PDO::FETCH_ASSOC);
// print_r($rows);
echo '
';
$stmt-> ;setFetchMode(PDO::FETCH_ASSOC); //Same implementation effect, you can also use this method, set the default mode
//var_dump($stmt);
$rows=$stmt-> fetchAll();
print_r($rows);
}catch(PDOException $e){
echo $e->getMessage();
}

Generally we want to index an array.

2.5 Set database connection properties

setAttribute()——Set database connection attributes;

getAttribute()——Get the database connection attributes;

--give an example

$pdo=new PDO('mysql:host=localhost;dbname=imooc','root','');
echo "Autocommit".$pdo->getAttribute(PDO: :ATTR_AUTOCOMMIT);echo "


";
//Remember that pdo is an object, so you get the attributes, you know. Then there are many set attribute values ​​inside it, which is the premise for us to get the attributes.
echo "Default error handling mode:".$pdo->getAttribute(PDO::ATTR_ERRMODE);echo "
";
$pdo->setAttribute(PDO ::ATTR_AUTOCOMMIT, 0);
echo "Autocommit".$pdo->getAttribute(PDO::ATTR_AUTOCOMMIT);echo "
";

Then try to get a large wave of attribute information:

$attrArr=array(
'AUTOCOMMIT','ERRMODE','CASE','PERSISTENT','SERVER_INFO','SERVER_VERSION'
);
foreach ($attrArr as $attr) {
echo "PDO::ATTR_$attr: ";
echo $pdo->getAttribute(constant("PDO::ATTR_$attr"))."
";
}

Some are not available, there will be error messages, it doesn’t matter.

3. Use of PDOstatement object

3.1 The quote() method prevents SQL injection

--SQL injection

First of all, give an example to illustrate this simple SQL injection (actually I don’t understand it very well - Baidu http://baike.baidu.com/link?url=jiMtgmTeePlWAqdAntWbk-wB8XKP8xS3ZOViJE9IVSToLP_iT2anuUaPdMEM0b-VDknjolQ8BdxN8ycNLohup_)

The so-called SQL injection is to insert SQL commands into Web form submissions or enter domain names or query strings for page requests, ultimately tricking the server into executing malicious SQL commands.

So you need to have a form, and then you need to query the database for data, etc., and then through malicious use of loopholes in the rules, you can get a large amount of data that is not what the page expects. The chestnuts are as follows:

The example is login - login requires user name, password, etc., and needs to be compared with the information in the database;

The first is the login page





$stmt= $pdo->query($sql);
echo $stmt->rowCount();//Display the number of rows in the result set statement object

} catch ( PDOException $e) {
echo $e->getMessage();
}

Then open login.html in the browser, enter the username and password in the database, click login, you will get 1;

If you enter incorrect information, you will usually get 0;

Note, if you enter a username such as 'or 1=1# and a password of any size , you will easily get all the data in the database. This is due to the rules of the SQL statement itself.

So you need to filter the information entered by the user and don’t trust all the user’s operations.

--Coping methods

echo $pdo->quote($username);

Write this sentence, and then use the above cheat code, the output will have more single quotes, and automatically add:

''or 1=1#'

But if you do this, the call to $username will be automatically added with quotation marks, so the following sql statement will change accordingly:

$username=$pdo->quote($username);
$pdo->exec('use imooc_pdo');
$sql="select * from user where username={$username } and password='{$password}'";

To put it simply, put the user name on it. It seems that this is something to be guarded against when there is a database.

But it is not recommended to use this method - It is recommended to use the preprocessing method of prepare execute.

3.2 Use of placeholders in prepared statements

It is very good at preventing injection; it can be compiled once and executed multiple times to reduce system overhead;

--Placeholder: (named parameters) (recommended)

header('content-type:text/html;charset=utf-8');
$username=$_POST['username'];
$password=$ _POST['password'];
try {
$pdo=new PDO('mysql:host=localhost;dbname=imooc','root','');
$pdo->exec ('use imooc_pdo');
$sql="select * from user where username=:username and password=:$password";
$stmt=$pdo->prepare( $sql);
$stmt->execute(array(":username"=>$username,":password"=>$password));
//$ stmt=$pdo->query($sql);
echo $stmt->rowCount();//Display the number of rows in the result set statement object

} catch (PDOException $e) {
echo $e->getMessage();
}

The corresponding SQL statement, the corresponding execution, and the parameters that need to be passed must also be corresponding.

--Placeholder?

$sql="select * from user where username=? and password=?";
$stmt=$pdo->prepare($sql);
$stmt->execute(array($username,$password));

Feeling? The method should be simpler, just three points - input placeholder in sql statement, preprocessing and execution (use array to pass multiple data).

3.3 bindParam() method binds parameters

Bind a parameter to a variable name.

/*
* Binding parameters
*/

header('content-type:text/html;charset=utf-8');
try {
$pdo=new PDO('mysql:host=localhost;dbname=imooc','root ','');
$pdo->exec('use imooc_pdo');
$sql="insert user(username,password,email) values(:username,:password,: email)";
$stmt=$pdo->prepare($sql);
$username="Wid";$password="123";$email="324@qq.com "; //Define parameters
$stmt->bindParam(":username", $username,PDO::PARAM_STR);
$stmt->bindParam(" :password",$password);
$stmt->bindParam(":email",$email);
$stmt->execute();
$res=$pdo->query("select * from user");
foreach ($res as $row){ //View the output results (according to the return situation)
// print_r($row );echo "
";
echo 'Number:'.$row['id'];echo "
";
echo 'Username:'.$ row['username'];echo "
";
echo 'Password:'.$row['password'];echo "
";
echo 'Email :'.$row['email'];echo "
";
echo "


";
}

} catch (PDOException $e) {
echo $e->getMessage();
}

In fact, it is to perform slightly repetitive operations without changing the sql statement every time.

Of course you can also change the placeholder

// $sql="insert user(username,password,email) values(?,?,?)";

// $stmt-> bindParam(1,$username);

So, anyway, Actually: placeholders would be clearer,? will be confused.

3.4 bindValue() implements binding parameters

Bind values ​​to parameters.

/*
* Binding parameters
*/

header('content-type:text/html;charset=utf-8');
try {
$pdo=new PDO('mysql:host=localhost;dbname=imooc','root ','');
$pdo->exec('use imooc_pdo');
$sql="insert user(username,password,email) values(:username,:password,:email)" ;
// $sql="insert user(username,password,email) values(?,?,?)";
$stmt=$pdo->prepare($sql);

//Assume the email parameter remains unchanged
$stmt->bindValue(":email", 'shit@shit.com');
$username ="Wade";$password="123";
$stmt->bindParam(":username", $username,PDO::PARAM_STR);
$stmt->bindParam(":password" ,$password);
$stmt->execute();
$res=$pdo->query("select * from user");
foreach ($res as $row){ //View the output results (based on the return situation)
// print_r($row);echo "
";
echo 'Number:'.$row['id'];echo "
";
echo 'Username:'.$row['username'];echo "
";
echo 'Password:'.$row['password '];echo "
";
echo 'Email:'.$row['email'];echo "
";
echo "


}


} catch (PDOException $e) {
echo $e->getMessage();
}

The application scenario is that when a certain value is fixed, the parameter value of the variable can be fixed.

3.5 bindColumn() method binding parameters

Will bind a column to a php object.

$pdo=new PDO('mysql:host=localhost;dbname=imooc','root','');
$pdo->exec('use imooc_pdo');
$sql ="select * from user";
$stmt=$pdo->prepare($sql);
$stmt->execute();
//Control output
$stmt->bindColumn(2, $username);
$stmt->bindColumn(3,$password);
$stmt->bindColumn (4,$email);
while ($stmt->fetch(PDO::FETCH_BOUND)){
echo 'Username:'.$username.'- Password: '.$password.' - Email: '.$email.'


';
}

The usage here is to control the output results, which is conducive to the control of the output format.

Of course, you can see how many columns there are in the result set and what each column is:

echo 'Number of columns in the result set:'.$stmt->columnCount().'


';
print_r($stmt->getColumnMeta(2));

3.6 fetchColumn() fetches a column from the result set

The above getColumnMeta() method is actually an experimental function in this version of PHP and may disappear in future versions.

$stmt->execute();

print_r($stmt->fetchColumn(3));

It should be noted that the troublesome part of this method is that every time it is executed, the pointer will move down one bit, so you only need to specify which column, but you don’t know which row it is in.

3.7 debugDumpParams() prints a prepared statement

Test this method in bindParam:

$stmt->debugDumpParams();

The result is a bunch of:

SQL: [71] insert user(username,password,email) values(:username,:password,:email) Params: 3 Key: Name: [9] :username paramno=-1 name=[9] " :username" is_param=1 param_type=2 Key: Name: [9] :password paramno=-1 name=[9] ":password" is_param=1 param_type=2 Key: Name: [6] :email paramno=-1 name=[6] ":email" is_param=1 param_type=2

That is to say, the details of preprocessing will be given.

Obviously this is a method designed for debugging.

3.8 nextRowset() method to retrieve all result sets

For example, it is used for mysql stored procedures (see my previous mysql blog posts), which can take out many result sets at once and then operate on the sets.

In fact, the pointer just moves down step by step.

I am too lazy to type the examples. . . .

Although I didn’t write much, that’s it.

I want to check my foot again in two days. Although it is still hurting, I don’t know if I dare to stimulate blood circulation. . . .

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1082310.htmlTechArticleI have a big rub-PDO (2), rub-pdo hi Yesterday it was 213 again, although I have roommates 3 It’s an objective effect of not going to bed until after midnight, but not wanting to study last night is the fundamental reason. Start it today. Planning on 3 or 4 days...
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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks 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)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1270
29
C# Tutorial
1250
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

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.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

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.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles