I want to ask help for my MySQLI OOP. My MySQLI Class look like this:
Class DB {
Private $connection;
Public Function __construct($host = "localhost", $user = "root", $password = "", $db = "social_network") {
$this->host = $host;
$this->db = $db;
$this->user = $user;
$this->password = $password;
$this->connection = #new mysqli($this->host, $this->user, $this->password);
$this->connection->set_charset("UTF-8");
if($this->connection->connect_errno > 0){
die('Tietokantapalvelimeen ei saada yhteyttä [' . $this->connection->connect_error . ']');
} else {
if(!$this->connection->select_db($db)) {
die('Tietokantaan ei saada yhteyttä: ' . $this->connection->error);
}
return $this->connection;
}
}
Public Function connect() {
if(!$this->connection){
return $this->connection;
}
return true;
}
Public Function disconnect() {
if($this->connection){
$this->connection->kill($this->connection->thread_id);
$this->connection->close();
}
return true;
}
Public Function query($sql) {
return $this->connection->query($sql);
}
Public Function result($sql) {
$query = $this->connection->query($sql);
if($query){
$result = array();
$i = 0;
while($row = $query->fetch_object()){
$result[$i] = $row;
$i++;
}
return $result;
} else {
return print $this->connection->error;
}
}
Public Function escape_string($sql) {
return $this->connection->real_escape_string($sql);
}
Public Function __destruct() {
$this->disconnect();
}
}
Example result:
$DB = new DB($_CONFIG['host'], $_CONFIG['user'], $_CONFIG['password'], $_CONFIG['db']);
$row = $DB->result("SELECT username, password FROM users WHERE username = T0niiiiii LIMIT 1");
print $row['username'];
I get error "Unknown column 'T0niiiiii' in 'where clause' ".
So what is wrong? How i fix that? Or anyone know ready MySQLI OOP?
If you don't wrap the value with apostrophes, MYSQL will 'think' you're referencing a column.
This should be your code:
$DB->result("SELECT username, password FROM users WHERE username = 'T0niiiiii' LIMIT 1");
You didn't even need to ask in here, the error message says it all.
And about retrieving the row, you could do this:
$query = $DB->query("SELECT username, password FROM users WHERE username = 'T0niiiiii' LIMIT 1");
foreach ($query->result() as $row)
{
echo $row->username;
echo $row->password; //Never echo the password, this is just for testing :P
}
Related
Is it possible to get different output when you run the exact same query from PHP vs. PHPMyAdmin? When I run
$sql = "SELECT IF(PersonA=200, PersonB, PersonA) AS Person
FROM People
WHERE PersonA=200 OR PersonB=200;";
I get the correct output from PHPMyAdmin but a different (incorrect) result from my PHP code above. The following is my SQL class I use.
<?php
class SQLQueryExecutor {
private $queryString;
private $conn;
private $db;
private $host;
private $username;
private $password;
public function __construct($queryString, $db, $host, $username, $password) {
$this->queryString = $queryString;
$this->conn = NULL;
$this->db = $db;
$this->host = $host;
$this->username = $username;
$this->password = $password;
}
// make connection to mysql database
public function makeConnection() {
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->db);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
}
// execute query
public function executeQuery() {
if ($this->conn != NULL)
{
$result = mysqli_query($this->conn, $this->queryString);
$rows = Array();
if ($result !== False) // resource returned?
{
while($row=mysqli_fetch_assoc($result))
{
$rows= $row;
}
return $rows;
}
}
return NULL;
}
// close sql connection
public function closeConnection() {
mysql_close($this->conn);
}
} // class
?>
I call this class as follows...
$user = $_GET['User_ID'];
$sql = "
SELECT IF(PersonA=$user, PersonB, PersonA) AS Person
FROM People
WHERE PersonA=$user OR PersonB=$user;";
$newSQLQueryExecutor = new SQLQueryExecutor($sql, "blah","blah", "blah", "blah");
$newSQLQueryExecutor->makeConnection();
$rows = $newSQLQueryExecutor->executeQuery();
$friends = Array("friends" => $rows);
$newSQLQueryExecutor->closeConnection();
print_r($friends);
The PHPMyAdmin prints all the correct rows but the PHP only prints the very last row.
Here is your issue, a mistake in the executeQuery() method
public function executeQuery() {
if ($this->conn != NULL) {
$result = mysqli_query($this->conn, $this->queryString);
$rows = Array();
if ($result !== False) { // resource returned?
while($row=mysqli_fetch_assoc($result)) {
$rows[] = $row;
// amended ^^
}
return $rows;
}
}
return NULL;
}
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.
I am making a module in which I am fetching users from Database Using OOP.
But due to some reason , records are not fetching, and there is no mysql error.
Here is my Code:
dbsetup_class.php :
<?php
class mySQL{
var $host;
var $username;
var $password;
var $database;
public $dbc;
public function connect($set_host, $set_username, $set_password, $set_database)
{
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$this->database = $set_database;
$this->dbc = mysqli_connect($this->host, $this->username, $this->password, $this->database) or die('Error connecting to DB');
}
public function query($sql)
{
/* echo "<pre>";
var_dump($this->dbc);
*/
//echo $sql;
return mysqli_query($this->dbc, $sql) or die('Error querying the Database');
}
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
public function close()
{
return mysqli_close($this->dbc);
}
}
?>
And here is my index.php:
<?php
require_once("dbsetup_class.php");
$connection = new mySQL();
$connection->connect('localhost', 'admin', 'admin', 'oop_test');
//die('success');
$myquery = "SELECT * FROM users";
$query = $connection->query($myquery);
$array = $connection->fetch($query);
while($array)
{
echo $array['first_name'] . '<br />';
echo $array['last_name'] . '<br />';
}
$connection->close();
?>
What I am doing here?
Your fetch method expects SQL query, and not the result of a query. You should redefine it as (assuming that the client code is what you want as an interface):
public function fetch($resource)
{
$array = mysqli_fetch_array($resource);
return $array;
}
Also if you have results, your while will be infinite.
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);
}
}
After taking some advice from people on here in a previous thread, I'm trying to convert my MySQL to PDO, but am running into some issues.
Here is my original MySQL connection class:
class DbConnector {
public static function getInstance() {
static $instance = null;
if ($instance === null) {
$instance = new DbConnector();
}
return $instance;
}
protected $theQuery;
private $link;
function DbConnector() {
$host = 'localhost';
$db = '';
$user = '';
$pass = '';
// connect to the db
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
}
public function find($query) {
$ret = mysql_query($query, $this->link);
if (mysql_num_rows($ret) == 0)
return array();
$retArray = array();
while ($row = mysql_fetch_array($ret))
$retArray[] = $row;
return $retArray;
}
public function insert($query) {
$ret = mysql_query($query, $this->link);
if (mysql_affected_rows() < 1)
return false;
return true;
}
public function query($query) {
$this->theQuery = $query;
return mysql_query($query, $this->link);
}
public function fetchArray($result) {
return mysql_fetch_array($result);
}
public function close() {
mysql_close($this->link);
}
public function exists($query) {
$ret = mysql_query($query, $this->link);
if (mysql_num_rows($ret) == 0)
return false;
}
public function last_id($query) {
return mysql_insert_id($query);
}
}
Here is the function that I'm writing:
function getRandomSubmission() {
global $db;
if(!empty($_GET['id'])){
$submission_id = $_GET['id'];
$query = $db->find("
SELECT
*
FROM
`submissions`
WHERE id = '{$submission_id}'
LIMIT 1
");
}
else {
$query = $db->find("
SELECT
*
FROM
`submissions`
ORDER BY RAND()
LIMIT 1
");
}
if($query) {
return $query[0];
}
else {
$query = $db->find("
SELECT
*
FROM
`submissions`
ORDER BY RAND()
LIMIT 1
");
}
}
Here is the PDO connector:
$host = 'localhost';
$username = '';
$pass = '';
$db = '';
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $username, $pass);
} catch (PDOException $e) {
echo $e->getMessage();
}
Here is what I've tried to convert it to, but it's just plain wrong. I think I need to be returning a PDO associative array in the 2nd if statement, but am not sure.
function getRandomSubmission() {
global $dbh;
if(!empty($_GET['id'])){
$submission_id = $_GET['id'];
$stmt = $dbh->prepare('
SELECT
*
FROM
`submissions`
WHERE
`id` = ?
LIMIT 1
');
$stmt->bindParam(1, $submission_id, PDO::PARAM_INT);
$stmt->execute();
}
else {
$stmt = $dbh->prepare('
SELECT
*
FROM
`submissions`
ORDER BY RAND()
LIMIT 1
');
$stmt->execute();
}
if($stmt) {
return $stmt[0];
}
else {
$stmt = $dbh->prepare('
SELECT
*
FROM
`submissions`
ORDER BY RAND()
LIMIT 1
');
$stmt->execute();
}
}
The original one works as intended, however (I realize I left the connection details blank).
You need to call fetch method of the PDOStatement object:
return $stmt->fetch()
Read about the fetch style, really you don't need FETCH_BOTH ;-)