0

我有这个查询:

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

我正在使用这段代码来做一个preparedstatement

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() 总是假的。

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

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

所以查询返回一行,但它没有被 php 捕获。我错过了什么?我怎样才能解决这个问题?

4

1 回答 1

0

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

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

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

编辑

来自文档

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

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

/* bind result variables */
$stmt->bind_result($name, $code);
于 2013-04-18T12:43:08.330 回答