【问题标题】:PHP: Can't access class in SQL Statement [duplicate]PHP:无法访问 SQL 语句中的类 [重复]
【发布时间】:2016-07-22 13:39:33
【问题描述】:

我的 SQL 语句有一些问题。

require_once("Dozent.php");
.
.
.

public function findAll()
    {
        try {
            $stmt = $this->pdo->prepare('
              SELECT * FROM vorlesung WHERE id_dozent = $dozent->id;
            ');
            $stmt->execute();
            $stmt->setFetchMode(PDO::FETCH_CLASS, 'Vorlesung');
            return $stmt->fetchAll();

        } catch (PDOException $e) {
            echo("Fehler! Bitten wenden Sie sich an den Administrator...<br>" . $e->getMessage() . "<br>");
            die();
        }
    }

'id_dozent = $dozent->id' 这不起作用,我不知道为什么。当我插入像“1”这样的数字时,它按预期工作。

有人知道我做错了什么吗?

非常感谢! :-)

Edit1:完整代码:

<?php

require_once("Manager.php");
require_once("Vorlesung.php");

require_once("Dozent.php");
require_once("DozentManager.php");

class VorlesungManager extends Manager
{
    protected $pdo;

    public function __construct($connection = null)
    {
        parent::__construct($connection);
    }

    public function __destruct()
    {
        parent::__destruct();
    }

    public function findAll()
    {
        try {
            $stmt = $this->pdo->prepare('
              SELECT * FROM vorlesung WHERE "id_dozent = $dozent->id";
            ');
            $stmt->execute();
            $stmt->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'Vorlesung');
            return $stmt->fetchAll();
        } catch (PDOException $e) {
            echo("Fehler! Bitten wenden Sie sich an den Administrator...<br>" . $e->getMessage() . "<br>");
            die();
        }

    }

【问题讨论】:

标签: php sql class pdo where


【解决方案1】:

$dozent-&gt;id 没有在 function findAll() 中定义

你必须使用一个参数:

public function findAll($dozent)

在查询中包含该值的更正确方法是:

$stmt = $this->pdo->prepare('SELECT * FROM vorlesung WHERE id_dozent = ?');
$stmt->execute(array($dozent->id));

或者这个:

$stmt = $this->pdo->prepare('SELECT * FROM vorlesung WHERE id_dozent = :id');
$stmt->execute(array(':id' => $dozent->id));

【讨论】:

  • 非常感谢@CJ Nimes!它现在正在工作!
【解决方案2】:

尝试使用“... {$dozent->id};”。用双引号和括号。

【讨论】:

    猜你喜欢
    • 2015-11-30
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多