Skip to content

Instantly share code, notes, and snippets.

@luckyshot
Created October 1, 2013 19:47
Show Gist options
  • Save luckyshot/6784024 to your computer and use it in GitHub Desktop.
Save luckyshot/6784024 to your computer and use it in GitHub Desktop.
PHP/MySQLi method (with parametrization)
<?php
// Config
define('MYSQL_SERVER', 'localhost');
define('MYSQL_DATABASE', 'database');
define('MYSQL_USER', 'root');
define('MYSQL_PASS', 'pass');
// MySQLi class method
private function db($q, $params = array()) {
if (!isset($this->mysqli)) {
$this->mysqli = new mysqli('MYSQL_SERVER', 'MYSQL_USER', 'MYSQL_PASS', 'MYSQL_DATABASE');
}
// check connection
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
// execute prepared statement
$stmt = $mysqli->prepare($q);
$stmt->bind_param($params);
$stmt->execute();
$result = $stmt->affected_rows;
/* close statement and connection */
$stmt->close();
return $result;
}
// Example
$q = "INSERT INTO table VALUES (?, ?, ?, ?)";
$params = array(
'iss', // s string, i integer, d double (big integer), b blob (big string)
42, 'bar', 'foo'
);
$result = $this->db($q, $params);
var_dump($result);die();//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment