<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
}catch( PDOException $e ){
die("couldn't connect ".$e->getMessage());//gives error message
}
$statement = $pdo->prepare('select * from todos');
$statement->execute();
var_dump($statement->fetchAll());
?>output:
array (size=2)
0 =>
array (size=6)
'id' => string '1' (length=1)
0 => string '1' (length=1)
'name' => string 'jhgyukgyug uftfty utfotfotf' (length=27)
1 => string 'jhgyukgyug uftfty utfotfotf' (length=27)
'status' => string '1' (length=1)
2 => string '1' (length=1)
1 =>
array (size=6)
'id' => string '2' (length=1)
0 => string '2' (length=1)
'name' => string 'ytfitf ytfityf ytf' (length=18)
1 => string 'ytfitf ytfityf ytf' (length=18)
'status' => string '0' (length=1)
2 => string '0' (length=1)
if we use PDO::FETCH_OBJ it will give object form.
var_dump($statement->fetchAll(PDO::FETCH_OBJ));output:
array (size=2)
0 =>
object(stdClass)[3]
public 'id' => string '1' (length=1)
public 'name' => string 'jhgyukgyug uftfty utfotfotf' (length=27)
public 'status' => string '1' (length=1)
1 =>
object(stdClass)[4]
public 'id' => string '2' (length=1)
public 'name' => string 'ytfitf ytfityf ytf' (length=18)
public 'status' => string '0' (length=1)
Another Example
todos table:
| id | name | status |
|---|---|---|
| 1 | go to shop | 1 |
| 2 | read book | 0 |
Task.php
<?php
class Task{
public $name;
public $status;
public function foobar(){
return 'foobar';
}
}
?>
index.php
<?php
require 'Task.php';
try {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
}catch( PDOException $e ){
die("couldn't connect ".$e->getMessage());
}
$statement = $pdo->prepare('select * from todos');
$statement->execute();
//var_dump($statement->fetchAll(PDO::FETCH_OBJ));
$tasks = $statement->fetchAll(PDO::FETCH_CLASS, 'Task');// assign the values to Task class
var_dump($tasks[0]->foobar());
require 'task.blade.php';
?>
task.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul>
<?php foreach ($tasks as $task): ?>
<?php if ($task->status): ?>
<strike><li><?= $task->name; ?></li></strike>
<?php else: ?>
<li><?= $task->name; ?></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
</body>
</html>output:
string 'foobar' (length=6)
go to shop- read book