Tag Archive for database

Dump Database

mysqldump -uuser  -ppass --opt database > file directory

source

Access SQLite Database from SAS

/************************************************
* ACCESS SQLITE DATABASE FROM SAS               *
* REQUIREMENT:                                  *
*   HAVE SQLITE ODBC DRIVER INSTALLED           *
************************************************/

libname sqlite odbc complete = "dsn=SQLite;
Driver={SQLite3 ODBC Driver};
Database=C:foldermydatabase.db";

source

Inserting/Retrieving checkbox values from database

//On form; checkbox option
echo "<input name='chbx' value='1' type='checkbox' CHECKED>";

//After form, find value of chbx for database
$showhide = (isset($_POST['chbx']) && $_POST['chbx'] == '1')? 1 : 0;

//Retrieving from database, find if chbx is checked for redisplaying original sumbission
$ckd = (isset($row['chbx']) && $row['chbx'] == '1')? "CHECKED" : "";
$checkbox = "<input name='chbx' value='1' type='checkbox' $chk>";

source

OOP MySQL Database Class

<?php
class database {

var $host = NULL;
var $username = NULL;
var $password = NULL;
var $databaseName = NULL;
var $link = NULL;
var $queries = NULL;
var $errors = NULL;

var $databaseExtras = NULL;

function __construct($host, $username, $password, $database) {
$this->database($host, $username, $password, $database);
}

function database($host, $username, $password, $database) {
/*$this->database = array (
"host" => $host,
"username" => $username,
"password" => $password,
"database" => $database,
"link" => "",
"queries" => array (),
"errors" => array ()
);*/

$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->databaseName = $database;
$this->link = "";
$this->queries = array ();
$this->errors = array ();

$this->databaseExtras = new stdClass;

$this->link = mysql_connect($this->host, $this->username, $this->password) or die("Could not connect to Database");
mysql_select_db($this->databaseName);
}

function justquery($sql) {
$this->queries[] = $sql;
return mysql_query($sql, $this->link);
}

function loadResult($sql) {
if (!($cur = $this->justquery($sql))) {
return null;
}
$ret = null;
if ($row = mysql_fetch_row( $cur )) {
$ret = $row[0];
}
mysql_free_result( $cur );
return $ret;
}

function loadFirstRow($sql) {
if (!($cur = $this->justquery($sql))) {
return null;
}
$ret = null;
if ($row = mysql_fetch_object( $cur )) {
$ret = $row;
}
mysql_free_result( $cur );
return $ret;
}

function insertid() {
return mysql_insert_id( $this->link );
}

function query($sql, $key = "", $returns = true, $batch = false) {
$result = array ();

switch ($batch) {
default:
case true:
foreach ($sql as $index => $query) {
$this->queries[] = $query;
$answer = mysql_query($query, $this->link);

if (!$answer) {
$this->errors[] = mysql_error($this->link);
}
else {
if ($returns != false) {
if (mysql_num_rows($answer) > 0){
while ($row = mysql_fetch_object($answer)) {
if ($key != ""){
$result[$index][$row->$key] = $row;
}
else {
$result[$index][] = $row;
}
}
} else {}
} else {}
}
}
break;

case false:
$this->queries[] = $sql;
$answer = mysql_query($sql, $this->link);

if (!$answer) {
$this->errors[] = mysql_error($this->link);
$result = false;
}
else {
if ($returns != false) {
if (mysql_num_rows($answer) > 0){
while ($row = mysql_fetch_object($answer)) {
if ($key != ""){
$result[$row->$key] = $row;
}
else {
$result[] = $row;
}
}
} else {}
}
else {
$result = true;
}
}
break;
}

return $result;
}

function loadObject( $sql, &$object ) {
if ($object != null) {
if (!($cur = $this->justquery($sql))) {
return false;
} else {}
if ($array = mysql_fetch_assoc( $cur )) {
mysql_free_result( $cur );
$this->bindArrayToObject( $array, $object);
return true;
}
else {
return false;
}
}
else {
if ($cur = $this->justquery($sql)) {
if ($object = mysql_fetch_object( $cur )) {
mysql_free_result( $cur );
return true;
}
else {
$object = null;
return false;
}
}
else {
return false;
}
}
}

function bindArrayToObject( $array, &$obj) {
if (!is_array( $array ) || !is_object( $obj )) {
return (false);
}

foreach (get_object_vars($obj) as $k => $v) {
if( substr( $k, 0, 1 ) != '_' ) {
$ak = $k;
if (isset($array[$ak])) {
$obj->$k = $array[$ak];
}
}
}

return true;
}

function formatCSVCell($data) {
$useQuotes = false;

$quotable = array (
""" => """",
"," => ",",
"
" => "
"
);

foreach ($quotable as $char => $repl) {
if (eregi($char, $data)) {
$useQuotes = true;
} else {}
}

if ($useQuotes == true) {
foreach ($quotable as $char => $repl) {
$data = str_replace($char, $repl, $data);
}

$data = """ . $data . """;
}
else {

}

return $data;
}
}
?>

source

AIR ActiveRecord is Open Source

1.
var employee = new Employee();
2.
employee.loadBy("username = ?", "bobTheBuilder");
3.

4.
// accessing tasks will autoload them from the database
5.
for each (var task:Task in employee.tasks)
6.
trace(task);
7.

8.
task = new Task("Call your mother");
9.
employee.task.push(task);
10.
employee.saveTasks();
11.

12.
employee.firstName = "Bobby";
13.
employee.save();
14.

15.
var employee2:Employee = new Employee();
16.
employee2.firstName = "Sue";
17.
....
18.
employee2.save();
19.
trace(employee2.id); // new id

source

Drupal function to return contents of a databasetable (for Debugging)

function helpers_database_render_table($table_name) {
$columns = $header = $rows = array();

$result = db_queryd('SHOW columns in {%s}', $table_name);
while ($column = db_fetch_object($result)) {
$header[] = t('@columnname (@columntype)', array('@columnname' => $column->Field, '@columntype' => $column->Type));
$columns[] = $column->Field;
}

$result = pager_query('SELECT * FROM {%s}', 50, 0, NULL, $table_name);
while ($record = db_fetch_object($result)) {
foreach($columns as $column) {
//@TODO: include spans with title=fullresult on large results, and add ellipses in that case.
$row[$column] = drupal_substr($record->$column, 0, 36);
}
$rows[] = $row;
}

$count = db_result(db_query("SELECT count(%s) FROM {%s}", $columns[0], $table_name));

$caption = t('SELECT * FROM {%table_name} resulted in %count results', array('%table_name' => $table_name, '%count' => $count));

return theme('table', $header, $rows, array(), $caption) . theme('pager');
}

source

database class

<?php

class DB {

//connection variables
protected $dbhost = 'localhost';
protected $dbuser = 'root';
protected $dbpass = '';
protected $dbname = 'database';

//normal global resources
protected $db = null;
protected static $instance = null;

/**
* Singleton pattern for instantiating the DB class
*/
public static function GetInstance()
{
if(!self::$instance)
{
self::$instance = new DB;
}
return self::$instance;
}

protected function __construct()
{
if(($db = @mysql_connect($this->dbhost, $this->dbuser, $this->dbpass)) === false)
{
trigger_error('There was an error connecting to the server.');
exit;
}

if((@mysql_select_db($this->dbname, $db)) === false)
{
trigger_error('There was an error selecting the database.');
exit;
}
$this->db = $db;
}

/**
* simple method for sanitizing SQL query strings.
*/
public function Clean($string)
{
if(get_magic_quotes_gpc())
{
$string = stripslashes($string);
}
return mysql_real_escape_string($string);
}

/**
* DB class method call to the Query child class.
* SELECT queries only
* Returns number of rows affected.
*/
public function Query($statement)
{
return new Query($statement, $this->db);
}

/**
* DB class method call to the Execute child class.
* INSERT/UPDATE/DELETE queries only
* Returns number of rows affected.
*/
public function Execute($statement)
{
return new Execute($statement, $this->db);
}

/**
* Used to get the last inserted record
*/
public function InsertID()
{
return mysql_insert_id($this->link);
}

public function __destruct()
{
@mysql_close($this->db);
}

}

/**
* These are separate classes for the reason that I would like
* to be able to edit them with as little distruption to the
* flow of the parent class as possible.
*/

/**
* Query child class. Used for running SELECT queries.
* Called exclusively by the DB parent class in the Query method
*/
class Query
{
protected $result;

public function __construct($statement, $link)
{
if(($this->result = mysql_query($statement, $link)) === false)
{
trigger_error('There was an error in processing the Query method: '. mysql_error());
exit;
}
}

/**
* I dont really like how this class is going so far. its almost
* emulating the regular set of mysql_fetch_*() functions.
*
* So, im going to try and implement some sort of method where
* i can specify the fetch action as an argument.
* EG. $result = $db->Query($query)->Fetch('object', 'class');
* Or $arr = $db->Query($query)->Fetch('assoc');
*/
public function Get($method, $class = null)
{
$sql_magic = "mysql_fetch_".$method;
if(isset($class))
{
return @$sql_magic($this->result, $class);
} else {
return @$sql_magic($this->result);
}
}

public function NumRows()
{
return @mysql_num_rows($this->link);
}

public function __destruct()
{
@mysql_free_result($this->result);
}
}

/**
* Execute child class. Used for running INSERT/UPDATE/DELETE queries.
* Called exclusively by the DB parent class in the Execute method
*/
class Execute
{
public function __construct($statement, $link)
{
if((@mysql_query($statement, $link)) == false)
{
trigger_error('There was an error processing the Execute method: '. mysql_error());
exit;
}
return @mysql_affected_rows($link);
}
}

class Paginate
{
/**
* Adding this so that I can have pagination included in the class
*
* Its gonna be a bitch though.
*/
}

?>

source

PEAR::DB MySQL Functions

<?php
// import PEAR DB libraries.
require_once("DB.php");

