Skip to content

Instantly share code, notes, and snippets.

@adityapooniya
Forked from pipiscrew/config_pdo.php
Created November 17, 2015 03:32
Show Gist options
  • Save adityapooniya/e50d9ae323b6c9edaa42 to your computer and use it in GitHub Desktop.
Save adityapooniya/e50d9ae323b6c9edaa42 to your computer and use it in GitHub Desktop.
PDO Custom Class
<?php
function connect_mysql() {
$mysql_hostname = "localhost";
$mysql_user = "x";
$mysql_password = "x";
$mysql_database = "x";
$dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_database", $mysql_user, $mysql_password,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
));
return $dbh;
}
function connect_sqlite() {
//if doesnt exist, will created.
$dbh = new PDO('sqlite:dbase.db');
return $dbh;
}
function getScalar($db, $sql, $params) {
if ($stmt = $db -> prepare($sql)) {
$stmt->execute($params);
return $stmt->fetchColumn();
} else
return 0;
}
function getRow($db, $sql, $params) {
if ($stmt = $db -> prepare($sql)) {
$stmt->execute($params);
return $stmt->fetch();
} else
return 0;
}
function getSet($db, $sql, $params) {
if ($stmt = $db -> prepare($sql)) {
$stmt->execute($params);
return $stmt->fetchAll();
} else
return 0;
}
function executeSQL($db, $sql, $params) {
if ($stmt = $db -> prepare($sql)) {
$stmt->execute($params);
return $stmt->rowCount();
} else
return false;
}
?>
//sample.php
<?php
require_once("config_pdo.php");
$db = connect_mysql();
$user_id = 3;
$a = 1;
$names ="";
//example 1
$rows = getSet($db, "select * from users where user_id>? and user_is_active=?", array($user_id,$a)); //always pass as array, when not have parameters pass plain null
foreach($rows as $row) {
$names .= $row['user_name'] . ", ";
}
//example 2
$field = = getScalar($db, "select user_working_hour_id from user_working_hours where date_end is null and user_id=? order by user_working_hour_id DESC limit 1",array($user_id));
if(!$field ) //when the variable is not filled
echo "error";
else
echo $field;
//example 3
$row = getRow($db, "select * from user_working_hours where date_end is null and user_id=? order by user_working_hour_id DESC limit 1",array($user_id));
if(!$row) //when the variable is not filled
echo "error";
else
echo $r["user_working_hours_start"];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment