您的位置:首页 > 数据库

PDO中最推荐使用的方式来执行SQL语句

2017-08-28 15:10 393 查看
<?php

    try{

        $pdo=new PDO("mysql:host=localhost;dbname=bookstore","root","158369");

        echo "数据库连接成功!<br>";

    }

    catch(PDOexception $e){

        echo "数据库连接失败!".$e->getmessage()."<br>";

    }

    

    try{
        //1.传统的方式:将SQL发给数据库系统并直接执行

        //$pdo->exec("insert into salary(name,age,education,salary)values('liu',23,'high',2222)");

        
        /*2.最简单的方式来执行SQL语句:pdo类中的execute方法中传一个数组参数来赋值,建议使用这种方式

        $statme=$pdo->prepare("insert into salary(name,age,educatino,salary)values(:name,:age,:education,:salary)");

        //与上面名称索引一一对应

        $statme->execute(array("name"=>"liuhui3","age"=>"32","education"=>"Junior","salary"=>"2234"));

        */

        //通过索引参数一样能赋值

        $statme=$pdo->prepare("insert into salary(name,age,educatino,salary)values(?,?,?,?)");

        $statme->execute(array("liuhui4","3","Junior","3334"));

            

        echo "数据插入成功!<br>";

    }

    catch(PDOexception $e){

        echo "数据插入失败!".$e->getmessage();

    }

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息