Simple PHP MySQL Database Functions

A simple bit of code to make PHP database connections a little easier to use.<?php
function db_connect(){
$db = mysql_connect(DB_HOST,DB_USER,DB_PASS) or die("Cannot connect");
$dbcnx = mysql_select_db(DB_NAME) or die ("Cannot select db");
return $db;
}
function query($sql,$db){
$res = mysql_query($sql,$db) or die("Error in sql $sql: ".mysql_error());
return $res;
}
function qa($sql,$db){
$res = query($sql,$db);
$data = array();
while($row = mysql_fetch_assoc($res)){
if($res['id'])$data[$res['id']] = $row;
else $data[] = $row;
}
return $data;
}
function qa1($sql,$db){
return array_shift(qa($sql,$db));
}
?>

and to use it do something like:

<?php
$db = db_connect();
$sql = "SELECT * FROM foo";
$result_array = qa($sql,$db);
?>

Leave a Reply

Your email address will not be published. Required fields are marked *