Skip to content

Instantly share code, notes, and snippets.

View terrymun's full-sized avatar

Terry Mun-Andersen terrymun

View GitHub Profile
@terrymun
terrymun / bettermysql-rowCount.php
Last active August 29, 2015 14:27
Count the number of rows returned
<?php
// Assuming that database connection is already open
// Prepare statement
$stmt = $db->prepare("SELECT user, email, country FROM users WHERE id > 1000");
$stmt->execute();
// Get results
if($stmt->rowCount() > 0) {
// One or more rows returned, start iteration through set
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
@terrymun
terrymun / bettermysql-in-clause.php
Last active August 29, 2015 14:27
Filling placeholders in the IN clause
<?php
// Assuming that database connection is already open
// Get username
$userIDs = array(10, 38, 56, 93);
// Method 1: array_fill() then implode()
$placeholders = implode(',', array_fill(0, count($userIDs), '?'));
// Method 2: str_repeat() then str_split() then implode()
$placeholders = implode(',', str_split(str_repeat('?', count($userIDs))));
@terrymun
terrymun / bettermysql-bindParam-forLoop.php
Created August 19, 2015 07:41
Binding parameters or values to placeholders within the for loop
<?php
// Assuming that database connection is already open
// You have an array of userdata
$userData = array([1] => 'johndoe', [2] => '[email protected]', [3] => 'USA');
// Prepare statement
$stmt = $db->prepare("INSERT INTO users (user, email, country) VALUES (?, ?, ?)");
// For loop
// Bind param binds the REFERENCE, remember to modify array (&$value)
@terrymun
terrymun / bettermysql-advanced-like.php
Last active August 29, 2015 14:27
Formulating LIKE queries using prepared statements and named placedholders
<?php
// Assuming that database connection is already open
// Get username
$username = 'john';
$id = 1000;
// Using named placeholders
$stmt = $db->prepare("SELECT user, email, country FROM users WHERE user LIKE :username AND id > :id")
@terrymun
terrymun / bettermysql-namedPlaceholders.php
Last active August 29, 2015 14:27
Position vs named placeholders
<?php
// Assuming that database connection is already open
// Some variables
$userid = 1000;
$country = 'USA';
// Using named placeholders
$stmt = $db->prepare("SELECT user, email, country FROM users WHERE id > :id AND country = :country")
// The order of objects in the array does not matter
@terrymun
terrymun / bettermysql-bindParam.php
Last active April 30, 2018 03:30
The difference between bindParam() and bindValue()
<?php
// Assuming that database connection is already open
// Get username
$username = 'johndoe';
$stmt = $db->prepare("SELECT user, email, country FROM users WHERE user = :username");
$stmt->bindParam(':username', $username);
$username = 'janesmith';
$stmt->execute();
@terrymun
terrymun / bettermysql-advanced-multipleStatements.php
Last active August 29, 2015 14:27
Executing multiple prepared statements
<?php
// Assuming that database connection is already open
// Receive user input that is separated by a new line for each row
$favouriteFoods = array('Apple', 'Poutine', 'Cheesestrings', 'Pickle chips', 'Peanut butter and raisins');
$user = 'johndoe';
// Prepare statement
$stmt = $db->prepare("INSERT INTO users (user, foodItem) VALUES(:username, :favouriteFood)");
$db->beginTransaction();
@terrymun
terrymun / bettermysql-sanitize-input.php
Last active August 29, 2015 14:27
Sanitising user inputs for other variables
<?php
// Assuming that database connection is already open
// Let's say a user is allowed to provide a table name to query from
$tableName = trim($_GET['tableName']);
// This would NOT work (no good!)
$stmt = $db->prepare("SELECT user, id, email FROM :table WHERE id > 1000");
$stmt->bindParam(':table', $tableName);
$stmt->execute();
@terrymun
terrymun / bettermysql-connect-withError.php
Created August 18, 2015 22:13
Connecting to the MySQL database using PDO, with error catching enabled
<?php
try {
// Open new connection, allow catching of exceptions
$db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Wrap the rest of your code in the 'try' block
// since any step in here can go wrong, and you
// will be able to catch any exceptions.
} catch (PDOException $e) {
@terrymun
terrymun / bettermysql-fetch.php
Last active August 29, 2015 14:27
Fetching data from MySQL database
<?php
// Assuming that database connection is already open
// Prepare statement
$stmt = $db->prepare("SELECT
COUNT(user_id) AS UserCount,
country AS Country
FROM users
GROUP BY country
ORDER BY country");