This database has a table, called: jokes
Our table has these columns: id, joketext, jokedate
My task is to output on screen all entries from our jokes table which are from id and joketext column. No need to output jokedate. I hope it makes sense. Here is how I do it, but for some reason it does not work and acts as if I was stuck in an infinite while loop.
PHP controller called index.php
Code: Select all
//connect to database server
$link = mysqli_connect('localhost', 'root', 'password');
if (!$link)
{
$output = "Could not connect to database server.";
include 'output.php';//PHP template
exit();
}
//tell PHP to use UTF8 when talking to MySQL
if (!mysqli_set_charset($link, 'utf8'))
{
$output = "Could not set character set";
include 'output.php';
exit();
}
//select a database to work with
if (!mysqli_select_db($link, 'ijdb'))
{
$output = "Could not find a database.";
include 'output.php';
exit();
}
//Up to this point all goes just fine. Now, to a problem spot
//Request MySQL to output id and joketext of every joke
$result = mysqli_query($link, 'SELECT id, joketext FROM jokes');
if (!$result)
{
$output = "Did not receive a result set from database.";
include 'output.php';
exit();
}
//Trying to get rows from result set and save each row into a new array.
//Each row is an array that consists of two elements
while ($row = mysqli_fetch_array($result))
{
$jokes[] = array('id' =>row['id'], 'text' =>row['joketext']);
}
include jokes.php';
//And the above mentioned while loop is a place where I am stuck :banghead:
Code: Select all
<p>Here are all the jokes in the database:</p>
<?php foreach ($jokes as $joke): ?>
<form action="?deletejoke" method="post">
<blockquote>
<p>
<?php echo htmlspecialchars($joke['text'], ENT_QUOTES,
'UTF-8'); ?>
<input type="hidden" name="id" value="<?php
echo $joke['id']; ?>"/>
<input type="submit" value="Delete"/>
</p>
</blockquote>
</form>
<?php endforeach; ?>
Code: Select all
$jokes[] = array('id' =>row['id'], 'text' =>row['joketext']);$jokes[] is an array and we use [] here because we don't know how many rows/entries are there in our table, so the indexing will be handled automatically by PHP, wich first entry/row getting an index number 0 and this number will automatically increase. Each element of our newly created $jokes array has got an array inside of it, each having two elements. So, I could say that in $jokes[0] element there will be two elements['id'] and ['text'] and I copy the value of our $row['id'] into our $jokes['id'], and the same with $row['joketext'] that goes inside our $jokes['text']. It is all nuts and drives my crazy.
Could someone explain to me what I am missing out in here? Please no judging, everyone at one stage or another needs some help, and that is what I am here for.
Thanks in advance.
I would appreciate some explanation, especially in parts where we are dealing with assigning result set rows into an associative array.
Alex.