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 ;-)
Related
I came across an ancient PHP project where there's a modified QuickDB class(I had to strip it as it was too big for StackOverflow).
It'll work just fine if there's just one instance of QuickDB, but if you add another, it'll get real bad as the second instance overwrites the previous connection.
I'm struggling to find an elegant solution, could anyone give me a hint?
<?php
if (!function_exists("mysql_connect")) {
/* warning: fatal error "cannot redeclare" if a function was disabled in php.ini with disable_functions:
disable_functions =mysql_connect,mysql_pconnect,mysql_select_db,mysql_ping,mysql_query,mysql_fetch_assoc,mysql_num_rows,mysql_fetch_array,mysql_error,mysql_insert_id,mysql_close,mysql_real_escape_string,mysql_data_seek,mysql_result
*/
global $mysqli_connection;
function mysql_connect($host, $username, $password) {
global $mysqli_connection;
$mysqli_connection = mysqli_connect($host, $username, $password);
return $mysqli_connection;
}
function mysql_pconnect($host, $username, $password) {
return mysqli_connect("p:" . $host, $username, $password);
}
function mysql_num_fields($result) {
return mysqli_num_fields($result);
}
function mysql_field_name($result, $i) {
return mysqli_fetch_field_direct($result, $i)->name;
}
function mysql_fetch_object($result) {
return mysqli_fetch_object($result);
}
function mysql_select_db($db, $dbconnect = false) {
global $mysqli_connection;
if (!$dbconnect) {
$dbconnect = $mysqli_connection;
}
return mysqli_select_db($dbconnect, $db);
}
function mysql_ping($dbconnect = false) {
global $mysqli_connection;
if (!$dbconnect) {
$dbconnect = $mysqli_connection;
}
return mysqli_ping($dbconnect);
}
function mysql_query($stmt) {
global $mysqli_connection;
return mysqli_query($mysqli_connection, $stmt);
}
function mysql_fetch_assoc($erg) {
return mysqli_fetch_assoc($erg);
}
function mysql_num_rows($e) {
return mysqli_num_rows($e);
}
function mysql_affected_rows($e = NULL) {
return mysqli_affected_rows($e);
}
function mysql_fetch_array($e) {
return mysqli_fetch_array($e);
}
function mysql_error() {
global $mysqli_connection;
return mysqli_error($mysqli_connection);
}
function mysql_errorno() {
global $mysqli_connection;
return mysqli_errorno($mysqli_connection);
}
function mysql_insert_id() {
global $mysqli_connection;
return mysqli_insert_id($mysqli_connection);
}
function mysql_close() {
return true;
}
function mysql_fetch_row($erg) {
return mysqli_fetch_row($erg);
}
function mysql_errno() {
global $mysqli_connection;
return mysqli_errno($mysqli_connection);
}
function mysql_real_escape_string($s) {
global $mysqli_connection;
return mysqli_real_escape_string($mysqli_connection, $s);
}
function mysql_data_seek($re, $row) {
return mysqli_data_seek($re, $row);
}
function mysql_result($res, $row = 0, $col = 0) {
$numrows = mysqli_num_rows($res);
if ($numrows && $row <= ($numrows - 1) && $row >= 0) {
mysqli_data_seek($res, $row);
$resrow = (is_numeric($col)) ? mysqli_fetch_row($res) : mysqli_fetch_assoc($res);
if (isset($resrow[$col])) {
return $resrow[$col];
}
}
return false;
}
function mysql_set_charset($connection, $charset) {
return mysqli_set_charset($connection, $charset);
}
}
if (!function_exists('ereg_replace')) {
function ereg_replace($p1, $p2, $p3) {
return preg_replace("/".$p1.'/', $p2, $p3);
}
}
class QuickDB
{
private $con = null; // for db connection
private $row = null; // for fetched row
private $rows = null; // for number of rows fetched
private $affected = null; // for number of rows affected
private $insert_id = null; // for last inserted id
private $query = null; // for the last run query
public $show_errors = null; // for knowing whether to display errors
private $emsg = null; // for mysql error description
private $eno = null; // for mysql error number
// Intialize the class with connection to db
/**
* #param $host
* #param $user
* #param $password
* #param $db
* #param bool $persistent
* #param bool $show_errors
* #param bool $new_link
*/
public function __construct($host, $user, $password, $db, $persistent = false, $show_errors = false, $new_link = false)
{
if ($show_errors == true) {
$this->show_errors = true;
}
if ($persistent == true) {
$this->con = #mysql_pconnect($host, $user, $password, $new_link);
mysql_set_charset($this->con, "utf8"); // předefinování defaultu 8.6.2017
} else {
$this->con = #mysql_connect($host, $user, $password, $new_link);
mysql_set_charset($this->con, "utf8"); // předefinování defaultu 8.6.2017
}
if ($this->con) {
$result = mysql_select_db($db, $this->con) or die("Could Not Select The Database !!");
return $result;
} else {
die("Could Not Establish The Connection !!");
}
}
// Close the connection to database
/**
*
*/
public function __destruct()
{
$this->close();
}
// Close the connection to database
/**
* #return bool
*/
public function close()
{
//$result = #mysql_close($this->con); // orig
$result = #mysql_close($this->con);
return $result;
}
}
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 created a function to grab data from my database. I want this function to be reusable just by placing correct arguments for different tables. Here's what I've done :
public function selectdata($table, $arguments='*', $where = null){
if($this->isconnect){
//check whether users put column names in the select clause
if(is_array($arguments)){
$new_args = implode(',', $arguments);
$sql = 'SELECT '.$new_args.' FROM '.$table;
} else {
$sql = 'SELECT '.$arguments.' FROM '.$table;
}
//check whether users use the where clause
if($where != null && is_array($where)){
$where = implode(' ', $where);
$sql .= ' WHERE '.$where ;
}
$query = $this->db->query($sql);
$query -> SetFetchMode(PDO::FETCH_NUM);
while($row = $query->fetch()){
print_r($row);
}
} else {
echo 'failed, moron';
}
}
And this is the way to run the function :
$columnname = array('bookname');
$where = array('bookid','=','2');
echo $database-> selectdata('buku', $columnname, $where);
The code worked quite decently so far, but I'm wondering how I want to use $where but without $columnname in the function. How do I pass the arguments in the function?
And could you point to me the better way to create a function to grab data using PDO?
Just use a PDO class which can look like this:
<?php
class DB_Connect{
var $dbh;
function __construct(){
$host = "xxx";
$db = "xxx";
$user = "xxx";
$password = "xxx";
$this -> dbh = $this -> db_connect($host, $db, $user, $password);
}
public function getDBConnection(){
return $this -> dbh;
}
protected function db_connect($host, $db, $user, $password){
//var_dump($host, $db, $user, $password);exit();
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->getDBConnection();
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;
}
}
}
?>
Now you can include that class and create an object with $dbh = new DB_Connect; and call every statement you want just with the reference on $dbh->query($statement)
This is my prefered way to do this.
EDIT: If you want to use a statement on another Database, just use the __construct($db) method to pass your database name on object creation
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
}
I've been using this class:
<?
class DbConnector {
var $theQuery;
var $link;
function DbConnector() {
$host = 'localhost';
$db = 'my_db';
$user = 'root';
$pass = 'password';
// connect to the db
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
}
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;
}
function insert($query) {
$ret = mysql_query($query, $this->link);
if (mysql_affected_rows() < 1)
return false;
return true;
}
function query($query) {
$this->theQuery = $query;
return mysql_query($query, $this->link);
}
// get some results
function fetchArray($result) {
return mysql_fetch_array($result);
}
function close() {
mysql_close($this->link);
}
function exists($query) {
$ret = mysql_query($query, $this->link);
if (mysql_num_rows($ret) == 0)
return false;
}
function last_id($query) {
return mysql_insert_id($query);
}
}
?>
Which I'm using for a lot of queries and it's working fine, although I'm trying to insert using this query:
global $db;
$query = $db->insert("INSERT INTO `submissions` (
`id` ,
`quote` ,
`filename` ,
`date_added` ,
`uploaded_ip`
)
VALUES (
NULL , '{$quote}', '{$filename}', NOW(), '{$_SERVER['REMOTE_ADDR']}')
");
And it's giving me this error:
Not Found
The requested URL /horh_new/id/<br /><b>Fatal error</b>: Call to a member function insert() on a non-object in <b>/Applications/MAMP/htdocs/horh_new/addit.php</b> on line <b>52</b><br /> was not found on this server.
Although when I don't use that class above, and use this instead:
$con = mysql_connect("localhost","root","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO `submissions` (
`id` ,
`quote` ,
`filename` ,
`date_added` ,
`uploaded_ip`
)
VALUES (
NULL , '{$quote}', '{$filename}', NOW(), '{$_SERVER['REMOTE_ADDR']}')
");
echo mysql_insert_id();
mysql_close($con);
It works fine. Can anyone tell me what is wrong with my class? I'd really appreciate it.
You should do like
global $db;
$db = new DbConnector();
Or the better way to use this is
add a static function of class DbConnector, which will create only single instance throughout a request
public static function getInstance(){
static $instance = null;
if($instance === null){
$instance = new DbConnector();
}
return $instance;
}
And use this class as
$db = DbConnector::getInstance();
$db->insert($query);
you need to instantiate the object before using it
$db = new DbConnetor();
now you can do an insert
although i suggest adding a __construct method to connect to the database first
class DbConnector {
public function __construct() {
// connect to db here
}
Are you sure $db contains an instance of your class? Maybe just do a var_dump() of $db just before your call to $db->insert() and see if it's set.