I'm quering my database, and want to write a foreach loop, that goes trough my result set, and runs strtotime on the timestamp, in order to use it on my webpage (I want to adjust the array["posted"] value to strtotime(array["posted"]).
I am new to php and PDO, and can't figure out what's wrong with my foreach loop. The warning I get is Warning: Invalid argument supplied for foreach() in /home/shooshte/Dropbox/PTC_php/db_queries/articles.php on line 29 .
I guess I'm targeting the $result array wrong? Can anyone explain how to fix this? The timestamp is in the column called posted, which is also the key inside my array.
Thanks for the help.
my php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
try {
$hostname = "localhost";
$username = "root";
$password = "";
$db = new PDO("mysql:host=$hostname;dbname=topdecka_PTC",$username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!empty($_POST["searchword"])) {
$searchword = $_POST["searchword"];
$query = $db->prepare("SELECT title, posted, author_id, extract FROM articles WHERE title LIKE :searchword OR extract LIKE :searchword OR body LIKE :searchword");
$query->execute(array(":searchword" => "%" . $searchword . "%"));
$result = $query->fetchAll();
echo json_encode($result);
die();
}
else {
$query = $db->prepare('SELECT posted FROM articles');
$query->execute();
$result = $query->fetchAll();
foreach($result as $row) {
$row['posted'] = strtotime($row['posted']);
}
echo '<pre>';
var_dump($result);
echo '</pre>';
//echo json_encode($result);
die();
}
}
catch (PDOException $e) {
echo "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Here's the var_dump:
array(2) {
[0]=>
array(2) {
["posted"]=>
string(19) "2015-06-10 11:16:46"
[0]=>
string(19) "2015-06-10 11:16:46"
}
[1]=>
array(2) {
["posted"]=>
string(19) "2015-06-10 13:26:54"
[0]=>
string(19) "2015-06-10 13:26:54"
}
}
var_dump($result);display? - honerlawd