swto
February 25, 2011, 5:08pm
1
Hi All,
I’m running a SELECT statement in which the results are placed in an array and displayed using a ‘foreach’ statement. However, not all the results are meant to be in a ‘foreach’ statement. But when trying to do a simple htmlout, I get a undefined variable error:
Index Page
while ($row = mysqli_fetch_array($result))
{
$list[]= array('id' => $row['id'], 'blah' => $row['blah'], 'blee' => $row['blee']);
}
...
HTML page
<?php htmlout($blah); ?>
<?php if (isset ($list)): ?>
<?php foreach ($list as $car): ?>
...<?php echo htmlspecialchars($car['blee'], ENT_QUOTES, 'UTF-8'); ?>....
<?php endforeach; ?>
<?php endif; ?>
The error I am getting is with the $blah statement in my html page. Can anyone point me in the right direction so that I don’t get an undefined variable error?
Thanks in advance.
rguy84
February 25, 2011, 5:12pm
2
$list and $list are two different variables. You defined $list but are trying to use $list
swto
February 25, 2011, 6:05pm
3
many thanks, got it working
Just something to keep code neater:
while ($row = mysqli_fetch_array($result))
{
$list[]= array('id' => $row['id'], 'blah' => $row['blah'], 'blee' => $row['blee']);
}
assuming that you’ll be using all the fields in the results set
while ($row = mysqli_fetch_array($result))
{
$list[]= $row;
}
There’s no difference in terms of the way it works from how you done it but it just saves a little typing.
swto
February 26, 2011, 12:03am
5
great to know - I do call a lot of fields so this will help a bunch
Cheers
While we’re at it. This is unnecessary:
<?php echo htmlspecialchars($car['blee'], ENT_QUOTES, 'UTF-8'); ?>
The following will do exactly the same:
<?php echo htmlspecialchars($car['blee']); ?>
Passing the charset to this function only really makes sense if you’re using something that isn’t ascii compatible.
Personally, I even find this a bit tedious to type, so I usually define a function e like this:
function e($s) {
echo htmlspecialchars($s);
}
Then you can simply write:
<?php e($car['blee']); ?>