Skip to content

Instantly share code, notes, and snippets.

@kpion
Last active December 5, 2016 05:52
Show Gist options
  • Save kpion/ffb3e1aac4b32d019744d2a22495f141 to your computer and use it in GitHub Desktop.
Save kpion/ffb3e1aac4b32d019744d2a22495f141 to your computer and use it in GitHub Desktop.
<?php
/**
It's about a different way of passing params to an sql query. Yes, still using PDO behind the scenes.
*/
///////////////////////////
//The standard way of passing params:
$stmt = $dbh->prepare("INSERT INTO some_table (first_name, last_name) VALUES (?, ?)");
$stmt->bindValue(1, $_GET['first_name']);
$stmt->bindValue(2, $_GET['last_name']));
//or:
//$sth->execute(array(':first_name' => $_GET['first_name'], ':last_name' => $_GET['last_name']));
//////////////////////////
//Isn't this easier?
//By "easier" I mean cleaner and faster to implement.
$myCustomDbClass->insert(
'some_table',
['first_name' => $_GET['first_name'],
'last_name' => $_GET['last_name'] ]
);
/**
My "insert" would look like this:
function someCustomFunction ($table, $params){
1. build a query like $query = "INSERT INTO $some_table "
2. call ->prepare
2. foreach the $params:
a. add keys to the $query like ($key1, $key2) and values placceholders like (":$key1",":$key2")
b. call bindValue ($key, $value)
3. call ->execute
}
*/
/**
p.s.
* The "insert" function is just an example, there would be more funcs, like update, delete, select etc.
* This would be a bit more complicated in reality, that would be a query builder known from e.g. CodeIgniter
(yes, I know it's old, but this idea is good imho)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment