PHP fetchAll(PDO :: FETCH_ASSOC)在语句

时间:2018-04-29 10:27:41

标签: php pdo fetchall

我正在尝试使用PDO::FETCH_ASSOC获取插入数据库的数据。

由于某种原因(可能缺乏理解......)我无法回应类方法中的数据。

这是db表结构: enter image description here

我想将数据作为$fieldName['value'] => $fieldVal['value']

的关联数组执行

我有一个类,通过匹配tzyear值来从表中选择所有数据。 从print _r里面的函数中我收到了很好的数据。 如果我从类文件外部调用该方法,则将所有值都重置为null。

这是我的班级代码:

function dataExist($tz, $year){
    $tz = 303748891;
    $year = 2017;
    $query = "SELECT * FROM ". $this->table_name ." WHERE tz = ? AND year = ?";

    $stmt = $this->conn->prepare($query);

    $stmt->bindParam(1, $tz);
    $stmt->bindParam(2, $year);

    // execute query
    $stmt->execute();

    //get all data
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);


    echo '<pre>';
    print_r( $result);
    echo '</pre>';

    return $result;


}

这是我从班级print_r那边收到的好结果。

Array
(
    [0] => Array
        (
            [id] => 45
            [tz] => 303748891
            [fieldName] => tel
            [fieldVal] => 0547
            [year] => 2017
        )

    [1] => Array
        (
            [id] => 77
            [tz] => 303748891
            [fieldName] => fname
            [fieldVal] => Jon
            [year] => 2017
        )

    [2] => Array
        (
            [id] => 78
            [tz] => 303748891
            [fieldName] => lname
            [fieldVal] => black
            [year] => 2017
        )

    [3] => Array
        (
            [id] => 79
            [tz] => 303748891
            [fieldName] => tel
            [fieldVal] => 5555-555-55
            [year] => 2017
        )

    [4] => Array
        (
            [id] => 80
            [tz] => 303748891
            [fieldName] => mail
            [fieldVal] => aaa@aaa.aaa
            [year] => 2017
        )

    [5] => Array
        (
            [id] => 81
            [tz] => 303748891
            [fieldName] => fname
            [fieldVal] => James
            [year] => 2017
        )

    [6] => Array
        (
            [id] => 82
            [tz] => 303748891
            [fieldName] => lname
            [fieldVal] => White
            [year] => 2017
        )

    [7] => Array
        (
            [id] => 83
            [tz] => 303748891
            [fieldName] => tel
            [fieldVal] => 6669-666-666
            [year] => 2017
        )

    [8] => Array
        (
            [id] => 84
            [tz] => 303748891
            [fieldName] => mail
            [fieldVal] => bbb@bbb.bbb
            [year] => 2017
        )

)

这是来自其他文件的调用:

$dataExist = new Form($db);
$dataExist->dataExist($tz,$year);
echo '<pre>';
print_r( $dataExist);
echo '</pre>';

我收到了这个:

Form Object
(
    [conn:Form:private] => PDO Object
        (
        )

    [table_name:Form:private] => submisions
    [id] => 
    [tz] => 
    [fieldName] => 
    [fieldVal] => 
    [year] => 
)

1 个答案:

答案 0 :(得分:0)

您没有将对方法的调用结果分配给变量。变化

$dataExist->dataExist($tz,$year); 

$thedata = $dataExist->dataExist($tz,$year);

然后

print_r($thedata);

你会看到你的期望。