繁体   English   中英

Php PDO请求派生表列之和的数据

[英]Php PDO request for data from the sum of a derived table column

这是我试图在一些php PDO代码中使用的SQL查询:

SELECT SUM(credit_hours) AS hours FROM(SELECT Course_List.credit_hours FROM Program_Courses,    Course_List 
WHERE program_id= :pid and concentration_id= :conid 
and fulfills_major=1 and Program_Courses.course_id = Course_List.course_id ) AS major_credits

当我在SQL Workbench中对我的数据库运行此查询时,我得到一个派生表,其中包含一个名为“hour”的列和一个值为76的单行。

这是我用来尝试将相同的数据存储在变量$ major_hours中的PHP代码:

$result = $conn->prepare("SELECT * FROM students WHERE username = :un");    
    $result->bindParam(':un',$user);
    $result->execute();
    $data = $result->fetch(PDO::FETCH_ASSOC);   //returns an associated array where the indices are the column names
    $program = $data['program_id'];
    $concentration = $data['concentration_id'];

    //get the total number of credit hours in the student's major/concentration
    $result = $conn->prepare("SELECT SUM(credit_hours) AS hours FROM(
                                SELECT Course_List.credit_hours FROM Program_Courses, Course_List 
                                WHERE program_id= :pid and concentration_id= :conid 
                                and fulfills_major=1 and Program_Courses.course_id = Course_List.course_id 
                                ) AS major_credits");
    $result->bindParam(':pid',$program);
    $result->bindParam(':conid',$concentration);
    $result->execute();
    $major_hours = $result->fetchColumn();

我知道变量$ user,$ program和$ concentration都有合法的值,因为当我回显那些页面时,我得到了正确的结果。 然而,回应$ major_hours绝对没有。 我究竟做错了什么?

我没有使用过sql workbench,但你可能想在SUM(credit_hours)表达式上使用isnull()或coalesce()。 我认为这应该导致$ major_hours显示0。

使用fetch,因为你可能猜到它从结果集中获取下一行fetch_style参数确定PDO如何返回行,在你的情况下, FETCH_ASSOC将是一个好的,因为它返回一个由列名称索引的数组,如结果集中返回的那样。

$row = $result->fetch(PDO::FETCH_ASSOC);//row is an associative array
$major_hours = $row['hours'];           //access the column name hour
echo $majors_hours;                     //will print the hour value from db

用这个

$major_hours = $result->fetch(PDO::FETCH_ASSOC);
echo $majors_hours['hours'];

有两种方法可以从数据库返回数据。 fetch(PDO::FETCH_ASSOC)fetchAll(PDO::FETCH_ASSOC) Fetch仅从数据库中返回1行..但fetchAll将返回您所做的数据库查询中的所有行。

(PDO::FETCH_ASSOC)它意味着将使用数组返回数据。

暂无
暂无

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

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