PDO 和 INSERT INTO 通过准备好的语句 [英] PDO with INSERT INTO through prepared statements

查看:38
本文介绍了PDO 和 INSERT INTO 通过准备好的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PHP 丛林中的冒险之旅:数据对象 我在通过准备好的语句执行 MySQL 查询时遇到了问题.

On my adventure through the jungles of PHP: Data Objects I've encountered a problem with executing MySQL queries through prepared statements.

观察以下代码:

$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();

这就是我,我想出现在我的数据库中.然而我一直迷失在……嗯……我不知道!根据谷歌的说法,这是这样做的方法,尽管我的数据库保持为空.

This is me, and I want to be in my database. However I keep getting lost in.. well.. I don't know! According to google this is the way to do it, though my database stays empty.

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

Am I missing something here? Because I've been stuck for a good hour now and would like to continue studying PDO!

推荐答案

你应该像这样使用它

<?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)
    VALUES (:fname, :sname, :age)');

$statement->execute([
    'fname' => 'Bob',
    'sname' => 'Desaunois',
    'age' => '18',
]);

准备好的语句用于清理您的输入,为此您可以使用 :foo 没有 SQL 中的任何单引号来绑定 变量,然后在 execute() 函数中传入您在 SQL 语句中定义的变量的关联数组.

Prepared statements are used to sanitize your input, and to do that you can use :foo without any single quotes within the SQL to bind variables, and then in the execute() function you pass in an associative array of the variables you defined in the SQL statement.

你也可以使用 ? 而不是 :foo 然后像这样传入一个只有值的数组来输入;

You may also use ? instead of :foo and then pass in an array of just the values to input like so;

$statement = $link->prepare('INSERT INTO testtable (name, lastname, age)
    VALUES (?, ?, ?)');

$statement->execute(['Bob', 'Desaunois', '18']);

这两种方式各有优缺点.我个人更喜欢绑定参数名称,因为这样更容易阅读.

Both ways have their advantages and disadvantages. I personally prefer to bind the parameter names as it's easier for me to read.

这篇关于PDO 和 INSERT INTO 通过准备好的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