SQL Class
Posted by
shantanu
on August 29, 2004
/
/
//example of how to use at bottom
class mySQL
{
var $my_host;
var $my_username;
var $my_password;
var $my_port;
var $my_database;
var $my_connection;
var $is_alive;
var $sql_query;
var $default_field_sep = "|";
function mySQL($host, $un = "", $pw = "", $port = "") {
if (empty($port)) $port = "3306";
$this->my_host = $host;
$this->my_username = $un;
$this->my_password = $pw;
$this->my_port = $port;
$this->my_connection = mysql_connect($host . ":" . $port, $un, $pw) or die(mysql_error());
$this->is_alive = TRUE;
}
function SelectDB($db) {
$this->my_database = $db;
if ($this->is_alive !== TRUE) {
echo "You must be connected to a server before choosing a database.";
return;
}
mysql_select_db($this->my_database) or die(mysql_error());
}
function SqlClose() {
if ($this->is_alive === TRUE) {
mysql_close($this->my_connection) or die(mysql_error());
$this->is_alive = FALSE;
}
}
function SqlPut($table, $fields, $data) {
if ($this->is_alive !== TRUE) {
echo "You must be connected to a server before inputting data.";
return;
}
$seperator = $this->default_field_sep;
$tmp_query;
$field_arr = explode($seperator, $fields);
$data_arr = explode($seperator, $data);
if ( (count($field_arr)) != (count($data_arr)) ) {
echo "You must supply the same number of fields as data.";
return;
}
$tmp_query .= "INSERT INTO `" . $table . "` (";
for ($i = 0; $i < count($field_arr); $i++) {
$tmp_query .= "`" . $field_arr[$i] . "`";
if ($i < (count($field_arr) - 1)) $tmp_query .= ", ";
}
$tmp_query .= ") VALUES (";
for ($i = 0; $i < count($data_arr); $i++) {
$tmp_query .= "'" . $data_arr[$i] . "'";
if ($i < (count($data_arr) - 1)) $tmp_query .= ", ";
}
$tmp_query .= ");";
$this->SqlQuery($tmp_query);
}
function SqlFetchRow() {
if ($this->is_alive === TRUE) {
if (!empty($this->sql_query)) {
return @mysql_fetch_array($this->sql_query);
}
}
}
function SqlQuery($query) {
if ($this->is_alive === TRUE) {
$this->sql_query = "";
$this->sql_query = mysql_query($query) or die(mysql_error());
}
}
function SqlNumRows() {
if ($this->is_alive === TRUE) {
if (!empty($this->sql_query)) {
return @mysql_num_rows($this->sql_query);
}
}
}
}
$sql = new mySQL("db2.phenominet.com", "shantanuo", "");
$sql->SelectDB("shantanuo"); //selects database
$sql->SqlPut("ashprojects_users", "userid|fullname", "userboy|andhispassword");
$sql->SqlClose(); //closes sql connection
?>