Last active
January 6, 2020 17:41
-
-
Save lazanet/de9a53ad1bd60e7678eca3a8ee945bbc to your computer and use it in GitHub Desktop.
Simple PHP MySQL wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
This is a simple automagic MySQL wrapper which provides basic protection from SQL injections. | |
Usage (after you change database parameters on line 19): | |
require_once("db.php"); //in whichever script you want to run SQL code | |
... | |
$result = execute_sql("SELECT userId, userName, userAvatar FROM users WHERE username = ? AND email = ?", [$username, $email]); | |
foreach($result as $row) | |
echo $row["userId"].";".$row["userAvatar"]; | |
This will prepare connection, prepare statement, check if variables are of right type (and/or do casting etc). | |
No further code is necessary. | |
If query is INSERT/UPDATE/DELETE returned result will be number of affected fields. | |
*/ | |
$conn = null; | |
function init_sql() | |
{ | |
global $conn; | |
$host = "localhost"; | |
$db = "DATABASENAME"; | |
$username = "root"; | |
$password = ""; | |
try | |
{ | |
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION; | |
$conn = new PDO("mysql:host=$host;dbname=$db", $username, $password, $pdo_options); | |
} | |
catch(PDOException $e) | |
{ | |
die("Database connection failed!"); | |
} | |
} | |
function execute_sql($sql, $params = []) | |
{ | |
global $conn; | |
if ($conn == null) init_sql(); | |
try | |
{ | |
$stmt = $conn->prepare($sql); | |
$stmt->execute($params); | |
$data = array(); | |
if ($stmt->columnCount() == 0) //INSERT / UPDATE | |
return $stmt->rowCount(); | |
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) $data[] = $row; | |
return $data; | |
} | |
catch(Exception $e) | |
{ | |
die("Something died! Error is: $e"); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment