Unable to connect to mysql using php - php

While trying to connect through PHP it displays
Warning: mysqli_connect(): (HY000/1044): Access denied for user ''#'localhost' to database 'bookedscheduler' in C:\wamp\www\booked\lib\Database\MySQL\MySqlConnection.php on line 52
Warning: mysqli_select_db() expects parameter 1 to be mysqli, boolean given in C:\wamp\www\booked\lib\Database\MySQL\MySqlConnection.php on line 53
Warning: mysqli_set_charset() expects parameter 1 to be mysqli, boolean given in C:\wamp\www\booked\lib\Database\MySQL\MySqlConnection.php on line 54
Cannot modify header information - headers already sent by (output started at C:\wamp\www\booked\lib\Database\MySQL\MySqlConnection.php:53) in C:\wamp\www\booked\Pages\Page.php on line 138
My config.php
database connection
$conf['settings']['database']['type'] = 'mysql';
$conf['settings']['database']['user'] = 'booked_user';
$conf['settings']['database']['password'] = '';
$conf['settings']['database']['hostspec'] = '127.0.0.1';
$conf['settings']['database']['name'] = 'bookedscheduler';
Mysqlconnection.php file
class MySqlConnection implements IDbConnection
{
private $_dbUser = '';
private $_dbPassword = '';
private $_hostSpec = '';
private $_dbName = '';
private $_db = null;
private $_connected = false;
/**
* #param string $dbUser
* #param string $dbPassword
* #param string $hostSpec
* #param string $dbName
*/
public function __construct($dbUser, $dbPassword, $hostSpec, $dbName)
{
$this->_dbUser = $dbUser;
$this->_dbPassword = $dbPassword;
$this->_hostSpec = $hostSpec;
$this->_dbName = $dbName;
}
public function Connect()
{
if ($this->_connected && !is_null($this->_db))
{
return;
}
$this->_db = mysqli_connect($this->_hostSpec, $this->_dbUser, $this->_dbPassword,$this->_dbName);
$selected = mysqli_select_db($this->_db, $this->_dbName);
mysqli_set_charset($this->_db, 'utf8');
if (!$this->_db || !$selected)
{
throw new Exception("Error connecting to database\nError: " . mysql_error());
Log::Error("Error connecting to database\n%s", mysql_error());
}
$this->_connected = true;
}
public function Disconnect()
{
mysqli_close($this->_db);
$this->_db = null;
$this->_connected = false;
}
public function Query(ISqlCommand $sqlCommand)
{
mysqli_set_charset($this->_db, 'utf8');
$mysqlCommand = new MySqlCommandAdapter($sqlCommand, $this->_db);
Log::Sql('MySql Query: ' . str_replace('%', '%%', $mysqlCommand->GetQuery()));
$result = mysqli_query($this->_db, $mysqlCommand->GetQuery());
$this->_handleError($result);
return new MySqlReader($result);
}
public function LimitQuery(ISqlCommand $command, $limit, $offset = 0)
{
return $this->Query(new MySqlLimitCommand($command, $limit, $offset));
}
public function Execute(ISqlCommand $sqlCommand)
{
mysqli_set_charset($this->_db, 'utf8');
$mysqlCommand = new MySqlCommandAdapter($sqlCommand, $this->_db);
Log::Sql('MySql Execute: ' . str_replace('%', '%%', $mysqlCommand->GetQuery()));
$result = mysqli_query($this->_db, $mysqlCommand->GetQuery());
$this->_handleError($result);
}
public function GetLastInsertId()
{
return mysqli_insert_id($this->_db);
}
private function _handleError($result, $sqlCommand = null)
{
if (!$result)
{
if ($sqlCommand != null)
{
echo $sqlCommand->GetQuery();
}
throw new Exception('There was an error executing your query\n' . mysql_error());
Log::Error("Error executing MySQL query %s", mysql_error());
}
return false;
}
}
class MySqlLimitCommand extends SqlCommand
{
/**
* #var \ISqlCommand
*/
private $baseCommand;
private $limit;
private $offset;
public function __construct(ISqlCommand $baseCommand, $limit, $offset)
{
parent::__construct();
$this->baseCommand = $baseCommand;
$this->limit = $limit;
$this->offset = $offset;
$this->Parameters = $baseCommand->Parameters;
}
public function GetQuery()
{
return $this->baseCommand->GetQuery() . sprintf(" LIMIT %s OFFSET %s", $this->limit, $this->offset);
}
}
?>
Please someone guide me in this regard

It is very easy and I am providing you a tested answer, first you need to build the Database class as seen below, you need to put it in a file and include it from your homepage (might be the index.php page). Then, you need to initiate an instance of your class from the homepage to connect to the database, the code is very well explained in details in this great article: www.muwakaba.com/php-database-connection
<?php
// Class definition
class Database{
// The constructor function
public function __construct(){
// The properties
$this->host = "your_DB_host_address";
$this->login = "your_DB_login_name";
$this->password = "your_DB_password";
$this->name = "your_DB_name";
// The methods
$this->connect();
$this->select();
}
// The connect function
private function connect(){
$this->connection = mysql_connect($this->host, $this->login, $this->password) or die("Sorry! Cannot connect to the database");
}
// The select function
private function select(){
mysql_select_db($this->name, $this->connection);
}
}
?>

Related

PDO::__construct(): MySQL server has gone away

this seems to be a common issue, and I've read a lot about it tried to use 'ini_set' to change time outs and still getting this error after only 5 seconds. below is a sample of my code to show the flow between classes.
the thing that i'm most confused about is that it throws this warning after 5 seconds (even after a page refresh), but it still retrieves the data from the database.
require('../cfg/config.php');
class Process {
/**
* #var PDO
*/
private $conn = null;
/**
* #var PDOException
*/
public $error = null;
private $host = DB_SERVER;
private $user = DB_USER;
private $pass = DB_PASS;
private $db = DB_NAME;
public function __construct() {
ini_set('mysql.connect_timeout', 300);
ini_set('default_socket_timeout', 300);
$this->connect();
}
private function connect() {
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->db;
$options = [
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
];
try {
$this->conn = new PDO($dsn, $this->user, $this->pass, $options);
} catch(PDOException $e) {
$this->error = $e->getMessage();
}
return $this->conn;
}
public function query($sql, $params = null) {
preg_match('/SELECT/', $sql) ? $select = true : $select = false;
$connect = $this->conn->getAttribute(PDO::ATTR_CONNECTION_STATUS);
echo "CONNECTION STATUS::: " . $connect;
if($this->error == null) {
$query = $this->conn->prepare($sql);
$query->execute($params);
$query ? (!$select ? $results = true : $results = $query->fetchAll(PDO::FETCH_ASSOC))
: $results = false;
} else {
$results = $this->error;
}
return $results;
}
}
class Arrays {
public $family = [];
/**
* #var \Process
*/
private $db;
public function __construct() {
$this->db = new Process();
}
public function setFamily() {
$a = [];
$sql = "SELECT familyNick, familyName FROM budget.family ORDER BY familyOrder";
$query = $this->db->query($sql);
if($query != false && is_array($query)) {
foreach($query as $k => $v) {
$a[$v['familyNick']] = $v['familyName'];
}
}
$this->family = $a;
}
/**
* #return array
*/
public function getFamily() {
if(empty($this->family) || !isset($this->family)) {
$this->setFamily();
}
return $this->family;
}
}
class Options {
public $family = [];
/**
* #var \Arrays
*/
private $arrays;
public function __construct() {
$this->arrays = new Arrays();
}
public function setFamily() {
$this->family = $this->arrays->getFamily();
}
public function getFamilyOptions() {
if(empty($this->family)) {
$this->setFamily();
}
$options = [];
foreach($this->family as $famNick => $famName) {
$options[] = "<option class='family' value='$famNick'>" . $famName . "</option>";
}
return $options;
}
}
$test = new Options();
$family = $test->getFamilyOptions();
var_dump($family);
i'm certain there are various design flaws to this code. i'm just concerned about the PDO warning at this point.
for what i was trying to accomplish simply removing
ATTR_PERSISTENT => true
from the option array did the trick!

