Skip to content

Instantly share code, notes, and snippets.

@rstriquer
Created November 22, 2013 14:23
Show Gist options
  • Save rstriquer/7600647 to your computer and use it in GitHub Desktop.
Save rstriquer/7600647 to your computer and use it in GitHub Desktop.
A simple function to connect to the database and easy the creation of php-cli type scripts with database communication demands
<?php
$dbw = NULL;
$aDatabase = array (
'host' => '',
'database' => '',
'user' => '',
'pwd' => '',
);
echo '<pre>';
var_dump(query('create temporary table aaa_test (a int);'));
var_dump(query('insert into aaa_test (a) values (1);'));
var_dump(query('select * FROM aaa_test;'));
var_dump(query('drop table aaa_test;'));
function query($q) {
global $dbw, $aDatabase;
// retorno da fun<E7><E3>o
$xRst = (array) NULL;
if (!$dbw) {
$dbw = mysql_connect($aDatabase['host'], $aDatabase['user'], $aDatabase['pwd']);
if (!$dbw) {
exit('Conection error (could be: 1-link comunication; or 2-mistaken host, user or password parameter)'."\n");
}
if (!mysql_select_db($aDatabase['database'], $dbw)) {
exit('Conection ok, but I can´t select the database "'.$aDatabase['database'].'" (could be authority error)'."\n");
}
}
$rQuery = mysql_query($q, $dbw);
if (!$rQuery) {
echo $q . "\n";
echo mysql_errno($dbw) . ": " . mysql_error($dbw) . "\n";
exit('Query "'.$q.'" execution error (could be: 1-server load; 2-authority; or even 3-link problem)'."\n");
}
$sBuf = strtoupper(substr(ltrim($q), 0, 3));
if ($sBuf == 'SEL' || $sBuf == 'SHO') {
$nrw = mysql_num_rows($rQuery);
for ($i=0; $i<$nrw; $i++) {
$xRst[] = mysql_fetch_array($rQuery, MYSQL_ASSOC);
};
} else {
$xRst = mysql_affected_rows($dbw);
}
mysql_close($dbw);
$dbw = (boolean) false;
return($xRst);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment