預處理語句基礎使用
1,預處理sql語句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,參數綁定
<?php $name='java基础教程'; $author='smile4'; $stmt->bindParam(1,$name); $stmt->bindParam(2,$author);
3,執行預處理語句
<?php $stmt->execute();
全部程式碼如下:
<?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>'; }
#瀏覽器執行結果展示:
思考:如何大量新增資料與防sql注入處理? (下兩節會介紹)