How to output php sql function in html?

60

I have a function in php which needs to display all records within the table. But I just can't seem to display them in HTML.

Here is my php code:

<?php
function display_products(){
    $query = mysql_query("Select id, naam,prijs from product");
    $data = array();
    while ($row = mysql_fetch_assoc($result)){
        array_push($data, $row);
    }
    return $data;
}?>

and here is my attempt to display the array of in my html:

<?php
$products = display_products();
foreach ($products as $product): ?>
  <ul>
    <li><?php echo $product['naam'] ?></li>
    <li><?php echo $product['prijs'] ?></li>
  </ul>
}
<?php endforeach; unset($product); ?>
647

Answer

Solution:

Try something like the following (don't forget to change the constants in mysqli_connect() function). Also, if you get familiar with this try to use PDO.

<?php
function display_products() {
    //Connect to database
    $connection = mysqli_connect(SERVER, USER, MY_PASSWORD, MY_DATABASE);
    mysqli_set_charset($connection, 'utf8');
    if (!$connection) {
        die("Database connection failed: " . mysqli_error());
    }
    //Make the query
    $query = "SELECT id, naam, prijs FROM product;";
    $result = mysqli_query($connection, $query);
    $data = array();
    //Fetch all the data
   while ($row = mysqli_fetch_array($result)) {
        array_push($data, $row);
    }
    return $data;
}
?>


<?php
$products = display_products();
foreach ($products as $product): ?>
    <ul>
        <li><?php echo $product['naam']; ?></li>
        <li><?php echo $product['prijs']; ?></li>
    </ul>
<?php endforeach; ?>

People are also looking for solutions to the problem: php - Weird sql insert after json decode function

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.