select语句的问题mysql
问题描述:
这让我烦了一阵子。我正在使用phpmyadmin中的query
。select语句的问题mysql
select `id` from `users` where `fb_id` = 507292797 limit 1
这将返回值13
,所以为什么不这项工作:
$sql = "select `id` from `users` " .
"where `fb_id` = :fb_id " .
"limit 1";
try
{
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':fb_id', $fb_id2, PDO::PARAM_INT);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $stmt->execute();
$stmt->closeCursor();
}
catch (Exception $e)
{
die ($e->getMessage());
}
echo "id: " . $fb_id2 . " var_dump: " . var_dump($user);
exit();
这将返回:
ID:507292797
的var_dump:bool(false)
当的var_dump应该返回$user['id'] = 13
有人可以看到我在这里做错了吗?
ps。这里是我的数据库连接功能,如果这个问题
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
$driver_options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8');
try
{
$this->db = new PDO($dsn, DB_USER, DB_PASS, $driver_options);
答
你正在做的事情按以下顺序:
- 准备语句
- 绑定变量
- 试图从声明 获取数据
- 执行语句
最后两步应该是相反的顺序:您必须先执行语句,然后才能获取数据(即通过执行它获得)。
基本上,而不是使用这样的:
// fetch, then execute ???
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $stmt->execute();
您应该使用:
// Execute, **then** fetch
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
答
看起来你是在执行前取?