【问题标题】:Slim Framework PDO PGSQL, Not Binding ParametersSlim 框架 PDO PGSQL,不绑定参数
【发布时间】:2016-07-07 23:45:40
【问题描述】:

我在使用 PDO 绑定参数时遇到了一点问题。

我的设置如下。

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

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

我可以从一个表中获取所有记录,我可以让 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;
}
?>

index.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() .'}}';
}
}

我不知道哪里会出错。任何指导将不胜感激。

提前致谢。

【问题讨论】:

    标签: php postgresql pdo slim


    【解决方案1】:

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

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

    【讨论】:

    • 完成了,现在我得到以下错误而不是 SQL:[53] SELECT * FROM contacts WHERE contact_id = :contact_id Params: 1 Key: Name: [11] :contact_id paramno=0 name=[11 ] ":contact_id" is_param=1 param_type=1 {"Contact": null} 。有什么想法吗?
    猜你喜欢
    • 2015-09-07
    • 2017-01-29
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多