Member-only story

Writing Better PHP And Save Time — Part 2

Mark Caggiano
5 min readFeb 7, 2021

--

On the previous story i introduced you on some way to program in PHP instead of the old ways, now let’s continue with the infamous “mysqli” or even worse “mysql” functions.

Not only did development stop long ago on mysql, but it was deprecated as of PHP 5.5.0, and has been officially removed in PHP 7.0. — https://phptherightway.com/#databases

Modernizing Database Development

The infamous old way:

<?php

// Example of old style, bad mysql db access
$host = "localhost";
$username = "username";
$password = "password";
$dbname = "myapp";

// Create connection
$conn = new mysqli($host, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}
$user_role = $_GET['r'];
$query = "SELECT * FROM users WHERE role=".$user_role;

$result = $conn->query($query);

if ($result->num_rows > 0) {
// output data of each row

while($row = $result->fetch_assoc()) {
echo "id: ". $row["id"]. "- Name: ". $row["firstname"]. " ". $row["lastname"]. "<br>";
}

} else {
echo "0 results";
}

$conn->close();

There is so many thing wrong about this code, but let’s start with insecurity… this code is vulnerable to SQL Injection, it has sql queries in php code with makes things unreadable, unmaintanabile, difficult to refactor and modify.

--

--

Mark Caggiano
Mark Caggiano

Written by Mark Caggiano

Internet Marketer, Web Developer, Traveler

No responses yet