php with pdo, create dynamic database connection - php

I create connection with this statement
dbh = new PDO('mysql:host=localhost;dbname=mydb;port=3306;connect_timeout=15', 'root', '');
But in my application users capable to change data sources so I need to create current database connection with server informations user posted, I try this:
dbh = new PDO('sqlsrv:server=' + $result["servername"] + ';dbname=' + $result["dbname"] + ';port=3306;connect_timeout=15', '' + $result["user"] + '', '' + $result["password"] + '');`
But it failed. Even I tried the simple code examples got documents it fails for that too.. Whats with it and how can I make it ?

At first, you cant merge strings with '+'. you must use '.' and you need to create new PDO connection object(or set it existing) for each database connection here I share parts of my code doing this:
private function __construct()
{
//default database connection
$this->dbh = new PDO('mysql:host=localhost;dbname=webfilter;port=3306;connect_timeout=15', 'root', '');
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->directed = false;
$this->resultBool = true;
}
public static function getConnection()
{
$sqlstring = "select * from datasources WHERE ACTIVE =1";
if (!isset(self::$instance))
{
$object = __CLASS__;
self::$instance = new $object;
}
if (true) {
$request = self::$instance->dbh->prepare($sqlstring);
if ($request->execute()) {
if ($result = $request->fetch(PDO::FETCH_ASSOC)) {
if ($result["SOFTWARE"] == "mysql") {
self::$instance->dbh = null;
self::$instance->connectedDbName = "mysql(" . $result["DATABASENAME"] . ")";
self::$instance->dbh = new PDO('mysql:host=' . $result["SERVERADDRESS"] . ';dbname=' . $result["DATABASENAME"] . ';port=3306;connect_timeout=15', '' . $result["USERNAME"] . '', '' . $result["PASSWORD"] . '');
self::$instance->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::$instance->directed = true;
self::$instance->resultBool = true;
} else if ($result["SOFTWARE"] == "mssql") {
self::$instance->dbh = null;//close the existing connection
self::$instance->connectedDbName = "mssql(" . $result["DATABASENAME"] . ")";
self::$instance->dbh = new PDO('sqlsrv:server=' . $result["SERVERADDRESS"] . ';Database=' . $result["DATABASENAME"] . '', '' . $result["USERNAME"] . '', '' . $result["PASSWORD"] . '');
self::$instance->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::$instance->dbh->query("use " . $result["DATABASENAME"]);
self::$instance->directed = true;
self::$instance->resultBool = true;
} else if ($result["SOFTWARE"] == "oracle") {
self::$instance->connectedDbName = "oracle(" . $result["DATABASENAME"] . ")";
self::$instance->dbh = new PDO('odbc:DRIVER=FreeTDS;server=localhost;Database=Dbname', 'username', '!123qwe');
}
self::$instance->resultBool = true;
$temp = self::$instance->dbh->query("select DEVICEID from ethernet LIMIT 1");
self::$instance->setDeviceid($temp->fetchColumn());
return self::$instance;
}
self::$instance->connectedDbName = "default";
$temp = self::$instance->dbh->query("select DEVICEID from ethernet LIMIT 1");
self::$instance->setDeviceid($temp->fetchColumn());
return self::$instance;
}
}
self::$instance->connectedDbName = "default";
return self::$instance;
}
public function getConnectionStatusMessage()
{
if ($this->resultBool) {
return "Connection Successfull" . $this->connectedDbName;
} else {
return "Connection Failed:" . $this->resultString;
}
}

$dbh = new PDO('sqlsrv:server=' . $result["servername"] . ';dbname=' . $result["dbname"] . ';port=3306;connect_timeout=15', $result["user"], $result["password"]);

Related

Create my oracle oci class in php. But data show 1 first record only

This code from my PHP Project.
and create oracle connection class.
modified from mysql connection class(work fine).
class databaseOracle
{
public $oci;
public $connected = false;
public $parameters;
public $result;
function __construct($host, $dbPort, $dbName, $userDB, $passwordDB)
{
try {
$ociDB = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = " . $host . ")(PORT = " . $dbPort . ")))(CONNECT_DATA=(SID=" . $dbName . ")))";
$this->oci = oci_connect($userDB, $passwordDB, $ociDB, 'AL32UTF8');
if (!$this->oci) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
echo "Database oracle connection Failed.</br>";
exit();
} else {
echo "Database oracle connection success.</br>";
}
} catch (EngineExcpetion $e) {
echo "Error : " . $e->getMessage() . "</br>";
}
// exit();
}
public function bind($para, $value)
{
$this->parameters[count($this->parameters)] = ":" . $para . "\x7F" . $value;
}
public function bindParams($parray)
{
if (empty($this->parameters) && is_array($parray)) {
$columns = array_keys($parray);
foreach ($columns as $i => &$column) {
$this->bind($column, $parray[$column]);
}
}
}
public function queryString($showQuery = 0, $query = "", $parameters = "")
{
$this->result = null;
if ($showQuery == 1) {
require_once('SQLFormatter.php');
echo SqlFormatter::format($query);
var_dump($parameters);
}
$this->result = oci_parse($this->oci, $query);
# Add parameters to the parameter array
$this->bindParams($parameters);
# Bind parameters
if (!empty($this->parameters)) {
foreach ($this->parameters as $param) {
$parameters = explode("\x7F", $param);
oci_bind_by_name($this->result, $parameters[0], $parameters[1]);
}
}
oci_execute($this->result);
$r = oci_fetch_array($this->result, OCI_ASSOC + OCI_RETURN_LOBS + OCI_RETURN_NULLS);
$this->parameters = array();
return $r;
}
}
$oracleDB = new databaseOracle($ociHost, $ociPort, $ociDB, $ociUsername, $ociPassword);
$query = $oracleDB->queryString(0,"SELECT * from SOME_TABLE where CREATED_BY = :created FETCH NEXT 50 ROWS ONLY",array("created" => "2"));
print_r($query);
my problem
i'm create class of oracle connection. modify from mysql connection class.
it's can query and read record from oracle database. example 50 record
but array result of query show first row only.

Php - using include/require_once inside function

I am creating a class "DBQuery" that contains all the database query functions such as insert, select, delete, ...
Everything is working fine when I create database connection inside the INSERT function. But i want separate the configuration so that i can include it in any other files and pages.
configuration.php
define("HOSTNAME", "localhost");
define("USERNAME", "root");
define("PASSWORD", "");
define("DATABASE", "edubits");
try {
$conn = new PDO("mysql:host=" . HOSTNAME . ";dbname=" . DATABASE . ";", USERNAME, PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo $e;
}
class.php
/**
* Created by PhpStorm.
* User: Sunusi Mohd Inuwa
* Date: 11/18/2018
* Time: 11:02 AM
*/
class QUERY
{
function INSERT($table, $data, $conn)
{
include_once('../configuration.php');
// variable declaration
$columns = "";
$valueset = "";
$values = "";
//loop
foreach ($data as $column => $value) {
$columns = $columns . ', ' . $column;
$valueset = $valueset . ', ?';
$values = $values . ', ' . $value;
}
//trimming the first comma from the result above
$columns = ltrim($columns, ',');
$valueset = ltrim($valueset, ',');
$values = ltrim($values, ',');
//statement
$sql = "INSERT INTO " . $table . "(" . $columns . ") VALUES(" . $valueset . ")";
//convert values to array
$values = explode(',', $values);
//query
$query = $conn->prepare($sql)->execute($values);
//$query = $conn->prepare($sql)->execute([$values]);;
}
}
Use include, not include_once. If you use include_once, then it won't execute the code in the file the second time you call the method.
But it would probably be better to include the file in the class's constructor, so you only need to execute it once, rather than create a new connection every time you perform a query. Make $conn a class property instead of an ordinary variable.
The class below give the ability to get a connection object from getInstance() funtion, so you just include the Config class where you wanna communicate with database (model)
getInstance() : is singleton, which means that you have a single instance
class Config{
private $HOSTNAME = "localhost";
private $USERNAME = "root";
private $PASSWORD = "";
private $DATABASE = "edubits";
private static $pdo = null;
public static function getInstance($data = null){
if(self::$pdo == null){
self::PDOConnect($data = null);
}
return self::$pdo;
}
private static function PDOConnect(){
try{
$info = new DBInfo($data);
self::$pdo = new PDO("mysql:host=" . $this->HOSTNAME . ";dbname=" . $this->DATABASE . ";", $this->USERNAME, $this->PASSWORD);
self::$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
self::$pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $e) {
echo new PDOCustomException($e->getMessage(), null, $e);
}
}
public function close(){
return null;
}
}
Here i've choice to use config directly from your INSERT function to get connection object, or get connexion object in constructor one time and use it many time in QUERY class
So connection instance is stored on $cn
include_once('../configuration.php');
class QUERY
{
private $cn = null;
private $DBAction = null;
public function __construct(){
try {
$cn = new DBAction();
$this->cn = $cn::getInstance();
} catch (\PDOException $ex) {
throw new PDOCustomException($ex->getMessage(), null, $ex);
} catch (\Exception $ex) {
throw new CustomException($ex->getMessage(), null, $ex);
}
}
public function INSERT($table, $data, $conn) {
$config = new Config();
// variable declaration
$columns = "";
$valueset = "";
$values = "";
//loop
foreach ($data as $column => $value) {
$columns = $columns . ', ' . $column;
$valueset = $valueset . ', ?';
$values = $values . ', ' . $value;
}
//trimming the first comma from the result above
$columns = ltrim($columns, ',');
$valueset = ltrim($valueset, ',');
$values = ltrim($values, ',');
//statement
$sql = "INSERT INTO " . $table . "(" . $columns . ") VALUES(" . $valueset . ")";
//convert values to array
$values = explode(',', $values);
//query
$query = $this->cn->prepare($sql)->execute($values);
}
}

Copy one column of the first database in the second database in MySQL

i change all of one column of database by mistake with update command (about 18000 record)
i have backup , so reastore it to another database name
all of thing i want is copy one column of backup database to that coulmn of master database (update )
so i write this code in php :
ini_set('max_execution_time', 3000000000000000000000000000000000000000000);
error_reporting(E_ALL);
ini_set('display_errors', 1);
function connection1()
{
$DBName1 = "db1";
$DBUser1 = "user1";
$DBPassword1 = "pass1";
$DBHost1 = "localhost";
try {
$pdo = new PDO("mysql:host=" . $DBHost1 . ";dbname=" . $DBName1 .
";charset=utf8", $DBUser1, $DBPassword1, array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
PDO::ERRMODE_EXCEPTION,
PDO::ATTR_ERRMODE));
return $pdo;
}
catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
}
function connection2()
{
$DBName2 = "db2";
$DBUser2 = "user2";
$DBPassword2 = "pass2";
$DBHost2 = "localhost";
try {
$pdo = new PDO("mysql:host=" . $DBHost2 . ";dbname=" . $DBName2 .
";charset=utf8", $DBUser2, $DBPassword2, array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
PDO::ERRMODE_EXCEPTION,
PDO::ATTR_ERRMODE));
return $pdo;
}
catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
}
$con2 = connection2();
$NewItem = $con2->prepare("select id,fid,title,sign from news_tmp");
$NewItem->execute();
$con1 = connection1();
$contwovalue = array();
for ($i = 0; $row = $NewItem->fetch(PDO::FETCH_ASSOC); $i++) {
$NewItem2 = $con1->prepare("select id,fid,title,sign from news_tmp where id='{$row['id']}'");
$NewItem2->execute();
$contwovalue = $NewItem2->fetch(PDO::FETCH_ASSOC);
if (($contwovalue['id'] == $row['id']) && ($contwovalue['fid'] == $row['fid']) &&
($contwovalue['sign'] == $row['sign'])) {
$NewItem2 = $con1->prepare("UPDATE `news_tmp` SET `title`=? where id=?");
$NewItem2->bindValue(1, $row['title'], PDO::PARAM_INT);
$NewItem2->bindValue(2, $contwovalue['id'], PDO::PARAM_INT);
$NewItem2->execute();
}
}
i just want to ask this question : this way is best way ? or another way exist for this problem?
Why not just use a query for that?
UPDATE
database.news
SET
database.news.title= backupdatabase.news.title
WHERE
database.news.id= backupdatabase.news.id
Edit: Oh, about 6 Months late :-)

PHP file not pulling in my .txt's

I have an admin store dashboard with an update button that triggers a php file which empties a mySQL database that then puts in new data from three .txt files (they are new stores). There is an issue where the table just gets wiped and/or the data from the .txt file is not being sent. I recently upgraded my PHP to 5.4 from 5.3 and am unsure what the issue is. Can anyone recommend me a suggestion on how to fix this issue?
PHP:
<?php
header('Content-Type: application/json; charset=UTF-8');
$argv = $_SERVER['argv'];
$totalArgv = count($argv);
// Use PDO to connect to the DB
$dsn = 'mysql:dbname=busaweb_stores;host=127.0.0.1';
$dsn_training = 'mysql:dbname=busaweb_busaedu;host=127.0.0.1';
$user = 'busaweb_*****';
$password = '*****';
try {
$dbs = new PDO($dsn, $user, $password);
$dbt = new PDO($dsn_training, $user, $password);
$dbs->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo 'Connected to SQL Server';
}
catch (PDOException $e) {
die_with_error('PDO Connection failed: ' . $e->getMessage());
}
//Check request
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "move":
move_files();
echo_success("Files have been moved.");
break;
case "update-stores":
$count = update_stores_db($dbs);
echo_success("DB Updated.<br>" . $count . " Stores Geocoded.");
break;
case "geocode":
$count = geocode_remaining($dbs);
echo_success($count . " stores geocoded.");
break;
case "update-training":
update_training_db($dbt);
echo_success("Training DB Updated.");
break;
case "update-all":
$count = update_stores_db($dbs);
update_training_db($dbt);
echo_success("DB Updated.<br>" . $count . " Stores Geocoded.");
break;
case "backup":
$backupFile = backup_db();
echo_success("DB Backed Up: <br>" . $backupFile);
break;
default:
//Close PDO Connections
$dbs = null;
$dbt = null;
break;
}
}
}
//if being executed from the shell, update all
else if($totalArgv > 0){
$count = update_stores_db($dbs);
update_training_db($dbt);
echo_success("DB Updated.<br>" . $count . " Stores Geocoded.");
break;
};
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
//Error handling
function die_with_error($error) {
$return = array(
"status" => "Failed",
"data" => $error
);
//Close PDO Connections
$dbs = null;
$dbt = null;
die(json_encode($return));
}
function echo_success($message){
$return = array(
"status" => "OK",
"data" => $message
);
$return["json"] = json_encode($return);
echo json_encode($return);
//Close PDO Connections
$dbs = null;
$dbt = null;
}
//Move all files
function move_files(){
try {
move_file('sfinder/StoreList.txt');
move_file('sfinder/StoreProductIndex.txt');
move_file('sfinder/StoreTypeIndex.txt');
move_file('training/TrainingCustomerList.txt');
}
catch(Exception $e){
die_with_error($e->getMessage());
}
//sleep(1);
//Return JSON
$return["json"] = json_encode($return);
echo json_encode($return);
}
//Move a file
function move_file($filename){
$source ="/home/busaweb/public_html/b3/" . $filename;
$dest = "/home/busaweb/public_html/adminportal/includes/sfupdate/" . $filename;
if(!copy($source, $dest)){
throw new Exception("Failed to copy file: " . $filename);
}
else{
//echo "Successfully moved $filename.<br>";
}
}
//Empty a SQL Table
function empty_table($dbconnection, $tablename){
try{
$sql = "TRUNCATE TABLE " . $tablename;
$sth = $dbconnection->prepare($sql);
//$sth->bindParam(':tablename', $tablename, PDO::PARAM_STR);
// The row is actually inserted here
$sth->execute();
//echo " [+]Table '" . $tablename . "' has been emptied.<br>";
$sth->closeCursor();
}
catch(PDOException $e) {
die_with_error($e->getMessage());
}
}
//Import CSV file from JDE to DB
function load_csv($dbconn, $filename, $tablename){
try{
$sql = "LOAD DATA LOCAL INFILE '/home/busaweb/public_html/adminportal/includes/sfupdate/" . $filename . "' INTO TABLE " . $tablename . " FIELDS TERMINATED BY '\\t' ENCLOSED BY '\"' ESCAPED BY '\\\' LINES TERMINATED BY '\\n'";
$sth = $dbconn->prepare($sql);
// The row is actually inserted here
$sth->execute();
//echo " [+]CSV File for '" . $tablename . "' Table Imported.<br>";
$sth->closeCursor();
}
catch(PDOException $e) {
die_with_error($e->getMessage());
}
}
function update_stores_db($dbs){
move_files();
empty_table($dbs, "stores");
load_csv($dbs, 'sfinder/StoreList.txt', 'stores');
empty_table($dbs, 'stores_product_type_link');
load_csv($dbs, 'sfinder/StoreProductIndex.txt', 'stores_product_type_link');
empty_table($dbs, 'stores_store_type_link');
load_csv($dbs, 'sfinder/StoreTypeIndex.txt', 'stores_store_type_link');
return $count;
}
function update_training_db($dbt){
move_file('training/TrainingCustomerList.txt');
empty_table($dbt, 'customers');
load_csv($dbt, 'training/TrainingCustomerList.txt', 'customers');
}
}
?>

Migrate PHP code from MySQL to MS SQL Server

I want to migrate a php/mysql script to php/sql-server. The script code isn't mine, I tried to hack it by replacing mysqli_connect() with sqlsrv_connect(), but it's not working.
How I can migrate the script?
the script source code : https://github.com/fixwa/BlackFramework/tree/master/Lib/xcrud
Below is the database configuration code :
/** Database driver; f0ska xCRUD v.1.6.20; 06/2014 */
class Xcrud_db
{
private static $_instance = array();
private $connect;
public $result;
private $dbhost;
private $dbuser;
private $dbpass;
private $dbname;
private $dbencoding;
private $magic_quotes;
public static function get_instance($params = false)
{
if (is_array($params))
{
list($dbuser, $dbpass, $dbname, $dbhost, $dbencoding) = $params;
$instance_name = sha1($dbuser . $dbpass . $dbname . $dbhost . $dbencoding);
}
else
{
$instance_name = 'db_instance_default';
}
if (!isset(self::$_instance[$instance_name]) or null === self::$_instance[$instance_name])
{
if (!is_array($params))
{
$dbuser = Xcrud_config::$dbuser;
$dbpass = Xcrud_config::$dbpass;
$dbname = Xcrud_config::$dbname;
$dbhost = Xcrud_config::$dbhost;
$dbencoding = Xcrud_config::$dbencoding;
}
self::$_instance[$instance_name] = new self($dbuser, $dbpass, $dbname, $dbhost, $dbencoding);
}
return self::$_instance[$instance_name];
}
private function __construct($dbuser, $dbpass, $dbname, $dbhost, $dbencoding)
{
$this->magic_quotes = get_magic_quotes_runtime();
if (strpos($dbhost, ':') !== false)
{
list($host, $port) = explode(':', $dbhost, 2);
preg_match('/^([0-9]*)([^0-9]*.*)$/', $port, $socks);
$this->connect = mysqli_connect($host, $dbuser, $dbpass, $dbname, $socks[1] ? $socks[1] : null, $socks[2] ? $socks[2] : null);
}
else
$this->connect = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (!$this->connect)
$this->error('Connection error. Can not connect to database');
$this->connect->set_charset($dbencoding);
if ($this->connect->error)
$this->error($this->connect->error);
if (Xcrud_config::$db_time_zone)
$this->connect->query('SET time_zone = \'' . Xcrud_config::$db_time_zone . '\'');
}
public function query($query = '')
{
$this->result = $this->connect->query($query, MYSQLI_USE_RESULT);
//echo '<pre>' . $query . '</pre>';
if ($this->connect->error)
$this->error($this->connect->error . '<pre>' . $query . '</pre>');
return $this->connect->affected_rows;
}
public function insert_id()
{
return $this->connect->insert_id;
}
public function result()
{
$out = array();
if ($this->result)
{
while ($obj = $this->result->fetch_assoc())
{
$out[] = $obj;
}
$this->result->free();
}
return $out;
}
public function row()
{
$obj = $this->result->fetch_assoc();
$this->result->free();
return $obj;
}
public function escape($val, $not_qu = false, $type = false, $null = false, $bit = false)
{
if ($type)
{
switch ($type)
{
case 'bool':
if ($bit)
{
return (int)$val ? 'b\'1\'' : 'b\'0\'';
}
return (int)$val ? 1 : ($null ? 'NULL' : 0);
break;
case 'int':
$val = preg_replace('/[^0-9\-]/', '', $val);
if ($val === '')
{
if ($null)
{
return 'NULL';
}
else
{
$val = 0;
}
}
if ($bit)
{
return 'b\'' . $val . '\'';
}
return $val;
break;
case 'float':
if ($val === '')
{
if ($null)
{
return 'NULL';
}
else
{
$val = 0;
}
}
return '\'' . $val . '\'';
break;
default:
if (trim($val) == '')
{
if ($null)
{
return 'NULL';
}
else
{
return '\'\'';
}
}
else
{
if ($type == 'point')
{
$val = preg_replace('[^0-9\.\,\-]', '', $val);
}
//return '\'' . ($this->magic_quotes ? (string )$val : $this->connect->real_escape_string((string )$val)) . '\'';
}
break;
}
}
if ($not_qu)
return $this->magic_quotes ? (string )$val : $this->connect->real_escape_string((string )$val);
return '\'' . ($this->magic_quotes ? (string )$val : $this->connect->real_escape_string((string )$val)) . '\'';
}
public function escape_like($val, $pattern = array('%', '%'))
{
if (is_int($val))
return '\'' . $pattern[0] . (int)$val . $pattern[1] . '\'';
if ($val == '')
{
return '\'\'';
}
else
{
return '\'' . $pattern[0] . ($this->magic_quotes ? (string )$val : $this->connect->real_escape_string((string )$val)) .
$pattern[1] . '\'';
}
}
private function error($text = 'Error!')
{
exit('<div class="xcrud-error" style="position:relative;line-height:1.25;padding:15px;color:#BA0303;margin:10px;border:1px solid #BA0303;border-radius:4px;font-family:Arial,sans-serif;background:#FFB5B5;box-shadow:inset 0 0 80px #E58989;">
<span style="position:absolute;font-size:10px;bottom:3px;right:5px;">xCRUD</span>' . $text . '</div>');
}
}
My hacked code :
private function __construct($dbname, $dbhost, $dbencoding)
{
$this->magic_quotes = get_magic_quotes_runtime();
if (strpos($dbhost, ':') !== false)
{
list($host, $port) = explode(':', $dbhost, 2);
preg_match('/^([0-9]*)([^0-9]*.*)$/', $port, $socks);
$this->connect = sqlsrv_connect($host,$dbname, $socks[1] ? $socks[1] : null, $socks[2] ? $socks[2] : null);
}
else
$this->connect = sqlsrv_connect($dbhost, $dbname);
if (!$this->connect)
$this->error('Connection error. Can not connect to database');
$this->connect->set_charset($dbencoding);
if ($this->connect->error)
$this->error($this->connect->error);
if (Xcrud_config::$db_time_zone)
$this->connect->query('SET time_zone = \'' . Xcrud_config::$db_time_zone . '\'');
}
In config file :
> // default connection
> public static $dbname = array( "Database"=>"crud1");
> > public static $dbhost = '.\sqlexpress';
You should use PDO, specially if you hope for a better future for your application or website, but you can still use sqlsrv_* functions if you want. Whatever you do, make sure you replace all function and provide the right parameters.
Let's see if you want to use SQLSRV Functions (which I don't recommend but I feel this is what you want); You need to change all mysqli_* functions with their sqlsrv_* counter part, and again, provide the right parameter in the right form:
Example
In the constructor, you have:
$this->connect = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
That should be replaced with:
$this->connect = sqlsrv_connect($dbhost, array( 'Database'=>$dbName, 'UID'=>$dbuser, 'PWD'=>$dbpass));
You see that mysqli_connect was called with 4 parameters (all strings), but sqlsrv_connect was called with only 2, (a string and an array).

Categories