I am trying to put all the using the technique in kevins book p118
I can put named fields into an array ; but I want to put all the field data in row into an array without having to write out each field
I tried $gallery = $row; but it doesnt like it
below is my code
I sure this is solvable !!!
$sql = 'SELECT * from gallery LIMIT 10';
$result = $pdo->query($sql);
$row = $result->fetch();
while ($row = $result->fetch())
{
// $gallery[] = $row; doesnt like it
// $gallery[]=$row['title']; works like the example in the book
$gallery[] = array('title' => $row['title'], 'category' => $row['Category']);
}
Can you expand on “doesn’t like it” - what exactly happens? If you turn on error reporting do you get an error message? If you define gallery as an array before you start your loop:
$gallery = array();
does that make any difference?
If you’re only going to use the loop to get all rows from your query and stick them in an array (and not do anything else in the loop), you could also look at fetchAll().
I am then going on to use the array to print the items. It is only a small test PHP file at the moment. But I am looking for a statement to put all the values into an array without naming them individually. I would like to use the foreach construct as I am trying to follow Kevin Yanks book and if I deviate I get horribly lost !
My two files are below.
the error I get is
Notice: Undefined index: category in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\www\test_bjart_pdo_jan15\gallery1_output.php on line 12
gallery1.php
<?php
include 'header.php';
include 'mysqlLogin/mysql_connect.php';
$sql = 'SELECT * from gallery LIMIT 10';
$result = $pdo->query($sql);
$row = $result->fetch();
while ($row = $result->fetch())
{
$gallery = array();
$gallery[] = $row;
//// $gallery[]=$row['title']; works ( like the example in the book)
// $gallery[] = array('title' => $row['title'], 'category' => $row['Category']); works but have to specify each field
}
include 'gallery1_output.php'
?>
<?php
include 'footer.php';
=============
gallery1_output.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>List of pictures</title>
</head>
<body>
<p>Here are all the pictures in the database:</p>
<?php foreach ($gallery as $galleryline): ?>
<blockquote>
<p>
<?php echo htmlspecialchars($galleryline ['title']." ".$galleryline ['category'], ENT_QUOTES, 'UTF-8'); ?>
</p>
</blockquote>
<?php endforeach; ?>
</body>
</html>
EDIT
This post has been reformatted by enclosing the code block in 3 backticks
```
on their own lines.