0
\$\begingroup\$

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:

  1. Is the coding in my project acceptable?
  2. Is it similar to how most PHP projects are built? (i.e. are most procedural or OOP)
  3. What should I learn as a beginner? (procedural or OOP?)
  4. 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();
    }
}
?>
\$\endgroup\$
1
\$\begingroup\$
  1. Is the coding in my project acceptable?

More or less. There are no essential flaws but the structure is quite questionable.

  1. Is it similar to how most PHP projects are built? (i.e. are most procedural or OOP)

Depends on the project's maturity. Your code is quite similar to what a usual first project looks like, and even above the average. Speaking of mature projects, they indeed are mostly written using OOP and essentially different from what you wrote here.

  1. What should I learn as a beginner? (procedural or OOP?)

First of all, there is nothing wrong with procedural programming, it's perfectly OK to start from it. Eventually you will learn some OOP and may be even master it.
Besides, it looks like you are confusing OOP which is indeed opposite to procedural programming with PDO which is just a PHP extension to work with databases (though using OOP syntax).
PDO is better than mysqli which you are using at the moment, so to answer your questions about procedural/OOP/PDO:

  • Learn procedural PHP with occasional use of built-in objects
  • Better to use PDO for the database access instead of mysqli

Do you have any beginner advice?

Just write a code and post it here for the review.

Now to your code

db.php

this file is better to be rewritten (in case you are going to stick with mysqli) according to my article How to properly connect to Mysql database using mysqli.

index.php

is better to be split into two parts, the data gathering part and the output part. Such a separation will make both parts cleaner:

<?php
include 'db.php';
// Fetch data from db
$query = mysqli_query($con, 'SELECT *, t_firstNo * t_secondNo as result FROM data');
// the following function will give you an array
$data = mysqli_fetch_all($query);
?>
<?php foreeach ($data as $row) : ?>
    <li>
        <?= $row['t_name'] ?> entered 
        <?= $row['t_firstNo'] ?> and 
        <?= $row['t_secondNo'] ?> 
        (result = <?= $row['result'] ?>)
    </li>
<?php endwhile ?>

as you can see, we calculated the result right in the query, which made our output code cleaner and focused on the output. Getting data into array before output is also a good practice, completely separating the database interaction from the output.

process.php

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if(empty($_POST['nickname']) || empty($_POST['firstNo']) || empty($_POST['secondNo'])) {
        echo 'Bad input - try again.';
    } else {
        include 'db.php';
        // insert into DB
        $sql = "INSERT INTO data (t_name, t_firstNo, t_secondNo) VALUES (?,?,?)";
        $stmt = mysqli_prepare($sql);
        $stmt->bind_param("sss", $_POST['nickname'], $_POST['firstNo'], $_POST['secondNo']);
        $stmt->execute();
        header("Location: index.php");
        exit();
    }
}
?>
<form>
Here goes your input form

some notes

  • it's better to use $_SERVER['REQUEST_METHOD'] if POST method is used.
  • empty() is essentially a shorthand of isset($var) || $var==''.
  • it's better to keep the form and its processing on the same page. it can let you to fill the entered values for the convenience.
  • it is much, much better to use a prepared statement as opposite to the manual escaping you were using, so you should stick with the former.
  • there is no need to check for the success, your application should be just configured to say "Error" in case of error automatically.
\$\endgroup\$
  • \$\begingroup\$ wow, thanks for the great advice! do you know of any link to example project tutorials with PHP? I think the course I'm following is a bit outdated \$\endgroup\$ – user8758206 Oct 29 '18 at 19:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.