This is my first time messing with PHP and I tried to put together a simple address book that when the user fills out the form it would update a database table, then display the row data on the page after submission.
It works fine, but I just want to make sure I'm headed in the right direction.
index.php
:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// connect to database
include("inc/dbconnect.php");
// assigns form data to table columns
$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ('$_POST[firstName]','$_POST[lastName]','$_POST[email]','$_POST[phone]','$_POST[birthday]')";
// execute query
if (mysqli_query($database,$assign)) {
header("Location:http://localhost/address-book/");
exit;
} else {
echo "Everything blew up!" . mysqli_error($database);
}
// closes database connection
mysqli_close($database);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Address Book</title>
</head>
<body>
<h1>Address Book</h1>
<table cellpadding="5" cellspacing="0">
<thead>
<tr>
<th>Contact name</th>
<th>Email address</th>
<th>Phone</th>
<th>Birth Date</th>
<tr>
</thead>
<tbody>
<?php include("inc/records.php"); ?>
</tbody>
</table>
<h3>Add new contact</h3>
<form method="post" action="index.php">
<input type="text" name="firstName" id="firstName" placeholder="First name">
<input type="text" name="lastName" id="lastName" placeholder="Last Name"><br />
<input type="text" name="email" id="email" placeholder="Email address">
<input type="text" name="phone" id="phone" placeholder="Phone"><br />
<input type="text" name="birthday" id="birthday" placeholder="Birthday">
<input type="submit" value="Save record" placeholder="Save">
</form>
</body>
</html>
dbconnect.php
:
// database connect
$database = mysqli_connect(
"localhost",
"user",
"password",
"database"
);
records.php
:
// connects to database
include("dbconnect.php");
// targets the database table contacts
$records = mysqli_query($database,"SELECT * FROM contacts");
// pull row data from database
while($record = mysqli_fetch_array($records)) {
echo "<tr>";
echo "<td>" . $record['firstName'] . " " . $record['lastName'] . "</td>";
echo "<td><a href='mailto:" . $record['email'] . "'>" . $record['email'] . "</a></td>";
echo "<td>" . $record['phone'] . "</td>";
echo "<td>" . $record['email'] . "</td>";
echo "</tr>";
}
mysqli_close($database);