PDO = "PHP DATABASE OBJECT"
1. Select
$dsn= "Mysql:host=127.0.0.1;port=3306;dbname=dbname"; $DBH=NewPDO ($dsn, ' root ', ' password ');$sql= "SELECT * FROM table_name WHERE name =: Name and PWD =:p WD";$sth=$DBH->prepare ($sql);$sth->bindvalue (': Name ', ' user ');$sth->bindvalue (':p wd ', ' password ');$sth-execute ();foreach($sth as $row) { Echo Var_dump($row); } $DBH=NULL;
$dsn= "Mysql:host=127.0.0.1;port=3306;dbname=dbname"; $DBH=NewPDO ($dsn, ' root ', ' password ');$sql= "SELECT * FROM table_name WHERE name =?" and PWD =? ";$sth=$DBH->prepare ($sql);$sth->bindvalue (1, ' user ');$sth->bindvalue (2, ' password ');$sth-execute ();foreach($sth as $row) { Echo Var_dump($row); } $DBH=NULL;
2. UPDATE
$dsn= "Mysql:host=127.0.0.1;port=3306;dbname=dbname"; $DBH=NewPDO ($dsn, ' root ', ' password ');$sql= "UPDATE table_name set name =: name WHERE id =: id";$sth=$DBH->prepare ($sql);$sth->bindvalue (': Name ', ' user ');$sth->bindvalue (': Id ', ' 1 ');$flag=$sthExecute ();//true or False$DBH=NULL;
$dsn= "Mysql:host=127.0.0.1;port=3306;dbname=dbname"; $DBH=NewPDO ($dsn, ' root ', ' password ');$sql= "UPDATE table_name set name =?" WHERE id =? ";$sth=$DBH->prepare ($sql);$sth->bindvalue (1, ' user ');$sth->bindvalue (2, ' 1 ');$flag=$sthExecute ();//true or False$DBH=NULL;
3. Insert
$dsn= "Mysql:host=127.0.0.1;port=3306;dbname=dbname"; $DBH=NewPDO ($dsn, ' root ', ' password ');$sql= "INSERT into table_name (name) VALUES (: Name)";$sth=$DBH->prepare ($sql);$sth->bindvalue (': Name ', ' user ');$flag=$sthExecute ();//true or False$DBH=NULL;
$dsn= "Mysql:host=127.0.0.1;port=3306;dbname=dbname"; $DBH=NewPDO ($dsn, ' root ', ' password ');$sql= "INSERT into table_name (name) VALUES (?)";$sth=$DBH->prepare ($sql);$sth->bindvalue (1, ' user ');$flag=$sthExecute ();//true or False$DBH=NULL;
4. Delete
$dsn= "Mysql:host=127.0.0.1;port=3306;dbname=dbname"; $DBH=NewPDO ($dsn, ' root ', ' password ');$sql= "DELETE from table_name WHERE id =: id";$sth=$DBH->prepare ($sql);$sth->bindvalue (': Id ', ' 1 ');$flag=$sthExecute ();//true or False$DBH=NULL;
$dsn= "Mysql:host=127.0.0.1;port=3306;dbname=dbname"; $DBH=NewPDO ($dsn, ' root ', ' password ');$sql= "DELETE from table_name where id =?";$sth=$DBH->prepare ($sql);$sth->bindvalue (1, ' 1 ');$flag=$sthExecute ();//true or False$DBH=NULL;
The second piece of code in each section is used to bind parameters in the same way as the number index, and some people may not understand the difference between the post-binding and the direct generation of the SQL statement, but it is not difficult to understand.
Suppose you enter:
Select * from where = ?
The part of the question mark can become this way if it is generated directly
Select * from where = 1 or 1 = 1
If you bind dynamically, the question mark section is limited to entering a variable that conforms to the ID field type, and if there is SQL injection it compiles
PDO DEMO in PHP