使用PHP为Postgres准备的语句

Léo*_* 준영 9 php database postgresql

这是一个类似的问题"何时不使用预备语句?" ,但使用"how-to"-part和PostgreSQL.

我知道我需要准备好的语句,因为我在一个脚本中对数据库进行了多次调用.

我想得到关于以下句子的具体例子

查看类型转换,验证和清理变量以及将PDO与预准备语句一起使用.

通过验证和消毒变量,我知道他的意思.但是,我并不完全确定准备好的陈述.我们如何准备陈述?通过过滤器,即通过消毒?或者通过一些PDO层?层的定义是什么?

准备好的陈述在声明中意味着什么?请使用具体的例子.

Gla*_*bot 6

这意味着它将通过消除手动引用参数的需要来帮助您防止SQL注入攻击.

您不必将变量放入sql中,而是使用命名或问号标记,在执行语句时将替换实际值.

从PHP手册中定义PDO:
'PHP数据对象(PDO)扩展定义了一个轻量级,一致的接口,用于访问PHP中的数据库.

请参阅PDOPDO :: prepare上的php手册.

具有命名标记的预准备语句的示例:

<?php
$pdo = new PDO('pgsql:dbname=example;user=me;password=pass;host=localhost;port=5432');

$sql = "SELECT username, password
FROM users
WHERE username = :username
AND password = :pass";

$sth = $pdo->prepare($sql);
$sth->execute(array(':username' => $_POST['username'], ':pass' => $_POST['password']));
$result = $sth->fetchAll();
Run Code Online (Sandbox Code Playgroud)

带有问号标记的预准备语句的示例:

<?php
$pdo = new PDO('pgsql:dbname=example;user=me;password=pass;host=localhost;port=5432');

$sql = "SELECT username, password
FROM users
WHERE username = ?
AND password = ?";

$sth = $pdo->prepare($sql);
$sth->execute(array($_POST['username'], $_POST['password']));
$result = $sth->fetchAll();
Run Code Online (Sandbox Code Playgroud)


kar*_*m79 5

准备好的陈述在声明中意味着什么?

文档:

此功能允许重复使用的命令只被解析和计划一次,而不是每次执行时.

pg_prepare

上面链接的页面示例:

<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');

// Execute the prepared query.  Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));

// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
?>
Run Code Online (Sandbox Code Playgroud)

准备语句MySQL文档很好地回答了以下问题:

  • 为何使用准备好的陈述
  • 什么时候应该使用准备好的陈述