Reputation: 157
I did a very short and simple PHP .
The output is an array in json. However it doesn't work .
The array-items are always null.
I guess it must have something to do with mistakenly calling the db table columns
('id' => $row->MASTER_ID
).
Whereas 'MASTER_ID
' is the name of the column in my db.
I'd be very glad if someone could point me in the right direction. My script looks as follows:
<?php
$db = new PDO('mysql:host=xxx;dbname=xx;charset=utf8mb4', 'xx', 'xxx');
$month = date('Y-m');
$monthwild = "$month%";
$sql = ("SELECT * FROM MASTER WHERE START_DATE LIKE '". $monthwild ."'");
$out = array();
foreach($db->query($sql) as $row) {
$out[] = array(
'id' => $row->MASTER_ID,
'title' => $row->MASTER_TITLE,
'start' => strtotime($row->MASTER_START),
'end' => strtotime($row->MASTER_END)
);
}
echo json_encode(array('success' => 1, 'result' => $out));
exit;
?>
I'm new to PDO (used to do things like this with mysql) and
I didn't get it yet and didn't find the right resources
Upvotes: 0
Views: 267
Reputation: 11689
PDO::query
“executes an SQL statement, returning a result set as a PDOStatement object,” not a row.
You have to put the result in a variable and then retrieve rows from this variable:
$result = $db->query( $sql );
while( $row = $result->fetchObject() )
{
(...)
}
As alternative, you can set a default fetch mode and then retrieve single rows with:
$result = $db->query( $sql );
$result->setFetchMode( PDO::FETCH_OBJ );
while( $row = $result->fetch() )
{
(...)
}
Actually, also direct foreach
works, but without a specific fetch mode it returns enumerated and associative result:
foreach( $db->query( $sql ) as $row )
{
$id = $row['MASTER_ID'];
// $id = $row[0]; // ← Alternative
}
To use objects with direct foreach
you have to use this syntax:
foreach( $db->query( $sql, PDO::FETCH_OBJ ) as $row )
{
$id = $row->MASTER_ID;
}
Upvotes: 1
Reputation: 21
I'd say that your definition of $monthwild is wrong. The right notation for that what you want to write is: $monthwild = $month."%"; In your script is the content of $monthwild the string "$month%" Now is the content of $monthwild the string %
I hope you can understand that. It is not easily described.
Upvotes: 1