如何从PHP查询(PDO)中获取字段值

时间:2015-12-03 21:00:54

标签: php pdo

这里是PHP的新手,只使用PHP来创建我的json数据并且很难理解语法。这是一些部分代码:

我所要做的就是检索值'2af8ddda-2be4-11e5-9453-b82a72d52c35'并将其放入变量@sharepointID:

function selectWithSharepointID($table, $columns, $where){
try{
//Get Sharepoint file ID first
$stmt = $this->db->prepare("SELECT ID FROM table1 ORDER BY DownloadedTimeStamp DESC LIMIT 1");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);                                
//$data[] = array("ID" => $rows['ID']);
//$sharepointID = $data[0];            
//$sharepointID = $rows[0];
$where   = array('id'=>$sharepointID);      
//$where = array('id'=>'2af8ddda-2be4-11e5-9453-b82a72d52c35'); //this works fine
... 

PS:还尝试使用print_r和echo但是无法在控制台中看到任何内容。

谢谢

2 个答案:

答案 0 :(得分:1)

如果您只有一条记录,则不需要fetchAll。尝试:

$stmt = $this->db->prepare("SELECT ID FROM table1 ORDER BY DownloadedTimeStamp DESC LIMIT 1");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sharepointID = $row['ID'];

如果您有多个记录,fetchAll有意义,但是您会遍历该记录以获取每一行及其值。

对于我使用fetchAll ...

的粗略示例
$stmt = $this->db->prepare("SELECT name, userid FROM users");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
   echo 'Name: ' . $row['name'] . ' userid :' . $row['id'];
}

答案 1 :(得分:0)

此表达式返回行数组:

$stmt->fetchAll(PDO::FETCH_ASSOC);

因此,您可以在案例中从第0行获取数据:

$sharepointID = $rows[0]['ID'];