Displaying data using MySQL class in PHP - php

I know how to display data without using class, but i have been asked to use mysql class instead. It seems that i have to initiate the class and just use the written functions, but whatever i try to display - it doesn't work. All i am getting is "Resource id #14", which means that everything should be good with the connection. Please help!
This is a part of the MySQL class:
class SQL //MySQL
{
var $link_id;
var $query_result;
var $num_queries = 0;
function connect($db_host, $db_username, $db_password, $db_name = '', $use_names = '', $pconnect = false, $newlink = true) {
if ($pconnect) $this->link_id = #mysql_pconnect($db_host, $db_username, $db_password);
else $this->link_id = #mysql_connect($db_host, $db_username, $db_password, $newlink);
if (!empty($use_names)) $this->query("SET NAMES '$use_names'");
if ($this->link_id){
if($db_name){
if (#mysql_select_db($db_name, $this->link_id)) return $this->link_id;
else die(mysql_error());// = "Can't open database ('$db_name')";
if (!empty($use_names)) $this->query("SET NAMES '$use_names'");
}
} else die(mysql_error());// = "Can't connect to mysql server";
}
function db($db_name) {
if ($this->link_id){
if (#mysql_select_db($db_name, $this->link_id)) return $this->link_id;
else die(mysql_error());// = "Can't open database ('$db_name')";
} else die(mysql_error());// = "Can't connect to database";
}
function query($sql){
$this->query_result = #mysql_query($sql, $this->link_id);
if ($this->query_result){
++$this->num_queries;
return $this->query_result;
} else {
$error = "
<pre>
QUERY: \n {$sql} \n\n
ERROR: <span style=\"color:red\">" . mysql_error() . " </span>
</pre>
";
die($error);
}
}
function result($query_id = 0, $row = 0, $field = NULL){
return ($query_id) ? #mysql_result($query_id, $row, $field) : false;
}
function fetch_row($query_id = 0){
return ($query_id) ? #mysql_fetch_row($query_id) : false;
}
function fetch_array($query_id = 0){
return ($query_id) ? #mysql_fetch_array($query_id) : false;
}
function fetch_assoc($query_id = 0){
return ($query_id) ? #mysql_fetch_assoc($query_id) : false;
}
function num_rows($query_id = 0){
return ($query_id) ? #mysql_num_rows($query_id) : false;
}
....
and my php code:
<?php
require_once('C:/wamp/www/smarty-3.1.21/libs/Smarty.class.php');
include('C:/wamp/www/smarty-3.1.21/libs/Mysql.class.php');
$smarty = new Smarty();
$smarty->enableSecurity();
$smarty->setTemplateDir('C:\wamp\www\forum\templates');
$smarty->setCompileDir('C:\wamp\www\forum\templates_c');
$smarty->setConfigDir('C:\wamp\www\forum\configs');
$smarty->setCacheDir('C:\wamp\www\forum\cache');
$db = new SQL();
$db->connect('localhost','root','','job', '', false, true);
$db->db('job');
$sql = "SELECT * FROM job";
$db->query($sql);
$output = $db->query_result;
$result = $db->fetch_row();
$smarty->assign('rez', $result);
$smarty->assign('output', $output);
$smarty->display('index.tpl');
?>

Related

Autoreconnect class for database in php

I am developing a class for Database access and query.
If database is accessible it is working correctly, But problem comes when somehow database is restarted.
Below is the code for library and its users code.
It is able to reconnect with database, but unable to select database. I have tried for 2,5 retry attempts from select_from_db function. But its throwing error Unable to select database test MySQL server has gone away. I am using Windows machine and in sleep time i am executing below command for restarting mysql.
net stop wampmysqld
net start wampmysqld
Please let me know for your suggestion and answers, so that i can improve on it.
<?php
class database {
private $host;
private $user;
private $pswd;
private $name;
private $db_handle;
private $error_msg;
function __construct($db_host, $db_user, $db_pswd, $db_name=NULL){
$this->host = $db_host;
$this->user = $db_user;
$this->pswd = $db_pswd;
$this->name = $db_name;
$this->db_handle = NULL;
$this->error_msg = NULL;
}
function connect(){
if(!is_null($this->db_handle)){
return True;
}
echo "Trying connection..\n";
$this->db_handle = mysql_connect($this->host, $this->user, $this->pswd);
if(!$this->db_handle){
$this->db_handle = NULL;
$this->error_msg = "Unable to connect to database : ".mysql_error();
return False;
}
else{
echo "\nconnected to database successfully!\n";
}
echo $this->name. "\n";
if(!is_null($this->name)){
$result = mysql_select_db($this->name, $this->db_handle);
if(!$result){
$this->db_handle = NULL;
$this->error_msg = 'Unable to select database '.$this->name.' '.mysql_error();
return False;
}
else{
echo "\nselected database successfully!\n";
}
}
return True;
}
function select_from_db($query, $retry=True){
if(!$this->is_connected()){
$result = $this->connect();
echo " 45 : $result\n";
if(!$result)
return $result;
}
echo " executing query \n";
$result = mysql_query($query, $this->db_handle);
if(!$result){
if(stristr(mysql_error(), 'MySQL server has gone away') === False){
$this->error_msg = "Unable to execute query ".mysql_error();
}
else{
if($retry){
$this->db_handle = NULL;
$result = $this->connect_wait(30,5);
return $this->select_from_db($query, False);
}
}
}
echo mysql_error();
echo " returning result $result query \n";
return $result;
}
function insert_to_db($query){
$result = $this->select_from_db($query);
if(!$result)
return $result;
if(stripos($query, 'insert into') !== False){
return mysql_insert_id($this->db_handle);
}
return $result;
}
function is_connected(){
if(is_null($this->db_handle))
return False;
return True;
}
function connect_wait($seconds_to_wait=30, $no_iterations=-1){
$result = $this->connect();
for($counter = 0; ($counter < $no_iterations) && !$result; $counter++){
echo "** $counter \n";
echo "\n$result waiting\n";
sleep($seconds_to_wait);
$result = $this->connect();
echo "\n$result\n";
}
return $result;
}
function disconnect() {
if(!is_null($this->db_handle)){
mysql_close($this->db_handle);
$this->db_handle = NULL;
}
}
function get_error() {
return $this->error_msg;
}
function __destruct() {
$this->disconnect();
}
}
// Connection to database machine
$db_host = 'localhost';
$db_user = 'root1';
#$db_pswd = 'rTpswd$567';
$db_pswd = '';
$db_name = 'test';
$db_table = 'user_login_info';
$db_obj = new database($db_host, $db_user, $db_pswd, $db_name);
if($db_obj->connect()){
echo "Connected";
sleep(20);
echo "Querying";
$query = "select * from $db_table";
$result = $db_obj->select_from_db($query);
if(!$result){
echo mysql_error();
die($db_obj->get_error());
}
while($row = mysql_fetch_assoc($result)){
echo "{$row['user_login_name']} {$row['user_password']}\n";
}
$db_obj->disconnect();
}
?>
PDO is a good library, you don't have to write your own !
You can add a class https://gist.github.com/extraordinaire/4135119 and use it to automatically reconnect when the database is away.

DB class wont load

I'm trying to connect using a simle db class. For some reason it only print out
"Initiate DB class"
test.php
include 'db.class.php';
echo 'Initiate DB class';
$db = new DB();
echo 'DB class did load';
db.class.php
class DB extends mysqli {
private static $instance = null;
private function __construct () {
parent::init();
$host = 'localhost';
$user = 'root';
$pass = 'MY_PASS';
$dbse = 'MY_DB';
parent::real_connect($host, $user, $pass, $dbse);
if (0 !== $this->connect_errno):
die('MySQL Error: '. mysqli_connect_error());
//throw new Exception('MySQL Error: '. mysqli_connect_error());
endif;
}
public function fetch ($sql, $id = null, $one = false) {
$retval = array();
if ($res = $this->query($sql)):
$index = 0;
while ($rs = $res->fetch_assoc()):
if ($one):
$retval = $rs; break;
else:
$retval[$id ? $rs[$id] : $index++] = $rs;
endif;
endwhile;
$res->close();
endif;
return $retval;
}
}
I have tried to search my log files for error but they come out empty.
Ok got it,
In your call to db your calling new DB(); which mean you're trying to call the constructor of your DB class.
In your DB class it looks like you're trying to create a singleton, but something is missing normally there would be something to assign the instance the database connection, and something that asks the instance if it's empty create a new connection or if it's not use the same instance.
At the end of the day to make this work you can change your constructor to public.
Try this:
Db_class:
class Db_class{
/***********************CONNECT TO DB*********************/
public function db_connect(){
$user = '***';
$db = '***';
$password = '***';
$host = '***';
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
/******************PREPARE AND EXECUTE SQL STATEMENTS*****/
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->db_connect();
if($dbh){
try{
$sql = $dbh->prepare($statement);
$exe = $sql->execute();
}
catch(PDOException $err){
return $err->getMessage();
}
switch($keyword){
case "SELECT":
$result = array();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
break;
default:
return $exe;
break;
}
}
else{
return false;
}
}
Other PHP:
$db = new Db_class();
$sql = "SQL STATEMENT";
$result = $db->query($sql);
Your constructor is marked as private which means new DB will raise an error. I see you have a private property to store an instance, are you missing the singleton method to return a new object?

PDO Insert query in table in another database not working

I want to make a sendmail function on my program. But first, I want to store the information: send_to, subject, and message in a table in another database(mes) where automail is performed. The problem is data fetched from another database(pqap) are not being added on the table(email_queue) in database(mes).
In this code, I have a table where all databases in the server are stored. I made a query to select a specific database.
$sql5 = "SELECT pl.database, pl.name FROM product_line pl WHERE visible = 1 AND name='PQ AP'";
$dbh = db_connect("mes");
$stmt5 = $dbh->prepare($sql5);
$stmt5->execute();
$data = $stmt5->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
Then after selecting the database,it has a query for selecting the information in the table on the selected database. Here's the code.
foreach ($data as $row5) GenerateEmail($row5['database'], $row5['name']);
Then this is part (I think) is not working. I don't know what's the problem.
function GenerateEmail($database, $line) {
$sql6 = "SELECT * FROM invalid_invoice WHERE ID=:id6";
$dbh = db_connect($database);
$stmt6 = $dbh->prepare($sql6);
$stmt6->bindParam(':id6', $_POST['idtxt'], PDO::PARAM_INT);
$stmt6->execute();
$data = $stmt6->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
foreach ($data as $row6) {
$invnumb=$row6['Invoice_Number'];
$partnumb=$row6['Part_Number'];
$issue=$row6['Issues'];
$pic=$row6['PIC_Comments'];
$emailadd= $row6['PersoninCharge'];
if($row6['Status']=="Open") {
$message = "<html><b>Invoice Number: {$invnumb}.</b><br><br>";
$message .= "<b>Part Number:</b><br><xmp>{$partnumb}</xmp><br><br>";
$message .= "<b>Issues:</b><br><xmp>{$issue}</xmp><br>";
$message .= "<b>{$pic}<b><br>";
$message .= "</html>";
if(!empty($emailadd)) {
dbInsertEmailMessage($emailadd, "Invoice Number: {$invnumb} - {$issue}.", $message);
$dbh=null;
}
}
}
}
function dbInsertEmailMessage($send_to, $subject, $message) {
$sql7 = "INSERT INTO email_queue (Send_to, Subject, Message) VALUES (:send_to, :subject, :message)";
$dbh = db_connect("mes");
$stmt7 = $dbh->prepare($sql7);
$stmt7->bindParam(':send_to', $send_to, PDO::PARAM_STR);
$stmt7->bindParam(':subject', $subject, PDO::PARAM_STR);
$stmt7->bindParam(':message', $message, PDO::PARAM_STR);
$stmt7->execute();
$dbh=null;
}
Here's my db connection:
function db_connect($DATABASE) {
session_start();
// Connection data (server_address, database, username, password)
$servername = '*****';
//$namedb = '****';
$userdb = '*****';
$passdb = '*****';
// Display message if successfully connect, otherwise retains and outputs the potential error
try {
$dbh = new PDO("mysql:host=$servername; dbname=$DATABASE", $userdb, $passdb, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
return $dbh;
//echo 'Connected to database';
}
catch(PDOException $e) {
echo $e->getMessage();
}
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
There are a couple things that may help with your failed inserts. See if this is what you are looking for, I have notated important points to consider:
<?php
// take session_start() out of your database connection function
// it draws an error when you call it more than once
session_start();
// Create a connection class
class DBConnect
{
public function connect($settings = false)
{
$host = (!empty($settings['host']))? $settings['host'] : false;
$username = (!empty($settings['username']))? $settings['username'] : false;
$password = (!empty($settings['password']))? $settings['password'] : false;
$database = (!empty($settings['database']))? $settings['database'] : false;
try {
$dbh = new PDO("mysql:host=$host; dbname=$database", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// You return the connection before it hits that setting
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
catch(PDOException $e) {
// Only return the error if an admin is logged in
// you may reveal too much about your database on failure
return false;
//echo $e->getMessage();
}
}
}
// Make a specific connection selector
// Put in your database credentials for all your connections
function use_db($database = false)
{
$con = new DBConnect();
if($database == 'mes')
return $con->connect(array("database"=>"db1","username"=>"u1","password"=>"p1","host"=>"localhost"));
else
return $con->connect(array("database"=>"db2","username"=>"u2","password"=>"p2","host"=>"localhost"));
}
// Create a query class to return selects
function query($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return (!empty($result))? $result:0;
}
// Create a write function that will write to database
function write($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
}
// Do not create connections in your function(s), rather pass them into the functions
// so you can use the same db in and out of functions
// Also do not null the connections out
function GenerateEmail($con,$conMes,$line = false)
{
if(empty($_POST['idtxt']) || (!empty($_POST['idtxt']) && !is_numeric($_POST['idtxt'])))
return false;
$data = query($con,"SELECT * FROM `invalid_invoice` WHERE `ID` = :0", array($_POST['idtxt']));
if($data == 0)
return false;
// Instead of creating a bunch of inserts, instead create an array
// to build multiple rows, then insert only once
$i = 0;
foreach ($data as $row) {
$invnumb = $row['Invoice_Number'];
$partnumb = $row['Part_Number'];
$issue = $row['Issues'];
$pic = $row['PIC_Comments'];
$emailadd = $row['PersoninCharge'];
if($row['Status']=="Open") {
ob_start();
?><html>
<b>Invoice Number: <?php echo $invnumb;?></b><br><br>
<b>Part Number:</b><br><xmp><?php echo $partnumb; ?></xmp><br><br>
<b>Issues:</b><br><xmp><?php echo $issue; ?></xmp><br>
<b><?php echo $pic; ?><b><br>
</html>
<?php
$message = ob_get_contents();
ob_end_clean();
if(!empty($emailadd)) {
$bind["{$i}to"] = $emailadd;
$bind["{$i}subj"] = "Invoice Number: {$invnumb} - {$issue}.";
$bind["{$i}msg"] = htmlspecialchars($message,ENT_QUOTES);
$sql[] = "(:{$i}to, :{$i}subj, :{$i}msg)";
}
}
$i++;
}
if(!empty($sql))
return dbInsertEmailMessage($conMes,$sql,$bind);
return false;
}
function dbInsertEmailMessage($con,$sql_array,$bind)
{
if(!is_array($sql_array))
return false;
write($con,"INSERT INTO `email_queue` (`Send_to`, `Subject`, `Message`) VALUES ".implode(", ",$sql_array),$bind);
return true;
}
// Create connections
$con = use_db();
$conMes = use_db('mes');
GenerateEmail($con,$conMes);

Handling results from MySQLi query after MySql to MySqli conversion

I am trying to change the following code to use MySqli instead of MySql. I have removed some methods that seem unimportant to what I'm addressing here.
class db {
var $hostname,
$database,
$username,
$password,
$connection,
$last_query,
$last_i,
$last_resource,
$last_error;
function db($hostname=DB_HOSTNAME,$database=DB_DATABASE,$username=DB_USERNAME,$password=DB_PASSWORD) {
$this->hostname = $hostname;
$this->database = $database;
$this->username = $username;
$this->password = $password;
$this->connection = mysql_connect($this->hostname,$this->username,$this->password) or $this->choke("Can't connect to database");
if($this->database) $this->database($this->database);
}
function database($database) {
$this->database = $database;
mysql_select_db($this->database,$this->connection);
}
function query($query,$flag = DB_DEFAULT_FLAG) {
$this->last_query = $query;
$resource = mysql_query($query,$this->connection) or $this->choke();
list($command,$other) = preg_split("|\s+|", $query, 2);
// Load return according to query type...
switch(strtolower($command)) {
case("select"):
case("describe"):
case("desc"):
case("show"):
$return = array();
while($data = $this->resource_get($resource,$flag)) $return[] = $data;
//print_r($return);
break;
case("replace"):
case("insert"):
if($return = mysql_insert_id($this->connection))
$this->last_i = $return;
break;
default:
$return = mysql_affected_rows($this->connection);
}
return $return;
}
function resource_get($resource = NULL,$flag = DB_DEFAULT_FLAG) {
if(!$resource) $resource = $this->last_resource;
return mysql_fetch_array($resource,$flag);
}
}
This is what I've got so far:
class db {
var $hostname = DB_HOSTNAME,
$database = DB_DATABASE,
$username = DB_USERNAME,
$password = DB_PASSWORD,
$connection,
$last_query,
$last_i,
$last_resource,
$last_error;
function db($hostname, $database, $username, $password) {
$this->hostname = $hostname;
$this->database = $database;
$this->username = $username;
$this->password = $password;
$this->connection = new mysqli($this->hostname, $this->username, $this->password, $this->database) or $this->choke("Can't connect to database");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if($this->database)
$this->database($this->database);
}
function database($database) {
$this->database = $database;
mysqli_select_db($this->connection, $this->database );
}
function query($query, $flag = DB_DEFAULT_FLAG) {
$this->last_query = $query;
//print_r($query);
$result = mysqli_query($this->connection, $query) or $this->choke("problem connecting to DB");
while($row=mysqli_fetch_assoc($result)) {
$resource[]=$row;
}
//print($command);
//print_r($resource);print("<br>");
list($command, $other) = preg_split("|\s+|", $query, 2);
// Load return according to query type...
switch(strtolower($command)) {
case("select"):
case("describe"):
case("desc"):
case("show"):
$return = array();
while($data = $this->resource_get($resource, $flag))
$return[] = $data;
//print_r($return);
break;
case("replace"):
case("insert"):
if($return = mysqli_insert_id($this->connection))
$this->last_i = $return;
break;
default:
$return = mysqli_affected_rows($this->connection);
}
return $return;
}
function resource_get($resource = NULL, $flag = DB_DEFAULT_FLAG) {
if(!$resource)
$resource = $this->last_resource;
return mysqli_fetch_array($resource, $flag);
}
So here's the problem: I've checked the results with a print_r() and the $resource array is loading correctly, but the value of $return when checked with print_r() just ends up being "Array()". Therefore, as near as I can figure, something isn't being handled correctly in this part of the code, which is why I included the resource_get() function call:
$return = array();
while($data = $this->resource_get($resource, $flag))
$return[] = $data;
//print_r($return);
break;
If I use mysqli_fetch_row($resource, $flag) instead of mysqli_fetch_array($resource, $flag) I still get the same result, i.e. print_r($return) yields simply "Array()".
The variable $resource does not represent a mysqli_result resource object at the time you pass it into $this->resource_get(). Instead, it is already a 2D array of results since you previously ran a mysqli_fetch_assoc() loop.
To make this work with your current code, you may either remove the earlier fetch loop:
$result = mysqli_query($this->connection, $query) or $this->choke("problem connecting to DB");
// Remove this
//while($row=mysqli_fetch_assoc($result)) {
// $resource[]=$row;
//}
And later, pass $result instead of $resource into your resource_get() method since it is $result that is the resource object.
Or, you might just skip the resource_get() call entirely and return $resource directly since it already contains the result array.

Update PHP class from mssql_ to sqlsrv_

We've just updated PHP on our server, for the most part everything is fine, but the mssql_ functions aren't supported any more unfortunately. I've tried to update our previous class:
$connection['server'] = 'server, port';
$connection['user'] = 'user';
$connection['pass'] = 'pass';
$connection['db'] = 'db';
class mssqlClass {
function connect($dbhost = NULL){
global $connection;
if(! ISSET ($dbconnect)){
$dbconnect = mssql_Connect($connection['server'], $connection['user'], $connection['pass'], true);
}
if(! $dbconnect){
return 'Failed to Connect to Host';
}else{
$select = mssql_select_db($connection['db'], $dbconnect);
if(! $select){
return 'Failed to select Database';
}else{
return $dbconnect;
}
}
}
function getData ($query){
$this->data_array = array();
$result = mssql_query($query);
while ($row = mssql_fetch_assoc($result)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query){
$result = mssql_query($query) or die("Query didn't work");
}
}
To be compliant with sqlsrv_, and whilst I can connect to the database without any issues, it won't return any data!:
class mssqlClass {
function connect($database = 'Db') {
$mssql_server = 'server';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
if(! ISSET ($dbconnect)){
$dbconnect = sqlsrv_connect($mssql_server, $mssql_data);
}
if(! $dbconnect){
return 'Failed to connect to host';
}
}
function getData ($query) {
$result = sqlsrv_query($db->connect, $query);
while ($row = sqlsrv_fetch_array($result)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work.");
}
}
ps. Example usage is as follows:
$db = new mssqlClass();
$conn = $db->connect('DATABASE');
$query = "SELECT * FROM Table";
$result= $db->getData($query);
So sorry for the horrible amount of code - I can edit it down to just the getData function if that's easier? Thank you!!
I've made some changes in your class:
<?php
class mssqlClass {
protected $connection = null;
public function connect($database = 'Db') {
// we don't need to connect twice
if ( $this->connection ) {
return;
}
// data for making connection
$mssql_server = 'gc-hr01';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
// try to connect
$this->connection = sqlsrv_connect($mssql_server, $mssql_data);
if(! $dbconnect){
return 'Failed to connect to host';
}
}
public function getData ($query) {
// reset results; is this really needed as object's variable? Can't it be just local function's variable??
$this->data_array = array();
$result = $this->query($this->connection, $query);
while ($row = sqlsrv_fetch_array($result)) {
$this->data_array[] = $row;
}
return $this->data_array;
}
public function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work..");
}
}
The code looks fine. The only thing which could be your problem is that sqlsrv_fetch_array needs maybe a second parameter e.g.:
sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC)
Because the default is that it returns two arrays with different formats. And if you may acess attributes by name it will return nothing but not fail.
Something like this. Because you actually call the sqlsrv_query method with the return value of the following method. And in the original version you missed to return the connection resource.
function connect($database = 'Db') {
$mssql_server = 'gc-hr01';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
$dbconnect = sqlsrv_connect($mssql_server, $mssql_data);
if(! $dbconnect){
return 'Failed to connect to host';
}
return $dbconnect;
}
in advance
function getData ($query) {
$result = sqlsrv_query($db->connect(), $query);
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work.");
}
I found this page while trying to find a quick short-cut to someone else's wrapper class for sqlsrv commands. Since this wasn't really complete, I have compiled my own quickly. Please don't think this is production code, you should test and test again, but it might help someone out of a jam quickly.
class db {
protected $connection = null;
private $debug = true;
private $stmt = null;
private $insertid = null;
private $affectedrows = null;
public function db($host = '.',$database,$username,$password) {
// we don't need to connect twice
if ( $this->connection ) {
return;
}
sqlsrv_configure('WarningsReturnAsErrors', 0);
// data for making connection
$sqlsvr_details = array( 'UID' => $username,
'PWD' => $password,
'Database' => $database,
'CharacterSet' => 'UTF-8'
);
// try to connect
$this->connection = sqlsrv_connect($host, $sqlsvr_details);
if($this->connection == false){
$this->debug('Failed to connect to host: '.$this->errors(),true);
return false;
}else{
return true;
}
}
public function query($query) {
return new resultset($query,$this->connection,$this->debug);
}
private function debug ($message,$hard = false){
if ($this->debug){
if ($hard){
die($message);
}else{
echo $message;
}
}
return true;
}
public function delete($query){
return $this->update($query);
}
public function update($query){
//Not happy with this
$this->affectedrows = null;
$this->insertid = null;
$this->stmt = sqlsrv_query($this->connection, $query);
if (!$this->stmt){
$this->debug('SQL Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
$this->affectedrows = #sqlsrv_rows_affected($this->stmt);
return $this;
}
}
public function insert($query){
//Not happy with this
$this->affectedrows = null;
$this->insertid = null;
$this->stmt = sqlsrv_query($this->connection, $query);
if (!$this->stmt){
$this->debug('SQL Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
//Get the last insert ID and store it on here
$this->insertid = $this->query('select ##IDENTITY as insert_id')->asObject()->insert_id;
return $this;
}
}
public function insert_id(){
return $this->insertid;
}
public function affected_rows(){
return $this->affectedrows;
}
private function errors(){
return print_r( sqlsrv_errors(SQLSRV_ERR_ERRORS), true);
}
}
class resultset implements Countable,Iterator {
private $result = null;
private $connection = null;
private $debug = false;
private $internal_pointer = 0;
private $data = array();
public function resultset($query,$link,$debug = false){
$this->connection = $link;
$this->debug = $debug;
$this->result = sqlsrv_query($this->connection, $query, array(), array('Scrollable' => SQLSRV_CURSOR_STATIC));
if ($this->result == false){
$this->debug('Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
return $this;
}
}
public function asObject($step = true){
$object = sqlsrv_fetch_object($this->result,NULL,NULL,SQLSRV_SCROLL_ABSOLUTE,$this->internal_pointer);
if (! $object){
return false;
}else{
if ($step) $this->internal_pointer++;
return $object;
}
}
public function num_rows() {
return sqlsrv_num_rows($this->result);
}
public function free(){
$this->internal_pointer = 0;
if (is_resource($this->result)){
sqlsrv_free_stmt($this->result);
}
}
public function __destory(){
$this->free();
}
//Countable Function
public function count(){
return $this->num_rows();
}
//Iteration Functions
public function rewind(){
$this->internal_pointer = 0;
}
public function current(){
return $this->asObject(false);
}
public function key(){
return $this->internal_pointer;
}
public function next(){
$this->internal_pointer++;
}
public function valid(){
return $this->internal_pointer <= $this->num_rows();
}
//============================================
private function debug ($message,$hard = false){
if ($this->debug){
if ($hard){
die($message);
}else{
echo $message;
}
}
return true;
}
private function errors(){
return print_r( sqlsrv_errors(SQLSRV_ERR_ERRORS), true);
}
}

Categories