article image

PHP Procedural Coding

Created by John Pepp on September 2, 2021

The Miniature Photographer is now known as PHP Procedural in order to help the beginner programmer that is coding in PHP. I don't really like doing tutorials, but the tutorials that are on the internet are either very outdated, junk or that you have to pay for them. I will do my best to keep up with the latest programming techniques, but still make sure my tutorials are pretty current to the latest programming guides. I will never do a tutorial on how to write PHP for security as that is best to leave it up to the security experts. I; however, will use that latest security techniques when it comes to writing secure code, but I am not responsible if my code fails a security test.

With that said I will eventually be writing tutorials on PHP on my other website and the only difference is that it will deal with Object-oriented Programming (OOP). There really isn't much difference other than OOP is more streamline, you can control the security even better and using an autoloader so you don't have to worrying about configuring it to work on every page.

Here's the update database functions in procedural and OOP.

/*
* Update data in the procedural way
*/
function updateData(array $data, $pdo, $table): bool
{
/* Initialize an array */
$attribute_pairs = [];

/* Create the prepared statement string */
foreach ($data as $key => $value)
{
if($key === 'id') { continue; } // Don't include the id:
$attribute_pairs[] = "$key=:$key"; // Assign it to an array:
}

/*
* The sql implodes the prepared statement array in the proper format
* and updates the correct record by id.
*/
$sql = 'UPDATE ' . $table . ' SET ';
$sql .= implode(", ", $attribute_pairs) . ' WHERE id =:id';

/* Normally in two lines, but you can daisy-chain pdo method calls */
$pdo->prepare($sql)->execute($data);

return true;
}

    /*
* This is the update that method that I came up with and
* it does use named placeholders. I have always found
* updating is easier than creating/adding a record for
* some strange reason?
*/
public function update(): bool
{
/* Initialize an array */
$attribute_pairs = [];

/* Create the prepared statement string */
foreach (static::$params as $key => $value)
{
if($key === 'id') { continue; } // Don't include the id:
$attribute_pairs[] = "{$key}=:{$key}"; // Assign it to an array:
}

/*
* The sql implodes the prepared statement array in the proper format
* and updates the correct record by id.
*/
$sql = 'UPDATE ' . static::$table . ' SET ';
$sql .= implode(", ", $attribute_pairs) . ' WHERE id =:id';

/* Normally in two lines, but you can daisy chain pdo method calls */
Database::pdo()->prepare($sql)->execute(static::$params);

return true;

}