Basic use of pr...LOGIN

Basic use of prepared statements

1, Use of preprocessed sql statement prepared

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/5 0005
 * Time: 上午 9:23
 */
header("Content-Type:text/html;charset=utf-8");
//mysql:host:localhost;port=3306;dbname=php;charset=utf-8
$dbms='mysql';
$host='localhost';
$port='3306';
$dbname='php';
$charset='utf-8';
//用户名与密码
$user='root';
$pwd='root';
$dsn="$dbms:host=$host;port=$port;dbname=$dbname;charset=$charset";
try{
    $pdo=new PDO($dsn,$user,$pwd);
    //预处理sql语句
    $stmt=$pdo->prepare("insert into book(name,author)values(?,?)");
}catch (PDOException $exception){
    echo $exception->getMessage().'<br>';
}

2, Parameter binding

<?php
$name='java基础教程';
$author='smile4';
$stmt->bindParam(1,$name);
$stmt->bindParam(2,$author);

3, execute the prepared statement

<?php
$stmt->execute();

The whole code is as follows:

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/5 0005
 * Time: 上午 9:23
 */
header("Content-Type:text/html;charset=utf-8");
//mysql:host:localhost;port=3306;dbname=php;charset=utf-8
$dbms='mysql';
$host='localhost';
$port='3306';
$dbname='php';
$charset='utf-8';
//用户名与密码
$user='root';
$pwd='root';
$dsn="$dbms:host=$host;port=$port;dbname=$dbname;charset=$charset";
try{
    $pdo=new PDO($dsn,$user,$pwd);
    //预处理sql语句
    $stmt=$pdo->prepare("insert into book(name,author)values(?,?)");
    $name='java基础教程';
    $author='smile4';
    $stmt->bindParam(1,$name);
    $stmt->bindParam(2,$author);
    $stmt->execute();
    //$sql='select *from book';
    //$result=$pdo->query($sql);
    //$row=$result->fetchAll();
    //echo "<pre>";
    //print_r($row);
    //echo "</pre>";
}catch (PDOException $exception){
    echo $exception->getMessage().'<br>';
}

Browser execution result display:

微信图片_20180305104141.png

Thinking: How to add data in batches and prevent SQL injection? (will be introduced in the next two sections)


Next Section
<?php echo "PDO预处理操作";
submitReset Code
ChapterCourseware