I'm still learning PHP OOP, so I'd like to seek for some expert advice or criticism regarding this code I created.
In this script, I created the objects I need to process the user input from a form. While the $homepage
object is responsible for displaying the whole webpage.
My questions are:
- Is this consider clean code?
- Can I completely hide the fact that I actually include the autoload and the configuration files?
- Any recommendation or tips to improve my code?
<?php
/**
*
* OOP practice
* @author Joey
*/
require_once 'config/autoload.php';
require_once 'config/config.php';
// Database credentials
$host = $config['host'];
$dbname = $config['dbname'];
$username = $config['username'];
$password = $config['password'];
// Short variable names
$fname = isset($_POST['fname']) ? clean_data($_POST['fname']) : null;
$lname = isset($_POST['lname']) ? clean_data($_POST['lname']) : null;
$your_question = isset($_POST['question']) ? clean_data($_POST['question']) : null;
try {
// Page object
$homepage = new Page('Questions and Answers', 'QA', '', 'You ask, we answer');
// Author object
$author = new Author($fname, $lname);
// Question object
$question = new Question($your_question, $author);
// Database object
$pdo = new DbConnect($host, $dbname, $username, $password);
// Connect to the database
$pdo->open_connection();
} catch (Exception $e) {
echo $e->getMessage(), '<br>';
exit;
} catch (PDOException $e) {
echo $e->GetMessage(), '<br>';
exit;
}
if (isset($_POST['submit'])) {
// Insert the user input into the database
$pdo->execute_query('INSERT INTO author (first_name, last_name) VALUES (?, ?)', array($author->getFirstName(), $author->GetLastName()));
$pdo->close_connection();
$homepage->content = '<h3>Your question</h3><br><p>Hello ' . $author->getFirstName() . ' ' . $author->getLastName() . '!' . '</p><br>';
$homepage->content .= '<p>You ask: ' . $question->getQuestion() . '</p><br>';
$homepage->content .= 'Do you want to ';
$homepage->content .= '<a href="index.php">Ask another question?</a>' . ' ' . '<br>';
} else {
// Display the form
$homepage->content = <<<_END
<h3>Your question here</h3><br>
<form action="{$_SERVER['PHP_SELF']}" method="post" role="form">
<label for="fname">Enter your first name</label><br>
<input type="text" id="fname" name="fname" size="30"><br>
<label for="lname">Enter your last name</label><br>
<input type="text" id="lname" name="lname" size="30"><br>
<label for="question">What is your question?</label><br>
<textarea id="question" name="question" rows="10" cols="70"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
_END;
}
// Display the webpage using the Page class
$homepage->display();
function clean_data($data)
{
$data = trim($data);
$data = strip_tags($data);
$data = addslashes($data);
return $data;
}