// Connects to database, returns PEAR DB Object.

function connect() {
$db =& DB::connect("mysql://user:password@host/database");
if(DB::isError($db)) {
die($db->getMessage());
}
return $db;
}

// Returns a list of Arrays containing the results
function execute_query($sql) {
$conn = connect();
$resultset = $conn->query($sql);
if(PEAR::isError($resultset)) {
die("Error: " . $resultset->getError());
}
$results = Array();

while($row =& $resultset->fetchRow(DB_FETCHMODE_ASSOC)) {
$results[] = $row;
}
$conn->disconnect();
return $results;
}
?>

source

MySQL DB Class

<?php
/**************************************
seesaw associates | <a href="http://seesaw.net" >http://seesaw.net</a>

client: 		mysql
file: 			class.mysql.php
description: 	handles mysql paging

Copyright (C) 2008 Matt Kenefick(.com)
**************************************/

class DB{
var $host;
var $user_name;
var $password;
var $db_name;

var $link_id;
var $result;
var $col;
var $query;
var $fields;
var $records;
var $setting;

var $debug = false;
var $query_count = 0;
var $debug_file = "debug.sql";

function settings($key,$value){
$this->setting[$key] = $value;
}

function init($_host, $_user, $_password, $_db_name){
$this->host = $_host;
$this->user_name = $_user;
$this->password = $_password;
$this->db_name = $_db_name;
$this->fields = array();

$this->link_id = @mysql_connect($_host, $_user, $_password) or die("Your website is not properly installed.");
@mysql_select_db($_db_name, $this->link_id);
}

function assign($field, $value){
$this->fields[$field] = ($value)==""?("'".$value."'"):$value;
}
function assign_str($field, $value){
$this->fields[$field] = "'".addslashes($value)."'";
//$this->fields[$field] = "'".($value)."'";
}

function reset(){
$this->fields = array();
}
function insert($table){
$f = "";
$v = "";
reset($this->fields);
foreach($this->fields as $field=>$value){
$f.= ($f!=""?", ":"").$field;
$v.= ($v!=""?", ":"").$value;
}
$sql = "INSERT INTO ".$table." (".$f.") VALUES (".$v.")";
$this->query($sql);
return $this->insert_id();
}

function update($table, $where){
$f = "";
reset($this->fields);
foreach($this->fields as $field=>$value){
$f.= ($f!=""?", ":"").$field." = ".$value;
}
$sql = "UPDATE ".$table." SET ".$f." ".$where;
$this->query($sql);
}

function timestampFormat($unixNumber){
return date('Y-m-d H:i:s',$unixNumber);
///      xxxx-xx-xx xx-xx-xx
}

function query($_query){
list($usec, $sec) = explode(" ",microtime());
$time_start  = ((float)$usec + (float)$sec);

$this->query = $_query;
$this->result = @mysql_query($_query, $this->link_id) or die( $_query."<p>".mysql_error($this->link_id) );

list($usec, $sec) = explode(" ",microtime());
$time_end  =  ((float)$usec + (float)$sec);
$time = $time_end - $time_start;

if($this->debug){
$this->query_count ++;
$f = fopen($this->debug_file, "a");
$sss = "# ".$this->query_count."
".$time." sec

".$_query."
#-------------------------------------------------------------------------

";
fputs($f, $sss, strlen($sss));
fclose($f);
}

return $this->result;
}

function get_records(){
$this->records = array();
while($row = @mysql_fetch_array($this->result, MYSQL_BOTH)){
$this->records[count($this->records)] = $row;
}
reset($this->records);
return $this->records;
}

function get_tables_status(){
$this->query("SHOW TABLE STATUS FROM `".$this->db_name."`");
if($this->num_rows() > 0){
$tables = array();
while($this->movenext()){
$tables[$this->col["Name"]] = $this->col;
}
return $tables;
}
return false;
}

function fetch_array(){
$this->col = @mysql_fetch_array($this->result, MYSQL_BOTH);
}

function num_rows(){
return (int)@mysql_num_rows($this->result);
}

function fixSlashes(){
if($this->col){
foreach($this->col as $key => $value)
$this->col[$key] = stripslashes($value);
return $this->col;
}
}

function movenext(){
$this->col=@mysql_fetch_array($this->result, MYSQL_ASSOC);
if($this->setting['fixSlashes'])
return $this->fixSlashes();
else
return $this->col;
}

function done(){
@mysql_close($this->link_id);
}

function insert_id(){
return @mysql_insert_id($this->link_id);
}

function affected_rows(){
return @mysql_affected_rows($this->link_id);
}
}
?>

source

listValues function

	function listValues($tbl='',$sql='', $velden='*') {
dbConnect();
$result=mysql_query("select $velden from $tbl $sql");
//echo "select $velden from $tbl $sql";
$x=0;
while($row=mysql_fetch_array($result)) {
for($j=0;$j<mysql_num_fields($result);$j++) {
$name = mysql_field_name($result, $j);
$list[$x][$name]=$row[$name];
}
$x++;
}
return $list;
}

source