猿问

通过准备好的语句使用INSERT INTO进行PDO

在穿越PHP:数据对象的丛林中,我遇到了通过准备好的语句执行MySQL查询的问题。


观察以下代码:


$dbhost = "localhost";

$dbname = "pdo";

$dbusername = "root";

$dbpassword = "845625";


$link = new PDO("mysql:host=$dbhost;dbname=$dbname","$dbusername","$dbpassword");


$statement = $link->prepare("INSERT INTO testtable(name, lastname, age)

        VALUES('Bob','Desaunois','18')");


    $statement->execute();

这就是我,我想进入我的数据库。但是我一直迷路在..好吧..我不知道!根据谷歌,这是做到这一点的方法,尽管我的数据库仍然是空的。


我在这里想念什么吗?因为我已经被困了一个小时,所以我想继续学习PDO!


慕婉清6462132
浏览 886回答 3
3回答

炎炎设计

你应该像这样使用它<?php$dbhost = 'localhost';$dbname = 'pdo';$dbusername = 'root';$dbpassword = '845625';$link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);$statement = $link->prepare('INSERT INTO testtable (name, lastname, age)&nbsp; &nbsp; VALUES (:fname, :sname, :age)');$statement->execute([&nbsp; &nbsp; 'fname' => 'Bob',&nbsp; &nbsp; 'sname' => 'Desaunois',&nbsp; &nbsp; 'age' => '18',]);准备的语句用于清理输入,并且您可以在SQL中使用这些语句:foo 而无需任何单引号来绑定变量,然后在execute()函数中传递在SQL语句中定义的变量的关联数组。您也可以使用?代替,:foo然后像这样传递仅输入值的数组;$statement = $link->prepare('INSERT INTO testtable (name, lastname, age)&nbsp; &nbsp; VALUES (?, ?, ?)');$statement->execute(['Bob', 'Desaunois', '18']);两种方式都有其优点和缺点。我个人更喜欢绑定参数名称,因为它更易于阅读。

森栏

我刚刚将代码重写为以下代码:&nbsp; &nbsp; $dbhost = "localhost";&nbsp; &nbsp; $dbname = "pdo";&nbsp; &nbsp; $dbusername = "root";&nbsp; &nbsp; $dbpassword = "845625";&nbsp; &nbsp; $link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);&nbsp; &nbsp; $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);&nbsp; &nbsp; $statement = $link->prepare("INSERT INTO testtable(name, lastname, age)&nbsp; &nbsp; &nbsp; &nbsp; VALUES(?,?,?)");&nbsp; &nbsp; $statement->execute(array("Bob","Desaunois",18));它现在似乎可以正常工作。但。如果我故意造成错误发生,则表示没有错误。该代码有效,但仍然有效;如果我遇到更多错误,我将不知道为什么。

拉风的咖菲猫

请在代码中也添加try catch,以确保没有例外。try {&nbsp; &nbsp; $hostname = "servername";&nbsp; &nbsp; $dbname = "dbname";&nbsp; &nbsp; $username = "username";&nbsp; &nbsp; $pw = "password";&nbsp; &nbsp; $pdo = new PDO ("mssql:host=$hostname;dbname=$dbname","$username","$pw");&nbsp; } catch (PDOException $e) {&nbsp; &nbsp; echo "Failed to get DB handle: " . $e->getMessage() . "\n";&nbsp; &nbsp; exit;&nbsp; }
随时随地看视频慕课网APP
我要回答