php - Slim框架PDO PGSQL,不绑定(bind)参数

标签 php postgresql pdo slim

我在 PDO 绑定(bind)参数方面遇到了一些问题。

我的设置如下。

  • Ubuntu 桌面版 16.04
  • Netbeans 8.1(仅限 php 和 html 版本)
  • php cli 7.0.4(运行内部网络服务器)
  • Postgres SQL 9.5
  • 精简框架 3

我已选择使用 PDO 访问我的数据库。这是我为 future 项目学习的系统。

我可以从表中获取所有记录,我可以获取 uri 中发出的参数以在屏幕上回显。

但是使用 GET 方法定位特定条目会向我抛出以下错误。

{"error":{"text":SQLSTATE[08P01]: <>: 7 ERROR: bind message supplies 0 parameters, but prepared statement "pdo_stmt_00000001" requires 1}}

以下是我的代码。

db.php

<?php
function getDB() {
    $dbtype="pgsql";
    $dbhost="localhost";
    $dbuser="postgres";
    $dbpass="SomeSecurePassword";
    $dbname="bms";
    $dbConnection = new PDO("$dbtype:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbConnection;
}
?>

索引.php

<?php

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require 'vendor/autoload.php';
require 'db.php';

$app = new \Slim\App;

$app->get('/','getRoot');
$app->get('/contacts', 'getContacts');
$app->get('/contacts/{contact_id}', 'getContact');

$app->run();

function getRoot() {
echo 'This is the Root URI';
}

function getContacts() {
$sql = "SELECT last_name,first_name FROM contacts ORDER BY last_name DESC";
try {
    $db = getDB();
    $stmt = $db->query($sql);
    $contacts = $stmt->fetchAll(PDO::FETCH_OBJ);
    $db = null;
    echo '{"Contacts": ' . json_encode($contacts) . '}';
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

function getContact(Request $request, Response $response, $args) {
$contact_id = (int)$args['contact_id'];
$sql = "SELECT * FROM contacts WHERE contact_id = :contact_id";
try {
    $db = getDB();
    $stmt = $db->query($sql);
    $stmt->bindParam(':contact_id', $contact_id, PDO::PARAM_INT);
    $stmt->execute();
    $stmt->debugDumpParams();
    $db = null;
    echo '{"Contact": ' . json_encode($contact) . '}';
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

我哪里出错了?

最佳答案

您需要使用准备好的语句。

$stmt = $db->query($sql); //Executes a query and returns a statement

你想要的是...

$stmt = $db->prepare($sql);
$stmt->bindParam(':contact_id', $contact_id, PDO::PARAM_INT);
$stmt->execute();

关于php - Slim框架PDO PGSQL,不绑定(bind)参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38256953/

相关文章:

php - MySQL - 在查询中插入验证

php - 使用 jQuery、PHP 和 MySQL 为单选按钮加载 JSON 数据

PHP Preg 替换之间的行

php - PDO - 动态查询构建

postgresql - plpgsql:我们如何将 "max"值赋给 varchar 数据类型?

postgresql - 无法使用对等身份验证在没有密码的情况下运行 `mix ecto.migrate`

PHP - 如何在 php 中检索 session

php - CodeIgniter 不加载模型

postgresql - 如何拆分具有重叠多边形的多边形并计算 PostgreSQL 中的重叠?

php - pdo_mysql 在 centos 6.7 上不可用