Last active
January 16, 2017 22:22
-
-
Save bencentra/9312292 to your computer and use it in GitHub Desktop.
A bunch of database functions for prepared statements with PDO. Assumes a global $pdo object created in separate 'dbInfo.inc' file.
This file contains hidden or 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 | |
// Include the database connection info | |
require_once("path/to/dbInfo.inc"); | |
/* | |
* Database methods | |
*/ | |
function db_select($sql, $data) | |
{ | |
global $pdo; | |
$stmt = null; | |
// Make the query | |
try { | |
// Prepare the SQL statement | |
$stmt = $pdo->prepare($sql); | |
} | |
// Catch any exceptions/errors | |
catch (Exception $e) { | |
return false; | |
} | |
// Execute the statement | |
try { | |
if ($stmt->execute($data)) { | |
// Return the selected data as an assoc array | |
return $stmt->fetchAll(PDO::FETCH_ASSOC); | |
} | |
else { | |
return false; | |
} | |
} | |
catch (Exception $e) { | |
return false; | |
} | |
} | |
function db_insert($sql, $data) | |
{ | |
global $pdo; | |
$stmt = null; | |
// Make the query | |
try { | |
// Prepare the SQL statement | |
$stmt = $pdo->prepare($sql); | |
} | |
// Catch any exceptions/errors | |
catch (Exception $e) { | |
return false; | |
} | |
// Execute the statement | |
try { | |
if ($stmt->execute($data)) { | |
// Return the number of rows affected | |
return $stmt->rowCount(); | |
} | |
else { | |
return false; | |
} | |
} | |
catch (Exception $e) { | |
return false; | |
} | |
} | |
function db_update($sql, $data) | |
{ | |
return db_insert($sql, $data); | |
} | |
function db_delete($sql, $data) | |
{ | |
return db_insert($sql, $data); | |
} | |
function db_last_insert_id() { | |
global $pdo; | |
return $pdo->lastInsertId(); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment