【问题标题】:PDO variable not working in query but static value worksPDO 变量在查询中不起作用,但静态值起作用
【发布时间】:2014-12-25 17:50:45
【问题描述】:

所以我的情况是这样的,我正在尝试根据 isset 正在获取的id 获取用户详细信息,但是有些variable that contains the $_GET value doesn't work 在查询中的方式,但是当我将静态值放入 pdo 查询然后它工作并显示结果。我在查询之前通过对变量$user 执行var_dump 进行了检查,它显示了正确的值,但在查询中不起作用。以下是我正在使用的代码:

public function profile_view($user_id = null) {
            $user = $user_id;
            $stmt = $this->_db->prepare('SELECT memberID,username,email,profile_pic,active FROM members WHERE memberID = :user_id AND active="YES"');
            $stmt->execute(array(':user_id'=>$user));
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $user_det = (object) array('username'=> $row['username'],'email'=>$row['email'],'profile_pic'=>$row['profile_pic'],'id'=> $row['memberID'],'active'=>$row['active']);

            return $user_det;
            }


    }

这就是函数的调用方式(profile_view 函数是 User 类的子函数,因此 $user 是 User 类):

 $view_profile = $user->profile_view($_GET['u']);

上面的代码返回 null 但是当我把静态值:5 放在$stmt->execute 中的$user 的地方它返回整个用户的详细信息,这是我需要的,但它不适用于令人困惑的变量我很多。

【问题讨论】:

  • 那么你有没有 var_dumped 你的_GET 值?
  • 你确定你检查了方法里面的值吗?
  • 请发布函数的调用方式,启用错误报告并发布错误(如果在抛出的错误告诉您问题后您仍然需要帮助)
  • 我 100% 确定当我对 $user 变量执行 var_dump 时,它会显示正确的值。但不知道为什么它在查询中不起作用。
  • @michael 错误报告开启根本没有错误,它只显示空结果。我正在用如何调用函数来更新我的问题。

标签: php mysql variables pdo


【解决方案1】:

你更正了 php 代码。 SQL 查询错误(可能)。我不知道你的SQL表。

示例 php 代码手册。此链接http://php.net/manual/en/pdostatement.execute.php

<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->execute(array(':calories' => $calories, ':colour' => $colour));
?>

您的 SQL 代码编辑和测试代码。

【讨论】:

  • 对我来说,我的整个代码似乎还可以,但没有得到 $user 变量的问题以及为什么静态值起作用,因为我也在函数内部完成了 $user 的 var_dump,它向我显示了正确的值$_GET。
【解决方案2】:

当您调用该函数时,您将$user_id 设置为null,无论通过它传递什么,而不是获取$user_id 的值。试试这个:

$user_id = 5; //Set this to whatever int you want whether it be via POST or GET
public function profile_view($user_id) { //Note that I don't set $user_id equal to anything
    //The rest of the code remains the same
    $user = $user_id;
    $stmt = $this->_db->prepare('SELECT memberID,username,email,profile_pic,active FROM members WHERE memberID = :user_id AND active="YES"');
    $stmt->execute(array(':user_id'=>$user));
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $user_det = (object) array('username'=> $row['username'],'email'=>$row['email'],'profile_pic'=>$row['profile_pic'],'id'=> $row['memberID'],'active'=>$row['active']);
        return $user_det;
        }
}

【讨论】:

  • $user_id = null 在函数调用中没有显式传递值时定义默认值。
  • 就像我提到的问题:我已经完成了 var_dump$user 内部函数,它向我展示了 $_GET 得到的正确值。与 null 无关。
猜你喜欢
  • 2013-03-15
  • 2012-03-15
  • 2014-08-12
  • 2014-12-09
  • 2014-01-31
  • 1970-01-01
  • 2016-11-16
  • 2016-10-05
  • 2012-01-12
相关资源
最近更新 更多