简体   繁体   English

在php中使用PDO时,从mysql数据库读取数组时出现问题

[英]Issues reading arrays from mysql database when using PDO in php

I have the following code set to read and output a specific row from a database based on the criteria in the query statement below. 我将以下代码设置为根据以下查询语句中的条件从数据库读取和输出特定行。 When I try to log the output in console, however, I am only able to get one value and while it DOES exist in the database (as a key attribute), it is from the first row every time. 但是,当我尝试在控制台中记录输出时,我只能获得一个值,尽管它确实存在于数据库中(作为键属性),但每次都从第一行开始。 I am not getting a row that matches the SQL criteria. 我没有得到与SQL条件匹配的行。 Any ideas? 有任何想法吗?

function getLoginInfo($email,$password){
    global $db_user, $db_password, $db_host, $db_name;

    if (isValidLogin($email,$password)){
        $dbconn = connectToDB($db_user, $db_password, $db_host, $db_name);
        $userInfoQuery = $dbconn->prepare("Select * from (Users as U inner join RegisteredUsers as R on U.UID = R.UID) where email = :email");
        $userInfoQuery->execute(array(":email"=> 'derp@gmail.com'));
        $results = $userInfoQuery->fetch(PDO::FETCH_ASSOC);     
        echo $results; //will return data in the form ["col1"=>rowdata,"col2"=>rowdata,..."colX"=>rowdata]
        }
    else{
        return false;
    }
}

You need to use a loop to fetch all the rows returned by your query: 您需要使用循环来获取查询返回的所有行:

while( $results = $userInfoQuery->fetch(PDO::FETCH_ASSOC) ) { 
    echo $results;
}

The documentation for the PDOStatement::fetch function says that the function "Fetches the next row from a result set", so it only returns one row. PDOStatement::fetch函数的文档说该函数“从结果集中获取下一行”,因此它仅返回一行。 If the PDOStatement::fetchAll functions that will return the full result set. 如果PDOStatement::fetchAll函数将返回完整的结果集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM