Fetch data from MySQL using OOP - php

I'm a beginner in OOP PHP.
I'm trying to make a class that will connect,query and fetch data
I done the below coding
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"); }
}
public function Database($set_database)
{
$this->database=$set_database;
mysql_select_db($this->database)or die("cannot select Dataabase");
}
public function Fetch($set_table_name){
$this->table_name=$set_table_name;
$query=mysql_query("SELECT * FROM ".$this->table_name);
$result= mysql_fetch_array($query);
}
}
$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$connect->Fetch('posts');
what I'm trying to achieve is this
$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$connect->Fetch('posts');
and I want to fetch the data using a format like this
echo $result[0];
but I'm not getting that logic to make this happen
please help
Thanks!

Your Fetch function is only pulling one row from the database, and you aren't returning the results...
The method isn't the best, but in order to achieve what you're trying to do:
public function Fetch($set_table_name){
$query=mysql_query("SELECT * FROM ".$set_table_name);
$result = array();
while ($record = mysql_fetch_array($query)) {
$result[] = $record;
}
return $result;
}
This will make each row a part of $result, but you'll have to access it like this:
You would call the fetch function like this:
$result = $connect->Fetch('posts');
echo $result[0]['columnName']; // for row 0;
Or in a loop:
for ($x = 0; $x < count($result); $x++) {
echo $result[$x][0] . "<BR>"; // outputs the first column from every row
}
That said, fetching the entire result set into memory is not a great idea (some would say it's a very bad idea.)
Edit: It also looks like you have other issues with your class... I have to run but will check back tomorrow and if others haven't set you straight I will expand.
Edit2: Ok, going to do a once-over on your class and try to explain a few things:
class MySQL {
//declaring the private variables that you will access through $this->variable;
private $host;
private $username;
private $password;
private $database;
private $conn; // Adding the connection, more on this later.
public function __Construct($set_host, $set_username, $set_password){
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
// Combining the connection & connection check using 'or'
// Notice that I removed the semi-colon after the mysql_connect function
$this->conn = mysql_connect($this->host, $this->username, $this->password)
or die("Couldn't connect");
}
public function Database($set_database)
{
$this->database=$set_database;
// Adding the connection to the function allows you to have multiple
// different connections at the same time. Without it, it would use
// the most recent connection.
mysql_select_db($this->database, $this->conn) or die("cannot select Dataabase");
}
public function Fetch($table_name){
// Adding the connection to the function and return the result object instead
return mysql_query("SELECT * FROM ".$table_name, $this->conn);
}
}
$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$posts = $connect->Fetch('posts');
if ($posts && mysql_num_rows($posts) > 0) {
echo "Here is some post data:<BR>";
while ($record = mysql_fetch_array($posts)) {
echo $record[0]; // or a quoted string column name instead of numerical index.
}
} else {
echo "No posts!";
}
I hope this helps... It should get you started at least. If you have more questions you should ask them separately.

That's because $result is set inside the Fetch function. It won't be available outside the Fetch function.
Instead of this line $result= mysql_fetch_array($query);, you'll want something like return mysql_fetch_array($query);.
And then in your code
$row = $connect->Fetch('posts');
// do something with $row
On another note, your Fetch function only applies to database queries that return one row. You'll have to separate the mysql_query & mysql_fetch_array calls into another function if you want to loop through rows in a query result.
And on another note, you shouldn't need to encapsulate this code into a class. PHP already provides OOP-based database classes called PDO, or PHP Data Objects. There's a learning curve to it, but it's best practice, and will help secure your code against things like SQL injection.
This is a pretty good tutorial: http://www.giantflyingsaucer.com/blog/?p=2478

I would make a function that returns the value of the object.
public function returnData($data){
return $this->$data;
}
Then within the page you wish to get the data on just initiate the class and call the function within that class.
$post->returnDate("row name here");

<?php
//database.php
class Databases{
public $con;
public function __construct()
{
$this->con = mysqli_connect("localhost", "root", "", "giit");
if(!$this->con)
{
echo 'Database Connection Error ' . mysqli_connect_error($this->con);
}
}
public function insert($table_name, $data)
{
$string = "INSERT INTO ".$table_name." (";
$string .= implode(",", array_keys($data)) . ') VALUES (';
$string .= "'" . implode("','", array_values($data)) . "')";
if(mysqli_query($this->con, $string))
{
return true;
}
else
{
echo mysqli_error($this->con);
}
}
public function selectmulti($selecttype,$table_name)
{
$array = array();
$query = "SELECT ".$selecttype." FROM ".$table_name."";
$result = mysqli_query($this->con, $query);
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
return $array;
}
public function selectsingle($selecttype,$table_name)
{
$query = "SELECT ".$selecttype." FROM ".$table_name."";
$result = mysqli_query($this->con, $query);
$row = mysqli_fetch_assoc($result);
return $row;
}
}
?>
<?php
$data = new Databases;
$post_data = $data->selectmulti('*','centerdetail');
$n = 1;
foreach($post_data as $post)
{
echo $n.'.'.$post['CenterCode'].'___';
$n += 1;
}
echo '<br>';
$post_data = $data->selectsingle('*','centerdetail');
echo $post_data['CenterCode'];
?>

Related

PHP MySQL Only Printing Last Row in Query

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;
}

OOP PHP Database results to Array

I am new to the idea of oop php and i am trying to write an irc php.
What I'm trying to do:
I am trying to query my database, get results from my database and put it into an array inside my program.
I tried making a new function to carry out the task and called it in the __construct function.
I have shortened the code but it pretty much looks like this:
Any thoughts and ideas are much appreciated.
class IRCBot
{
public $array = array();
public $servername = "localhost";
public $username = "root";
public $password = "usbw";
public $dbname = "bot";
function __construct()
{
//create new instance of mysql connection
$conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$this->database_fetch();
}
function database_fetch()
{
$query = "SELECT word FROM timeoutwords";
$result = mysqli_query($query);
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row();
}
}
function main()
{
print_r($array);
}
}
$bot = new IRCBot();
Changes
1) Change if ($mysqli->connect_errno) to if ($conn->connect_errno)
2) Change $array[] = $row(); to $array[] = $row;
3) Add return $array; in function database_fetch()
4) Call database_fetch() function inside main() function instead of constructor.
5) Add $this->conn in mysqli_query() (Thanks #devpro for pointing out.)
Updated Code
<?php
class IRCBot
{
public $array = array();
public $servername = "localhost";
public $username = "root";
public $password = "usbw";
public $dbname = "bot";
public $conn;
function __construct()
{
//create new instance of mysql connection
$this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_errno)
{
echo "Failed to connect to MySQL: (" . $this->conn->connect_errno . ") " . $this->conn->connect_error;
}
}
function database_fetch()
{
$query = "SELECT word FROM timeoutwords";
$result = mysqli_query($this->conn,$query);
while($row = mysqli_fetch_assoc($result)){
$array[] = $row;
}
return $array;
}
function main()
{
$data = $this->database_fetch();
print_r($data);
}
}
Quick Start
Object Oriented Programming in PHP
Classes and Objects
Principles Of Object Oriented Programming in PHP
First of all you need to fix error from your constructor, you can modify as:
function __construct()
{
//create new instance of mysql connection
$this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_errno)
{
echo "Failed to connect to MySQL: (" . $this->conn->connect_errno . ") " . $this->conn->connect_error;
}
echo $this->conn->host_info . "\n";
}
Here, you need to replace $mysqli with $conn because your link identifier is $conn not $mysqli
No need to call database_fetch() here.
You need to use $conn as a property.
Now you need to modify database_fetch() method as:
function database_fetch()
{
$query = "SELECT word FROM timeoutwords";
$result = mysqli_query($this->conn,$query);
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
return $array;
}
Here, you need to pass add first param in mysqli_query() which should be link identifier / database connection.
Second, you need to use return for getting result from this function.
In last, you need to modify your main() method as:
function main()
{
$data = $this->database_fetch();
print_r($data);
}
Here, you need to call database_fetch() method here and than print the data where you need.

PDO query class

I'm tinkering with a class that 'should' allow me to easily execute a fetchall query and display the results within a foreach statement. I assume all is working correctly as I have no errors. As for the foreach - this must be the problem? How would I foreach the results gained from the $connect->query()? I'm new to using any database OOP framework in my functions so I could be along the wrong lines completely.
<?
error_reporting(1);
class dbconnect {
private $host;
private $database;
private $username;
private $password;
private $pdo;
private $error;
public function __construct() {
$this->host = "localhost"; // Host
$this->database = "images"; // Database Name
$this->username = "*"; // Username
$this->password = "*"; // Password
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
);
try {
$this->pdo = new PDO("mysql:host={$this->host};dbname={$this->dbname};charset=utf8", $this->username, $this->password, $options);
}
catch(PDOException $e) {
$this->error = $e->getMessage();
}
}
public function query($query) {
try {
$stmt = $this->pdo->prepare($query);
$stmt->execute();
} catch(PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
return $rows;
}
}
$connect = new dbconnect;
$rows = $connect->query("select * from photos");
foreach($rows as $row):
print $row['id'];
endforeach;
?>
The $rows variable you're declaring inside query is not accessible to the outside, it is local to that function. Most likely, you simply want to return those results to the caller:
$rows = $stmt->fetchAll();
return $rows; // return value from function...
and have the caller capture that return value in its own variable:
$rows = $connect->query("select * from images"); // ... is received by caller
foreach($rows as $row):
Also check out dougjore's answer, you're mixing $this->stmt and $stmt inside your query method.
Pretty sure you aren't ever actually executing the query:
$this->stmt = $this->pdo->prepare($query);
$stmt->execute();
I believe (I could be wrong, I'm rather new to PDO myself and I haven't built a class for it), that you need to say $this->stmt->execute();
You could do
//PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set
$this->stmt = $this->pdo->prepare($query);
$this->stmt->execute();
while ($result = $this->stmt->fetch(PDO::FETCH_ASSOC))
{
//do something with the result
}
Have a look here for more options to fetch PDO query results:
http://php.net/manual/en/pdostatement.fetch.php
$connect = new dbconnect;
$sql="select * from photos";
$stmt=$connect->pdo->prepare($sql);
$stmt->execute();
$result=$stmt->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
echo $key . "-" . $value . "<br/>";
}

MySQLi database connection

I have this (from someone else derived from my first attempt at a database class):
require_once( "declarations.php" );
class Database{
private static $mysqli;
private static $dbName = '';
private static $username = '';
private static $password = '';
private static $host = 'localhost';
private static $prefix = '';
public function __construct(){
if( self::$host & self::$username & self::$password & self::$dbName )
{
self::$mysqli = new mysqli( self::$host, self::$username, self::$password, self::$dbName );
if (self::$mysqli->connect_error) {
die('Connect Error (' . self::$mysqli->connect_errno . ') '
. self::$mysqli->connect_error);
}
}
else
{
echo "You forgot to fill in your database connection details";
}
}
public function Query( $query ){
$query = self::$mysqli->real_escape_string( $query );
if ($query = self::$mysqli->prepare($query)) {
$query->execute();
$query->store_result();
$stmt = $query->result;
//$query->mysql_num_rows = $stmt->num_rows();
$query->close();
return $stmt;
}
}
public function Close()
{
self::$mysqli->close();
}
}
This is how i'm calling it:
include_once( "system/database.php" );
$query = "SELECT * FROM app";
$dbr = new Database();
//Change this here since your method is query and not $mysqli
while( $row = $dbr->Query( $query )->fetch_object() ){
echo '<td>'. $row['id'] . '</td>' ;
echo '<td>'. $row['title'] . '</td>' ;
}
Database::Close();
I am getting an error Call to a member function fetch_object() on a non-object in on the while loop.
Any ideas?
fetch_object works with result set returned after query is executed with methods like: mysql_query or use fetch_assoc instead with
$query->execute();
$result = $query->get_result();
while ($myrow = $result->fetch_assoc()) {
//Your logic
}
Well, your first attempt resulted with totally unusable code.
There are 2 critical faults and one serious one.
As I told you already, doing $query = self::$mysqli->real_escape_string( $query ); is useless and harmful at once. You have to get rid of this line. Completely and forever.
Preparing a query without binding variables is totally useless.
You have to check for mysql errors.
So, at the very least your query() function have to be
public function query($query)
{
$res = self::$mysqli->query($query);
if (!$res)
{
throw new Exception(self::$mysqli->error);
}
return $res;
}
But again - this function is not safe as it's not not implementing placeholders to substitute data in the query.

Issues using PHP MySQL Built-In Functions inside a class

I am working with a MySQL Database and having some issues while trying to get data from several built-in PHP MySQL methods. I have written a class to interact with the database, and here are the relevant bits:
<?php
include("includes/Config.inc.php");
include_once("ChromePHP.class.php");
class Database{
private $db;
private $hostname;
private $username;
private $password;
private $schema;
function __construct() {
if(func_num_args() == 0){
$this->hostname = conf_hostname;
$this->username = conf_username;
$this->password = conf_password;
$this->schema = conf_schema;
}
else{
$params = func_get_args();
$this->hostname = $params[0];
$this->username = $params[1];
$this->password = $params[2];
$this->schema = $params[3];
}
$this->open();
}
private function open(){
$this->db = mysql_connect($this->hostname, $this->username, $this->password) or die ('Error connecting to mysql');
mysql_select_db($this->schema, $this->db);
mysql_query("SET NAMES utf8");
}
public function executeQuery($query){
$results = mysql_query($query, $this->db) or die ("Error in query: $query. ".mysql_error());
return $results;
}
public function executeNonQuery($query){
mysql_query($query, $this->db) or die ("Error in query: $query. ".mysql_error());
$info = mysql_info($this->db);
if($info){
$bits = explode(' ', $info);
return $bits[4];
}
return false;
}
public function close(){
mysql_close($this->db);
}
public function escape($string){
$output = mysql_real_escape_string($string , $this->db);
return $output;
}
public function getRegionTree(){
$query = "SELECT COUNT(parent.Name) - 2 as level, node.Name AS Name, node.ID, node.Parent
FROM Region AS node, Region AS parent
WHERE node.LeftVal BETWEEN parent.LeftVal AND parent.RightVal and node.Name <> 'Earth'
GROUP BY node.ID
ORDER BY node.LeftVal";
$result = $this->executeQuery($query);
$last_level = 0;
$output = '<ul id="regionTree">'.PHP_EOL;
while ($row = mysql_fetch_assoc($result)) {
$link = '<li>'.PHP_EOL.''.$row["Name"]."".PHP_EOL;
$diff = $last_level - $row["level"];
if($diff == 0){
// Sibling
$output .= ($row["level"] != 0) ? '</li>'.PHP_EOL.$link:$link;
}
elseif($diff < 0){
// Child
$demoter = '<ul>'.PHP_EOL;
for ($i=0; $i > $diff; $i--) {
$output .= $demoter;
}
$output .= $link;
}
else{
// Parent
$promoter = '</li>'.PHP_EOL.'</ul>';
for ($i=0; $i < $diff; $i++) {
$output .= ($row["level"] != 0) ? $promoter.PHP_EOL."</li>":$promoter;
}
$output .= $link;
}
$last_level = $row["level"];
}
$output .= "</li></ul>";
return $output;
}
public function addRegion($name, $type, $parentID){
$query = "select Name, Region_Type from Region where ID = ".$parentID;
$result = $this->executeQuery($query);
if($result){
$row = mysql_fetch_assoc($result);
$query = "call AddRegion('".$name."', '".$type."', '".$row["Name"]."', '".$row["Region_Type"]."', #returnCode, #returnMessage)";
$result = $this->executeQuery($query);
if($result){
return true;
}
else{
$query = "select #returnCode as code, #returnMessage as message";
$result = $this->executeQuery($query);
while($row = mysql_fetch_assoc($result)){
print_r($row);
}
return false;
}
}
return false;
}
public function getInfo(){
return mysql_info();
}
public function editRegion($id, $name, $type){
$query = "update Region set Name = '$name', Region_Type = '$type' where ID = $id";
if($this->executeNonQuery($query) > 0){
return true;
}
return false;
}
}
$db = new Database();
?>
With this Database class I am able to successfully make queries, get region trees, and successfully change data in the database using the ExecuteNonQuery function. However, any attempts I have made to use mysql_info, mysql_affected_rows, or other similar functions fails, making it really difficult to write any error handling code. To make matters stranger yet, if I run the following code:
<?php
$db = mysql_connect("localhost", "User", "Password") or die ('Error connecting to mysql');
mysql_select_db("DB", $db);
mysql_query("update Region set Name = 'test' where ID = 594", $db);
echo mysql_info($db);
?>
I am able to get results as expected. Any Ideas?
Are you using mysql_info and mysql_error outside the Database class? And if so how are you referencing the database connection? If you don't identify the database connection then:
The MySQL connection. If the link identifier is not specified, the last
link opened by mysql_connect() is assumed. If no such link is found,
it will try to create one as if mysql_connect() was called with no
arguments. If no connection is found or established, an E_WARNING
level error is generated.
So internally you should be doing mysql_info($this->db); to get mysql_info. Accessing $db externally requires you to write something to get around it being private.
But if you are going to be doing database stuff in an object-oriented mode you really should investigate PDO.
After adding "or die()" statements in several places in my script, I was surprised to see that nothing was actually failing to work, instead it was failing to work the way I expected it to. The problem I was having as it turns out, was that splitting the output of mysql_info (on the space character) resulted in several indices in the array containing nothing, as would be generated by inconsistent whitespace in the output of mysql_info. The index that I thought (based upon counting spaces visually) would contain an integer instead contained a string, and I was attempting to compare that string against the number 0, which won't work. I have updated my executeNonQuery function as follows:
public function executeNonQuery($query){
mysql_query($query, $this->db) or die ("Error in query: $query. ".mysql_error());
$info = mysql_info($this->db);
if($info){
$output = array();
$bits = explode(' ', $info);
$output["rowsMatched"] = $bits[2];
$output["rowsChanged"] = $bits[5];
$output["warnings"] = $bits[8];
return $output;
}
return false;
}

Categories