« Parsing mutliple date formats in Python | Main | A brief history of some subversion transactions »
August 06, 2006
New do_sql.php
I've rewritten my do_sql.php code to work with the Pear DB library and refactored everything while I was at it:
<?php
require "DB.php";
include("read_config.php");
function sql_doozer($db, $sql, $is_query, $debug){
if($debug == true){ print $sql; }
# Set up the reply array
(array) $reply;
# Get our database connection details from the INI config file
(array) $config = read_config($db.".ini");
if($debug == true) { print_r($config); }
$conf = $config["connection_parameters"];
# Build the connection URL
$db_url = $conf["type"]."://".$conf["user"].":".$conf["passwd"].
"@".$conf["host"]."/".$conf["db"];
if($debug == true){ print $db_url; }
# Create our connection
$connection = DB::Connect($db_url);
if(DB::isError($connection)){
$reply["status"] = false;
$reply["message"] = $connection->getMessage();
return($reply);
}
(array) $reply["rows"];
# Do the query
$cursor = $connection->query($sql);
if(DB::isError($cursor)){
$reply["status"] = false;
$reply["message"] = $cursor->getMessage()." - ".$sql;
return($reply);
}
$count = 0;
# If this is an SQL query get the results back
if($is_query == true){
$reply["num_of_rows"] = $cursor->numRows();
if(DB::isError($cursor)){
$reply["status"] = false;
$reply["message"] = $cursor->getMessage();
return($reply);
}
while($this_row = $cursor->fetchRow(DB_FETCHMODE_ASSOC)){
if(DB::isError($this_row)){
$reply["status"] = false;
$reply["message"] = $this_row->getMessage();
return($reply);
}
$reply["rows"][$count] = $this_row;
$count++;
}
}
if($debug == true){ print_r($reply["rows"]); }
$reply["first_row"] = $reply["rows"][0];
$reply["status"] = true;
$reply["message"] = "OK";
return($reply);
}
function is_query($sql){
# Check to see if our SQL is an insert or update statement
$sql_list = explode(" ",$sql);
if((strtolower($sql_list[0]) == "insert")
or (strtolower($sql_list[0]) == "update")
or (strtolower($sql_list[0]) == "create")
or (strtolower($sql_list[0]) == "alter")){
return(false);
}
return(true);
}
function do_sql($db, $sql, $debug){
$is_query = is_query($sql);
return(sql_doozer($db, $sql, $is_query, $debug));
}
function do_sql_query($db, $sql, $debug){
return(sql_doozer($db, $sql, true, $debug));
}
function do_sql_insert($db, $sql, $debug){
return(sql_doozer($db, $sql, false, $debug));
}
function do_sql_update($db, $sql, $debug){
return(sql_doozer($db, $sql, false, $debug));
}
?>
Tags: PHP
Posted by pj at August 6, 2006 03:32 PM