I am trying to write into a database an entry while using the logic of Front Controller. This leads to the problem, where I have outputted already some set of information and thus the output is already given and header cannot be used.
The main functionality is a simple phonebook. You can write to a database the name and numbers (multiple). After submitting the entry, it should redirect to a page where all entries are displayed.
I have tried placing the redirect as the first thing to check. Trying to implement all Business Logic before using the Front Controller to create the view, but as this is the usage of the submit button, I am a bit confused.
I am a little concerned that my implementation of Front Controller and building of the page Add, on which the Submit is pressed means that the output is already created and header will not work. Is this a possibility?
Index.php looks like this
<?php
include "redirect.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Harjutustund 1</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<?php
include "navigation.php";
?>
<br><br>
<?php
include "footer.php"
?>
</body>
</html>
Redirect looks like this
<?php
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$phones = array($_POST["phone1"]);
if (!empty($_POST["phone2"])) {
array_push($phones, $_POST["phone2"]);
}
if (!empty($_POST["phone3"])) {
array_push($phones, $_POST["phone3"]);
}
if (!empty($firstName) && (!empty($lastName)) && (!empty($phones))) {
try {
//open the database
header("Location: index.php?command=show_list_page");
$db = new PDO('sqlite:db1.sqlite');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Insert record
$insert = "INSERT INTO contacts (firstName, lastName) VALUES (:firstName, :lastName);";
$stmt = $db->prepare($insert);
$stmt->bindParam('firstName', $firstName);
$stmt->bindParam('lastName', $lastName);
$stmt->execute();
// get Autoincrement value
//$id_value = $db->exec("select seq from sqlite_sequence where name=\"contacts\";");
$id_value = $db->lastInsertId();
foreach ($phones as $phone) {
$insert = "INSERT INTO phones (contact_id, number) VALUES (:id_value, :phone);";
$stmt = $db->prepare($insert);
$stmt->bindParam('id_value', $id_value);
$stmt->bindParam('phone', $phone);
$stmt->execute();
print_r($db->errorInfo());
}
} catch
(PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
}
$db = NULL;
What I would like is the all the business logic is worked through first and then view created. After pressing the submit, the record is stored and redirect will take me to the whole list.