To avoid injections and vulnerabilities when doing MYSQL interaction in PHP use PDO and prepared statements. It’s a bit more work but is the safest way to ensure you are not open to an attack.
First you want to define your MYSQL credentials and database as well as some PDO attributes.
$db = new PDO('mysql:host=localhost;dbname=DATABASENAME;charset=utf8mb4', 'USERNAME', 'PASSWORD'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
The following code selects the town value from the database where id = 472
$id = '472'; $statement = $db->prepare("SELECT `town` FROM `user_details` WHERE `id` = :id"); $statement->execute(array(':id' => $id)); $row = $statement->fetch(); $town = $row['town'];
The following code inserts Ryan Smith into the database for first_name and last_name where id = 472
$id = '472'; $first_name = 'Ryan'; $last_name = 'Smith'; $statement = $db->prepare("INSERT INTO `user_details` (`first_name`, `last_name`) VALUES (:firstname, :lastname) WHERE `id` = :id"); $statement->execute(array(':firstname' => $first_name, ':lastname' => $last_name, ':id' => $id));
The following Updates email_verified to 1 for where id = 472
$id = '472'; $is_verified = 1; $statement = $db->prepare("UPDATE `user_details` SET `email_verified` = :isverified WHERE `id` = :id"); $statement->execute(array(':id' => $id, ':isverified' => $is_verified));
The following checks the database for a row where id = 472
$id = '472'; $statement = $db->prepare("SELECT `id` FROM `user_details` WHERE `id` = :id"); $statement->execute(array(':id' => $id)); $row = $statement->fetch(); $count = $statement->rowCount(); if ($count == 0) { //There is no entry for id = 472 } else { //There is an entry for id = 472 }
The following code example SELECTS ALL emails and email_verified values from the database then it echos them out in a formatted fashion.
$statement = $db->prepare("SELECT `email`, `email_verified` FROM `user_details`"); $result->execute(); while ($row = $result->fetch(PDO::FETCH_ASSOC)) { $email = $row['email']; $verified = $row['email_verified']; echo "".$verified." email: ".$email."<br>"; }
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Using FTP and PHP to get an array of file details such as size and…
Creating and using Laravel form requests to create cleaner code, separation and reusability for your…
Improving the default Laravel login and register views in such a simple manner but making…
Laravel validation for checking if a field value exists in the database. The validation rule…