As my first simple PHP project, I've created a simple project that allows you to just enter your name and two numbers, where it displays them on the page and stores them in a database. It consists of 3 files: index.php, db.php & process.php. I wonder whether I have created the code efficiently.
I'm curious about all the talk behind procedural PHP vs OOP. I initially used some deprecated PHP5 functions and was corrected by the stack overflow community, but this has left me confused as to what specifically I should learn with PHP as a beginner. It sounds like procedural and OOP are very different, and that I should only pick one and learn that.
So my questions are as follows:
- Is the coding in my project acceptable?
- Is it similar to how most PHP projects are built? (i.e. are most procedural or OOP)
- What should I learn as a beginner? (procedural or OOP?)
- Do you have any beginner advice?
Any advice here would be very much appreciated as I'm new to PHP. Thanks for any help here. The files and code (excluding HTML & CSS) are below:
index.php:
<?php include 'db.php'; ?>
<?php
// Fetch data from db
$query = mysqli_query($con, 'SELECT * FROM data');
?>
<!-- create a loop (while there are results in the DB, spit them out) -->
<?php while ($row = $query->fetch_assoc()) : ?>
<li><?php echo $row['t_name'] ?> entered <?php echo $row['t_firstNo'] ?> and <?php echo $row['t_secondNo'] ?> (result =
<?php
$first = $row['t_firstNo'];
$second = $row['t_secondNo'];
$result = $first * $second;
echo $result;
?>)</li>
<?php endwhile ?>
<!-- if bad input, get & display error -->
<?php if(isset($_GET['error'])) : // if error variable is there ?>
<?php echo $_GET['error']; // get the error ?>
<?php endif ?>
db.php:
<?php
// Connect
$con = mysqli_connect("localhost", "tnnick", "PHPprojects", "timesNumbers");
// Test Connection
if (mysqli_connect_errno()) {
echo 'Failed: '.mysqli_connect_error();
}
?>
process.php:
<?php include 'db.php' ; ?>
<?php
if(isset($_POST['submit'])) { // if form submitted
$nickname = mysqli_real_escape_string($con, $_POST['nickname']); // get the inputs
$firstNo = mysqli_real_escape_string($con, $_POST['firstNo']);
$secondNo = mysqli_real_escape_string($con, $_POST['secondNo']);
}
?>
<?php
// validate inputs
if(!isset($nickname) || $nickname=='' || !isset($firstNo) || $firstNo=='' || !isset($secondNo) || $secondNo=='' ) {
// if invalid input, send error to index.php
$error = 'Bad input - try again.'; // create error message
header("Location: index.php?error=".urlencode($error)); // attach to URL & send to index.php
exit();
} else {
// insert into DB
$putIntoDB = "INSERT INTO data (t_name, t_firstNo, t_secondNo) VALUES ('$nickname','$firstNo','$secondNo')";
// check it inserted
if(!mysqli_query($con, $putIntoDB)) {
die('Error');
} else {
header("Location: index.php");
exit();
}
}
?>