我一直在阅读StackOverFlow中的很多帖子和php dot net的文档信息。
这是我尝试的代码:
示例1
$id = 1;
$sth = $this->pdo->prepare('SELECT * FROM USERS_TABLE WHERE ID_USR = ?');
$sth->execute(array(intval($id)));
示例2
$id = 1;
$sth = $this->pdo->prepare('SELECT * FROM USERS_TABLE WHERE ID_USR = :id');
$sth->bindParam(':id', $id, PDO::PARAM_INT);
$sth->execute();
示例3
$id = 1;
$sth = $this->pdo->prepare('SELECT * FROM USERS_TABLE WHERE ID_USR = :id');
$sth->bindValue(':id', intval($id));
$sth->execute();
如果我试试这个:
$sth = $this->pdo->prepare('SELECT * FROM USERS_TABLE WHERE ID_USR = 1');
$sth->execute();
我得到了我期待的结果,但这不是我正在寻找的解决方案。
希望你能提前帮助我。
//////////编辑1
在所有这些例子的最后我都是这样做的:
$arr = $sth->errorInfo();
print_r($arr);
回报是:
数组([0] => 00000 [1] => [2] =>)
///////////编辑2
这是代码
class User {
private $registry;
private $userId;
private $userLan;
private $fullName;
private $dob;
private $email;
private $sex;
private $nationality;
private $valid; // User valid?
private $pdo; // PDO reference
/**
* Constructor del usuario. Se puede construir de dos formas, pasando email y password o pasando una id de usuario.
* @param Registry $registry.
* @param Int $id
* @param String $email
* @param String $password
* @param String $username
* @return void
*/
public function __construct ( Registry $registry, $id, $email, $password, $username)
{
echo "constructor user with id = $id ";
$this->valid = false;
$this->registry = $registry;
if($id = 0 && $username != '' && $password != '')
{
// ...
$this->valid = true;
}
//else if($id > 0)
else
{
// $id = intval($id);
echo "second if";
$this->pdo = $registry->getObject('db')->getPdo();
try
{
$sth = $this->pdo->prepare('SELECT * FROM USERS_TABLE WHERE ID_USR = :id');
$sth->execute(array(':id' => intval($id)));
//$sth->execute(array(intval($id)));
$arr = $sth->errorInfo();
print_r($arr);
$result = $sth->fetch(PDO::FETCH_BOTH);
print_r($result);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
echo "passing query";
if($sth->rowCount() ==1)
echo "yeeeha";
else
echo "not yeeha (".$sth->rowCount().") ";
// ...
$this->valid = true;
}
}
答案 0 :(得分:0)
您的错误检查看起来不正确:
$sth = $this->pdo->prepare('SELECT * FROM USERS_TABLE WHERE ID_USR = :id');
$sth->bindParam(':id', $id, PDO::PARAM_INT);
$sth->execute();
$arr = $sth->errorInfo();
这假设PDO::prepare()
总是返回一个对象,但这不是documentation所说的:
返回值
如果数据库服务器成功准备了语句, PDO :: prepare()返回一个PDOStatement对象。 如果是数据库服务器 无法成功准备语句,PDO :: prepare()返回 FALSE或发出PDOException (取决于错误处理)。
我建议您让生活更轻松,并配置PDO以抛出异常。这个例子是from the manual:
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
^^^^^^^^^^^^^^^^^^^^^^
答案 1 :(得分:0)
我讨厌猜测,但我能找到的唯一明智的解释是$ id和缺少错误报告的问题