I am new to PHP and are currently a student and need to do the following assignemt
-
Connect to the database using PDO, and then use the fetchAll method to list (on separate lines) all the animal types and their names in a neat table
-
Below this list, present a simple form to capture a new animal type and its name. When the form is submitted, a prepared INSERT statement is used to insert the new data. The new row containing the new animal data will immediately appear in the table in (1) above, and without requiring the user to refresh the page.
My code is as follow - but it does not update the displayed table as requested
[php]<?php
include(‘menu.inc’);
echo “
”;
echo "//////////////////////////////Task 1 ////////////////////////// ";
function display_data(){
//Establish database connection
$dsn = ‘mysql:host=localhost;dbname=portfolio’;
$username = ‘root’;
$password = ‘’;
$db = new PDO($dsn, $username, $password);
$animal_type = ‘’;
$animal_name = ‘’;
// build sql query and retrieve data
$query = 'SELECT animal_type, animal_name FROM animals';
$statement =$db->prepare($query);
$statement->execute();
$animals=$statement->fetchALL();
$statement->closeCursor();
//create table layour
print ’
Animal List
’ ;print ’
Animal Type | ’;Animal Name | ’;
---|---|
"; echo $animal_type; print " | "; echo $animal_name ; endforeach; print’ |
}
display_data();
// Add a new Animal to the Table
echo “
”;
echo "//////////////////////////////Task 2 ////////////////////////// ";
if(isset($_POST['formSubmit'])){
add_data();
}
function add_data(){
if( $_POST["name"] || $_POST["animal"] )
{
$type_animal = $_POST['animal'];
$name_animal = $_POST['name'];
// Connect to Database
$dsn = ‘mysql:host=localhost;dbname=portfolio’;
$username = ‘root’;
$password = ‘’;
$db = new PDO($dsn, $username, $password);
// Build database query and retrieve data
$myquery = ‘INSERT INTO animals
( animal_type, animal_name)
VALUES
( :type_animal, :name_animal)’;
$mystatement =$db->prepare($myquery);
$mystatement->bindValue(’:type_animal’ , $type_animal);
$mystatement->bindValue(’:name_animal’ , $name_animal);
$sucess = $mystatement->execute();
$row_count = $mystatement->rowCount();
$mystatement-> closeCursor();
$animal = $db->lastInsertID();
// Display message to show data added correctly
if ($sucess) {
echo "
$row_count row was inserter with this ID: $animal
";}else{
echo “no records added” . “
”;
}
}
display_data();
}
?>
Input new Record
Animal TypeAnimal Type
[/php]