通过准备好的语句使用INSERT INTO进行PDO [英] PDO with INSERT INTO through prepared statements

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

问题描述

在穿越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();

这是我,我想进入我的数据库. 但是我一直迷路在..很好..我不知道! 根据google的说法,这是做到这一点的方法,尽管我的数据库仍然为空.

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中使用任何单引号对 bind 进行变量,然后在在您在SQL语句中定义的变量的关联数组中传递的execute()函数.

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.

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

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