Print_r 和 foreach 给出不同的结果
我有一个 pdo 函数,可以从数据库中获取用户名和用户 ID。当我运行该函数时,我得到不同的结果。
print_r 给出
Array ( [ID] => 58 [username] => abdullatif )
,foreach 给出
5-5a-a
有一行与数据库中的 pdo 查询匹配。
public function getUserCredentials($userName, $password){
$this->db = new Dbpdo_Database();
$this->db->connect();
try{
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT
ID
FROM
administrators
WHERE
username = :username
AND
user_password = :password
LIMIT 1");
$stmt->bindParam(':username', $userName, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
}
$stmt->execute();
/*** fetch the results ***/
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
/*** close the database connection ***/
//$dbh = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
$results = $mydb->getUserCredentials($userName, $password);
foreach ($results as $row){
echo $row['ID'].'-'.$row['username'];
}
print_r($results);
任何有关问题所在的提示将不胜感激。提前致谢。
I have a pdo function that fetches usernames and user ids from the database. When I run the function i get different results.
print_r gives
Array ( [ID] => 58 [username] => abdullatif )
and foreach gives me
5-5a-a
There is one row that matches the pdo query in the database.
public function getUserCredentials($userName, $password){
$this->db = new Dbpdo_Database();
$this->db->connect();
try{
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT
ID
FROM
administrators
WHERE
username = :username
AND
user_password = :password
LIMIT 1");
$stmt->bindParam(':username', $userName, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
}
$stmt->execute();
/*** fetch the results ***/
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
/*** close the database connection ***/
//$dbh = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
$results = $mydb->getUserCredentials($userName, $password);
foreach ($results as $row){
echo $row['ID'].'-'.$row['username'];
}
print_r($results);
Any hints as to whats wrong would be much appreciated. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
$results
数组是一维的 - 它有一个 ID 和一个用户名。您的foreach
正在寻找一个二维数组,每行包含一个 ID 和一个用户名。将其更改为:你应该得到:
Your
$results
array is one-dimensional - it has an ID and a username. Yourforeach
is looking for a two-dimensional array, with each row containing an ID and a username. Change it to:and you should get: