Hi, I am currently following along the sitepoint PHP & mySQL book by Kevin Yank.
I decided in order to learn more, I would be better off creating my own fictional website so that I am more or less creating all the code. I decided to make a job listing site, which has similar functions to the joke site in the book but goes a bit further.
I have working code that takes the info entered in the form and posts it to the database. Some of the information is in the form of required fields and they go to two tables, “author” and “job”.
In order to further my learning, I was hoping someone could look at my code and see if there is an easier, less cluttered way to do this, so here it is:
//Add job listing to database
if (isset($_GET['add']))
{
include $_SERVER['DOCUMENT_ROOT'] . '/studentjobs/includes/db.inc.php';
include $_SERVER['DOCUMENT_ROOT'] . '/studentjobs/includes/helpers.inc.php';
$error = ''; //Set $error to '' to avoid notice/error.
if ($_POST['name'] == '')
{
$error = 'You must enter your name.';
include 'addjob.html.php';
exit();
}
if ($_POST['email'] == '')
{
$error = 'You must enter your e-mail address.';
include 'addjob.html.php';
exit();
}
if ($_POST['title'] == '')
{
$error = 'You must enter a job title.';
include 'addjob.html.php';
exit();
}
if ($_POST['description'] == '')
{
$error = 'You must enter a job description.';
include 'addjob.html.php';
exit();
}
$name = mysqli_real_escape_string($link, $_POST['name']);
$email = mysqli_real_escape_string($link, $_POST['email']);
$title = mysqli_real_escape_string($link, $_POST['title']);
$description = mysqli_real_escape_string($link, $_POST['description']);
$authorsql = "INSERT INTO author SET
name='$name',
email='$email'";
if ($_POST['company'] != '')
{
$company = mysqli_real_escape_string($link, $_POST['company']);
$sql .= ",company='$company'";
}
if ($_POST['phone'] != '')
{
$phone = mysqli_real_escape_string($link, $_POST['phone']);
$sql .= ",phone='$phone'";
}
if ($_POST['address'] != '')
{
$address = mysqli_real_escape_string($link, $_POST['address']);
$sql .= ",address='$address'";
}
if (!mysqli_query($link, $authorsql))
{
$error = 'Unable to add author to the database. ' . mysqli_error($link);
include 'error.html.php';
exit();
}
$authorid = mysqli_insert_id($link);
$jobsql = "INSERT INTO job SET
title='$title',
description='$description',
date=CURDATE(),
authorid='$authorid'";
if (!mysqli_query($link, $jobsql))
{
$error = 'Unable to add job listing to the database. ' . mysqli_error($link);
include 'error.html.php';
exit();
}
header('Location: .');
exit();
}
I imagine the form that the information is taken from wont be needed but if it is let me know and I will post the code for that too.
As you can see it’s a bit all over the place, hoping you can help, thanks.