Querying JSON from PHP Function

I have a sequence order of PHP programming that i need to query from a table and insert it in a JSON array. I dont know where my mistake is but it just doesnt go through. please help me,
in dbinfo.inc.php,
define("ORA_CON_UN", "ADMIN");
define("ORA_CON_PW", "pass");
define("ORA_CON_DB", "192.168.100.195/finance");
class db {
private $conn;
private $lastId;
private static $instance;
private function _construct(){
$this->connect();
}
public static function create(){
if (!isset(self::$instance)) {
self::$instance = new db();
}
return self::$instance;
}
public function connect($dbconn = ORA_CON_DB, $dbuser = ORA_CON_UN, $dbpass = ORA_CON_PW){
$this->conn = oci_connect($dbuser, $dbpass, $dbconn);
}
}
and in DBFunction.php
include 'dbinfo.inc.php';
class Connection{
private $dbConnection;
public function _construct($dbConnection){
$this->dbConnection = $dbConnection;
}
function initConnection(){
$db = new db();
$dbConnection = $db->connect();
}
}
class PurchaseOrder {
private $job = '%';
private $subjob = '%';
public function _construct($job, $subjob){
$this->job = $job;
$this->subjob = $subjob;
}
function listPO($job, $subjob){
$conn = new Connection();
$conn->initConnection();
$sql = oci_parse($conn, 'SELECT VPI.PO_NO FROM VW_PO_INFO#WENFINANCE_WENLOGINV_LINK WHERE VPI.PROJECT_NO = ' .$job. ' AND VPI.PROJECT_NAME = ' .$subjob);
if (!$conn) {
$oerr = OCIError($conn);
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
exit();
} else {
echo 'CONNECTION SUCCEDED';
}
$rows = array();
while ($r = oci_fetch_assoc($sql)){
$rows[] = $r;
}
$listPO = json_encode($rows);
oci_execute($sql);
oci_close($conn);
}
}
and lastly, testDBFunction.php
include('DBFunction.php');
$queryOracle = new PurchaseOrder();
$queryOracle->listPO('W-IGG','');
var_dump($queryOracle);
and this is my error message,
Warning: oci_parse() expects parameter 1 to be resource, object given
in C:\xampp\htdocs\WeltesFinance\pages\lib\DBFunction.php on line 36
CONNECTION SUCCEDED Warning: oci_fetch_assoc() expects parameter 1 to
be resource, null given in
C:\xampp\htdocs\WeltesFinance\pages\lib\DBFunction.php on line 47
Warning: oci_execute() expects parameter 1 to be resource, null given
in C:\xampp\htdocs\WeltesFinance\pages\lib\DBFunction.php on line 52
object(PurchaseOrder)#1 (2) { ["job":"PurchaseOrder":private]=>
string(1) "%" ["subjob":"PurchaseOrder":private]=> string(1) "%" }
I dont know exactly where my error is, Please help me
UPDATE:
I made some more updates to your code and classes, here's relevant changes for each file.
dbinfo.inc.php
<?php
define("ORA_CON_UN", "ADMIN");
define("ORA_CON_PW", "pass");
define("ORA_CON_DB", "192.168.100.195/finance");
Class DbConnect{
private $user = null;
private $password = null;
private $db_string = null;
public function __construct(){
$this->user = ORA_CON_UN;
$this->password = ORA_CON_PW;
$this->db_string = ORA_CON_DB;
}
public function connect() {
$connection = oci_pconnect($this->user, $this->password, $this->db_string);
return $connection;
}
}
?>
DBfunction.php
<?php
include 'dbinfo.inc.php';
// there is no need for a Connection class unless you want further wrapping or something :-/
Class PurchaseOrder {
// ....
public function listPO($job,$subjob){
$db = new DbConnect();
$conn = $DbConnect->connect();
if (!$conn) {
// keep your code, throw error, exit
}
else{
// move all your database processing here
$sql = oci_parse($conn, 'SELECT VPI.PO_NO FROM VW_PO_INFO...');
// also note that you are passing an empty value for the $subjob parameter, thus making the query likely to fail
oci_execute($sql);
$rows = array();
while($r = oci_fetch_assoc($sql)){
$rows[] = $r;
}
$listPO = json_encode($rows);
oci_close($conn);
}
return $listPO; // you need to return $listPO in order to be able to dump it
}
// ....
}
testDBFunction.php
<?php
include('DBFunction.php');
$queryOracle = new PurchaseOrder();
// either pass what listPO() returns to a variable and dump it
$jsonResults = $queryOracle->listPO('W-IGG','');
var_dump($jsonResults);
// or dump the return directly
// var_dump($queryOracle->listPO('W-IGG',''));
You need to return the actual connection resource in the initConnection function
See the following inline comments
function initConnection(){
$db = new db();
// $dbConnection = $db->connect(); // this is not needed since you call connect from the
// constructor, but you need to return the connection
// see below the EDIT
// return the actual connection resource
// return $dbConnection;
return $db;
}
$sql = oci_parse($conn->initConnection(), 'SELECT VPI.PO_NO FROM VW_ ...')`
EDIT:
public function connect($dbconn = ORA_CON_DB, $dbuser = ORA_CON_UN, $dbpass = ORA_CON_PW){
$this->conn = oci_connect($dbuser, $dbpass, $dbconn);
return $this->conn;
}

PHP mysqli query: couldn't fetch mysqli

I am trying to make a db connection and check a table for existing data. However I recieve this error and I am unable to find the cause:
Warning: mysqli::query(): Couldn't fetch mysqli in
/usr/share/nginx/www/me/container/class_lib.php on line
33 Warning: mysql_fetch_assoc() expects
parameter 1 to be resource, null given in
/usr/share/nginx/www/me/container/class_lib.php on line
97
class dbHandler {
static $dbObj = null;
protected $db_host = 'localhost'; #db host
protected $db_username = 'user'; #db username
protected $db_password = 'password'; #db password
protected $db_name = 'db'; #db name
function __construct()
{
# connect if not connected
if(self::$dbObj === null)
{
self::$dbObj = new mysqli($this->db_host, $this->db_username, $this->db_password, $this->db_name)
or die($this->dbObj->error);
}
mysqli_set_charset(self::$dbObj, "utf8");
}
// query: query the db
public function query($query)
{
return self::$dbObj->query($query);
}
}
/*
class userLogin
create user login
*/
class userLogin {
private $username;
private $password;
function __construct($username, $password) {
$this->_dbConn = new dbHandler();
$this->username = $username;
$this->password = $password;
}
public function verifyCredentials() {
if($this->verifyUsername())
{
} else {
exit;
}
if($this->verifyPassword())
{
} else {
exit;
}
}
private function verifyUsername() {
if(!(preg_match('/[^a-z_\-0-9]/i', $this->username)))
{
return true;
}
}
private function verifyPassword() {
$query = "SELECT * FROM tbl_user";
$result = $this->_dbConn->query($query);
$row = mysql_fetch_assoc($result);
var_dump($row);
}
}
What am I doing wrong here?
All your wrapper is over a mysqli object oriented way, and suddenly you have this line?
$row = mysql_fetch_assoc($result);
You have to use the fetch_assoc from the mysqli result object
$result->fetch_assoc()
Your SQL query is clearly failing. Why you have a function query to call a query I don't know but I have a feeling that is the route cause of your issue. You would be better off with something like this:
class dbHandler extends mysqli {
protected $db_host = 'localhost'; #db host
protected $db_username = 'user'; #db username
protected $db_password = 'password'; #db password
protected $db_name = 'db'; #db name
function __construct()
{
parent::__construct($this->db_host, $this->db_username, $this->db_password, $this->db_name);
if($this->connect_errno)
{
trigger_error('Unable to connect to the database [' . $this->connect_errno . ']: ' . $this->connect_error, E_USER_ERROR);
}
}
public function __destruct()
{
parent::close();
}
}
/*
class userLogin
create user login
*/
class userLogin {
private $username;
private $password;
function __construct($username, $password) {
$this->_dbConn = new dbHandler();
$this->username = $username;
$this->password = $password;
}
public function verifyCredentials() {
if($this->verifyUsername())
{
} else {
exit;
}
if($this->verifyPassword())
{
} else {
exit;
}
}
private function verifyUsername() {
if(!(preg_match('/[^a-z_\-0-9]/i', $this->username)))
{
return true;
}
}
private function verifyPassword() {
$query = "SELECT * FROM tbl_user";
$result = $this->_dbConn->query($query);
if($this->_dbConn->errno)
{
trigger_error('Error fetching users from table. Query: ' . $query . '. Error: ' . $this->_dbConn->error);
return false;
}
if($result->num_rows)
{
while($row = $result->fetch_assoc())
{
var_dump($row);
}
}
}
}
Let me know how you get on with that.
So... I never gave the mysql user from localhost any grants. Only from the remote LAN. Problemo solved.
Probably you are closing the connection too early? DBConnect->close();?
so, if you try to execute any query after that, you will get an error!

Database connection through class

i want to crete a class that will contain various general variables and functions to be used throughout the website. One of these things will be a database connection. I am trying the following code:
class Sys {
public $dbc = new mysqli('localhost', 'user', 'pass', 'db');
$dbc->query("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci'");
}
$system = new Sys;
It is giving me a syntax error in the first line of the class... What am i doing wrong?
Thanks
you should do things like this in the constructor. You can only set primitives in the initial declaration. Also you need braces when creating the object.
class Sys {
private $dbc;
private $someInteger = 4; // you can do this
private $someArray = array(); // and this.
public function __construct()
{
$this->dbc = new mysqli('localhost', 'user', 'pass', 'db');
$this->dbc->query("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci'");
}
public function getDbc()
{
return $this->dbc;
}
}
$system = new Sys();
//$system->getDbc()->soSomethingWithMyDb();
i would advise you to read up on using objects: http://php.net/manual/en/language.types.object.php
You should just declare a public $dbc.
And then have a constructor function function __construct() { ...... } where you initialize it/ set it up.
class Sys {
public $dbc;
function __construct() {
$this->dbc = new mysqli('localhost', 'user', 'pass', 'db');
$this->dbc->query("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci'");
}
}
$system = new Sys;
class Sys {
var $mysqli;
function DB($database,$server,$user,$pass) {
$this->mysqli = mysqli_connect($server, $user, $pass, $base) or die('Server connection not possible. '. mysqli_connect_error());
}
}
include("db.class.mysqli.php"); // db handler class
// Open the base (construct the object):
$db = new Sys(DB_NAME, SERVER_NAME, USER_NAME, PASSWORD);
This is how I do it
check out the use of magic methods http://php.net/manual/en/language.oop5.magic.php in php - as mentioned above the __construct method is needed for your class to work. Below is an example from Peter Lavin's book Object Oriented PHP http://objectorientedphp.com/ in chapter 9.
class MySQLConnect {
// Data Members
private $connection;
private static $instances = 0;
// Constructor
public function __construct($hostname, $username, $password) {
if(MySQLConnect::$instances == 0) {
$this->connection = new mysqli($hostname, $username, $password);
// Check for Errors then report them
if ($this->connection->connect_error) {
die("Connect Error ($this->connection->connect_errno) $this->connection->connect_error");
}
// Set the Class variable $instances to 1
MySQLConnect::$instances = 1;
} else {
$msg = "There's another instance the MySQLConnect Class with a connect open already. Close it";
die($msg);
}
}
}
Try this:
$db = new DB;
$link = $db->connect()->getLink();
class DB {
public $connection = array();
public function __construct() {
return $this;
}
public function connect($host=null, $user=null, $pass=null, $database=null) {
$this->connection = new Connection($host, $user, $pass, $database);
$this->connection->connect();
$this->link = $this->connection->getLink();
if ($this->connection->ping()) {
if (!is_null($database)) {
if (!$this->connection->databaseConnect($database)) {
throw new\Exception('Unable to connect to the server.');
}
}
}else{
throw new \Exception('Unable to connect to the server.');
}
return $this;
}
public function getLink() {
return $this->link;
}
}
class Connection {
protected $chost='localhost';
protected $cuser='guest';
protected $cpass='password';
protected $cdatabase='PROFORDABLE';
function __construct($host=null, $user=null, $pass=null, $database=null) {
$host = !is_null($host) ? $host : $this->chost;
$user = !is_null($user) ? $user : $this->cuser;
$password = !is_null($pass) ? $pass : $this->cpass;
$database = !is_null($database) ? $database : $this->cdatabase;
$this->set('host', $host)->set('user', $user)->set('password', $password)->set('database', $database);
return $this;
}
public function connect() {
$link = mysqli_connect($this->host->getHost(), $this->user->getUser(), $this->password->getPassword());
if (!is_object($link)) {
throw new \Exception("An error has occurred while connecting to the server.");
}
$this->link = $link;
}
public function databaseConnect($database) {
if (!mysqli_select_db($this->getLink(), $database)) {
throw new \Exception("Unable to select the database.");
}
}
public function getLink() {
return $this->link;
}
public function ping() {
if (mysqli_ping($this->link)) {
return TRUE;
}
return FALSE;
}
public function set($name, $param) {
if (!isset($name) || !isset($param)) return $this;
$class = __NAMESPACE__.'\\'.ucwords($name);
$this->$name = new $class($param);
return $this;
}
public function get($name) {
$getfunc = 'get'.ucwords($name);
return $this->$name->$getFunc();
}
}
class Host {
public function __construct($host) {
$this->setHost($host);
}
public function setHost($host) {
$this->host = $host;
}
public function getHost() {
return $this->host;
}
}
class User {
public function __construct($user) {
$this->setUser($user);
}
public function setUser($user) {
$this->user = $user;
}
public function getUser() {
return $this->user;
}
}
class Password {
public function __construct($password) {
$this->setPassword($password);
}
public function setPassword($password) {
$this->password = $password;
}
public function getPassword() {
return $this->password;
}
public function sha($value) {
return sha1($value);
}
}
class guestPassword extends Password {
const PASSWORD='password';
public function __construct() {
return PASSWORD;
}
}
class Database {
public function __construct($database) {
$this->setDatabase($database);
}
public function setDatabase($database) {
$this->database = $database;
}
public function getDatabase() {
return $this->database;
}
}
class Query {
}
//Create mysql.php and paste following code
<?php
class MySQL {
private $set_host;
private $set_username;
private $set_password;
private $set_database;
public function __Construct($set_host, $set_username, $set_password) {
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$con = mysql_connect($this->host, $this->username, $this->password);
if (!$con) {
die("Couldn't connect to the server");
}
}
//end of __construct
//connect to database
public function Database($set_database) {
$this->database = $set_database;
mysql_query("set character_set_server='utf8'");
mysql_query("set names 'utf8'");
mysql_select_db($this->database) or die("Unable to select database");
}
//fetch data from any table
public function fetch_data($sql) {
$this->sql = $sql;
$query = mysql_query($this->sql);
$result = array();
while ($record = mysql_fetch_array($query)) {
$result[] = $record;
}
return $result;
}
//fetch all columns from any table to be used for INSERT INTO.
public function get_all_columns($table_name) {
$this->table_name = $table_name;
$sql = "SHOW COLUMNS FROM $this->table_name";
$result = mysql_query($sql);
while ($record = mysql_fetch_array($result)) {
$fields[] = $record['0'];
}
$val = '';
foreach ($fields as $value) {
$val .= $value . ',';
}
$vals = rtrim($val, ',');
return $vals;
}
//insert data to any table by $_POST or set of variables separated by ,
public function insert_data($tbl_name, $tbl_value) {
$this->tbl_name = $tbl_name;
$this->tbl_value = $tbl_value;
//use mysql_real_escape_string($tbl_value) to clean & insert data.
$this->tbl_col = $this->get_all_columns($this->tbl_name);
$sql = "INSERT INTO $this->tbl_name ($this->tbl_col) VALUES ($this->tbl_value)";
$query_result = mysql_query($sql);
}
//end of insert data
public function delete_data($del_id, $table_name) {
$this->del_id = $del_id;
$this->table_name = $table_name;
if (isset($this->del_id) && is_numeric($this->del_id) && !empty($this->del_id)) {
$sql = "DELETE FROM $this->table_name WHERE id=$this->del_id LIMIT 1";
$del_result = mysql_query($sql);
$aff_row = mysql_affected_rows();
return $aff_row;
}
}
}
// class ends here
//call class to connect to server and db as well.
$connect = new MySQL('localhost', 'root', '');
$connect->Database('db_name');
?>
//include file mysql.php and call your class object as :
//fetching data from any table use :
$variable = $connect->fetch_data("SELECT * FROM table_name");
for($i=0;$i<count($variable);$i++){
$result = $variable[$i]['col_name'];
}
//insert INTO values in any table
$result = $connect->insert_data($tbl_name, $tbl_value);
if($result)
echo 'inserted';
else{
echo 'failed';
}
//delete record from any table
$result = $connect->delete_data($del_id, $table_name)
You can use a wonderful class ezSQL

ADODB Multiple Databases

I am using adodb for my database operations and here i am facing a problem that i can't add tow or 3 databases in my script i am using 3 databases but its not working properly need help in this situation.
myadodb connection file:
<?php
include_once("/adodb/adodb.inc.php");
include_once("/adodb/adodb-exceptions.inc.php");
class ADb {
function ADb()
{
global $dbserver;
global $dbuser;
global $dbpass;
global $database;
$dbuser = "";
$dbpass = "";
$dbserver = "";
$database = "";
$this->conn1 = &ADONewConnection('mysql');
$this->conn1->PConnect($dbserver, $dbuser, $dbpass, $database);
}
function query($sql)
{
try
{
$Result = $this->conn1->Execute($sql);
}
catch (exception $e)
{
echo $e->msg;
}
}
}
?>
I have created 3 files for 3 databases connections
This is a quick class that I made that should allow you to connect to 3 databases using adoDB:
class Data {
private static $_dbOne = null;
private static $_dbTwo = null;
private static $_dbThree = null;
protected function __construct() {
}
/**
* This function returns the database connection object
* #return Object Database Connection
*/
public static function dbOne() {
include_once(LIBRARY_PATH.'adodb5/adodb.inc.php');
if (null === self::$_dbOne) {
$_connOne = 'mysql://username:password#www.server.com/database';
self::$_dbOne = &ADONewConnection($_connOne);
if (self::$_dbOne==false) { die('Could not connect to the database.'); }
}
return self::$_dbOne;
}
/**
* This function returns the database connection object
* #return Object Database Connection
*/
public static function dbTwo() {
include_once(LIBRARY_PATH.'adodb5/adodb.inc.php');
if (null === self::$_dbTwo) {
$_connTwo = 'mysql://username:password#www.server.com/database';
self::$_dbTwo = &ADONewConnection($_connTwo);
if (self::$_dbTwo==false) { die('Could not connect to the database.'); }
}
return self::$_dbTwo;
}
}
/**
* This function returns the database connection object
* #return Object Database Connection
*/
public static function dbThree() {
include_once(LIBRARY_PATH.'adodb5/adodb.inc.php');
if (null === self::$_dbThree) {
$_connThree = 'mysql://username:password#www.server.com/database';
self::$_dbThree = &ADONewConnection($_connThree);
if (self::$_dbThree==false) { die('Could not connect to the database.'); }
}
return self::$_dbThree;
}
}
Here is an example of how you would use this class:
$sql = "SELECT * FROM *";
$results1 = Data::dbOne()->Execute($sql);
$results2 = Data::dbTwo()->Execute($sql);
$results3 = Data::dbThree()->Execute($sql);

Categories