|
Posted by Rik on 05/27/06 05:27
Bob Bedford wrote:
> Hello Rik, thanks for advice.
>
> In fact SQL is a language that allow to do a lot of different
> queries. If the only think it may do is select-insert-update-delete I
> think it would be simpler. I'll try or have a look around.
>
> In any case, I've seen on some open-source project that some code to
> get the result from a query is one line, as many times the code would
> be bigger (at least 2 lines without caring about error handling).
> I'll start to simplify this then try to get further.
Yup, terribly simplified for instance:
class database{
var $queries = array();
var $errors = array();
var $connection;
var $print_errors;
function __construct($host, $database,$user='root',$pass=''){
$this->database($host,$database,$user,$pass);
}
function database($host,$database,$user,$pass){
if($connection = @mysql_connect($host,$user,$pass){
$this->connection = $connection;
if($database !=''){
if(!@mysql_select_db($database,$this->connection)){
$this->errors[] = 'Could not select database';
}
}
} else {
$this->errors[] = 'Could not connect to server';
}
}
function print_errors($bool=true){
$this->print_errors = $bool;
}
function log_queries($query, $result='',$error=''){
$log = array('query' => $query, 'result'=>$result,'errors'=$error);
$this->queries = $log;
if($this->print_errors && $error!=''){
print("ERROR:\nquery:$query\nMySQL said:$error");
}
}
function debug(){
print_r(end($this->queries));
}
function debug_all(){
print_r($this->queries);
}
function select_query($query,$index=false){
$result = @mysql_query($query, $this->connection);
if(@mysql_error()){
$this->log_queries($query,'',mysql_error());
return false;
}
if(@mysql_num_rows($result) > 0){
$return_array = array();
while($row = @mysql_fetch_assoc($result)){
if($index){
$return_array[$row[$index]] = $row;
} else {
$return_array[] = $row;
}
}
$this->log_queries($query,$return_array,'');
return $return_array;
} else {
$this->log_queries($query,'','');
return 0;
}
}
}
Now you you can use:
/* initialize object */
$db = new database('host','database','user','pass');
/* option debugging: print all errors, usefull in building fase
this can be turned of by giving false as argument */
$db->print_errors();
/* run query */
$result = $db->select_query('SELECT list, of, fields FROM table',
'optional_field_as_array_key');
/* optional debugging per query */
if($result===false) $db->debug();
/* working with the code */
if(is_array($result)){
//do stuff with it
}
I have never used it but maybe mysqli is something for you:
http://www.php.net/manual/en/ref.mysqli.php
Grtz,
--
Rik Wasmus
Navigation:
[Reply to this message]
|