使用php的PreparedStatement选择不按预期工作

时间:2013-04-18 12:31:02

标签: php sql select prepared-statement

我有这个问题:

SELECT id, result, ip_address, added_date
FROM results
WHERE course_id = ( 
SELECT id
FROM courses
WHERE course =  'informatica'
AND macro_course_id = ( 
SELECT id
FROM macro_courses
WHERE macro_course =  'scienze-matematiche-fisiche-e-naturali'
AND organization_id = ( 
SELECT id
FROM organizations
WHERE organization =  'universita-degli-studi-di-torino'
AND city_id = ( 
SELECT id
FROM cities
WHERE city =  'torino'
AND region_id = ( 
SELECT id
FROM regions
WHERE region =  'piemonte' ))))) ORDER BY id DESC

我正在使用此代码与预备陈述

public function getResults($region, $city, $organization, $macro_course, $course) { //works
    //added_date=datetime : YYYY-MM-DD HH:mm:ss
    echo "SELECT id, result, ip_address, added_date
    FROM results
    WHERE course_id = ( 
    SELECT id
    FROM courses
    WHERE course =  '$course'
    AND macro_course_id = ( 
    SELECT id
    FROM macro_courses
    WHERE macro_course =  '$macro_course'
    AND organization_id = ( 
    SELECT id
    FROM organizations
    WHERE organization =  '$organization'
    AND city_id = ( 
    SELECT id
    FROM cities
    WHERE city =  '$city'
    AND region_id = ( 
    SELECT id
    FROM regions
    WHERE region =  '$region' ))))) ORDER BY id DESC"; //just for me to know what query is being executed 


    if ($stmt = $this->mysqli->prepare(("
    SELECT id, result, ip_address, added_date
    FROM results
    WHERE course_id = ( 
    SELECT id
    FROM courses
    WHERE course =  ?
    AND macro_course_id = ( 
    SELECT id
    FROM macro_courses
    WHERE macro_course =  ?
    AND organization_id = ( 
    SELECT id
    FROM organizations
    WHERE organization =  ?
    AND city_id = ( 
    SELECT id
    FROM cities
    WHERE city =  ?
    AND region_id = ( 
    SELECT id
    FROM regions
    WHERE region =  ? ))))) ORDER BY id DESC

  "))) {
        $return = array();
        $stmt->bind_param('sssss', $course, $macro_course, $organization, $city, $region);
        $stmt->execute();
        if ($stmt->fetch()) {
            $i = 0;
            while ($row = $stmt->fetch()) {
                print_r($row);//this is never reached
                continue;
                $s = new Result($row['result'], $row['added_date'], $row['id']);
                $return[$i] = $s;
                $i+=1;
            }
        }
    }
    return $return;
}

问题是此函数返回0行和0错误(使用$this->mysqli->error检查),似乎$ row = $ stmt-> fetch()始终为false。

但是,如果我在PHPMyAdmin上复制并执行我在函数顶部得到的输出,我看到了

Showing lines 0 - 0 ( 1 total, Query time 0.0003 sec)

因此查询返回一行,但不会被php捕获。我错过了什么?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

因为你在这里两次使用$stmt-fetch()

if ($stmt->fetch()) {
        $i = 0;
        while ($row = $stmt->fetch()) {

删除if ($stmt->fetch())条件,它将按预期工作。

修改

来自docs

请注意,在调用$ stmt-> fetch()之前,所有列都必须由应用程序绑定。

您必须在调用$stmt->fetch()之前绑定结果

/* bind result variables */
$stmt->bind_result($name, $code);