how to display multiple rows from mysql using php oop? - php

I'm a newbie in oop style. I start practicing it since last week and I make simple CRUD website. but i got a problem when i tried fetching rows from mysql db its always display 1 row.
my created a class named class.user.php
and it shows here:
include "db_config.php";
class User{
private $db;
public function __construct(){
$this->connect();
}
private function connect($db_connect=true){
if ($db_connect){
$this->db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
printf("DB Connect failed: %s\n", mysqli_connect_error());
exit;
}
}
}
public function get_tutoriallist(){
$db = $this->db;
if(empty($db)){
$this->connect();
$db = $this->db;
}
try {
$stmt = $this->db->prepare('SELECT * FROM `topic`');
$stmt->execute();
$result = $stmt->get_result();
$dataArray = array();
while($row = $result->fetch_assoc()){
$count_row = $result->num_rows;
if ($count_row == 1) {
$dataArray[] = $row;
}
}
return ($dataArray);
mysqli_close($db);
$this->db = null;
} catch (Exception $e) {
echo $e->errorMessage();
}
}
}
and i call it using this:
$data = $user->get_tutoriallist();
if (!empty($data)) {
foreach ($data as $row){
echo "<tr>";
echo"<td>".$row['category']."</td>";
echo"<td>".$row['title']."</td>";
echo"<td>".$row['detail']."</td>";
echo"<td>".$row['photo']."</td>";
echo"<td>".$row['video_link']."</td>";
echo"<td>".$row['date_post']."</td>";
echo"<td class='option'><center><a href ='#' class='edit'>Edit</a>
<a href='#'>Delete</a></center></td>";
echo "</tr>";
}
}else{
echo '<tr><td colspan="6"><center><h2>No entries</h2></center></td></tr>';
}

I'm not quite sure what is going on here:
while($row = $result->fetch_assoc()){
$count_row = $result->num_rows;
if ($count_row == 1) {
$dataArray[] = $row;
}
But normally, you just iterate through the results and append them to an array:
while($row = $result->fetch_assoc()){
$dataArray[] = $row;
}
Then your $datArray has all the rows in it.

This is because you are appending to the result array only when $current_row == 1.
Try changing your while loop like this:
while($row = $result->fetch_assoc()){
$dataArray[] = $row;
}
Also, you are not closing the db connection correctly, you are mixing OOP style with procedural mysqli functions. This is how it should be:
$this->db->close();
$this->db = null;
Finally, you should return the data array after you closed the connection. If you returned the data array first and closed the connection after, that code wont get executed.
So your last three lines should look like this:
$this->db->close();
$this->db = null;
return $dataArray;

Related

How can I print a rows mysql array in a table in php? [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
I'm a class execute statement mysql and I don't know how to print a return array variable
class Db {
// The database connection
protected static $connection;
public function connect() {
// Try and connect to the database
if(!isset(self::$connection)) {
self::$connection = new mysqli('localhost','root','123456','dbGanaderia');
}
// If connection was not successful, handle the error
if(self::$connection === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return false;
}
return self::$connection;
}
public function query($query) {
// Connect to the database
$connection = $this -> connect();
// Query the database
$result = $connection -> query($query);
return $result;
}
public function select($query) {
$rows = array();
$result = $this -> query($query);
if($result === false) {
return false;
}
while ($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
}
This when i call the method to execute select statement the rows return an array, but i don't kno how to print... If i do this printr($rows) I verefy that the statement its returning from database
$db = new Db();
$rows = $db -> select("SELECT *FROM user");
if ($rows == true) {
echo "<table border = '1'> \n";
echo "<tr><td>name</td></tr> \n";
while($row = mysql_fetch_array($rows)) {
echo "<tr><td>".$row['1']."</td></tr> \n";
}
echo "</table> \n";
} else {
echo "ยก No data !";
}
Where am I wrong?
You are mixing mysql_ functions with mysqli_ functions
Change your fetch to
$r = mysqli_fetch_array()

PHP - Getting: Commands out of sync; you can't run this command now

I know that there were hundreds of similar questions, I have tried everything and nothing really worked for me.
I have got this function that is calling stored procedure in my MariaDB. This is returning array.
<?
class MyClass {
protected static $connection;
public function connect() {
// Try and connect to the database
if(!isset(self::$connection)) {
self::$connection = new mysqli(SERVERNAME,USERNAME,PASS,DBNAME);
}
// If connection was not successful, handle the error
if(self::$connection === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return false;
}
return self::$connection;
}
public function query($query) {
// Connect to the database
$connection = $this -> connect();
// Query the database
$result = $connection -> query($query);
return $result;
}
public function quote($value) {
$connection = $this -> connect();
return $connection -> real_escape_string($value);
}
public function CallStoredProc($query) {
// Connect to the database
$connection = $this -> connect();
// Query the database
$result = $connection -> query($query,MYSQLI_USE_RESULT); //,
if($result === false) {
return false;
}
while ($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
$result->free();
return $rows;
}
function StoreProcessed($Name,$Price){
//escape
$Name = $this->quote($Name);
$Price= $this->quote($Price);
$SQL = "INSERT INTO Result (`Name`,`Price`) VALUES ('$Name','$Price');";
$result = $this->query($SQL);
}
//the function I am using for processing:
function Compare($ID) {
$query = "CALL MyProcedure($ID);";
$result =$this->CallStoredProc($query);
/*After the array is returned I am looping trough each element of array
and storing this in DB with another function. */
$Table = "<table>";
foreach ($result as $key=>$val)
{
$Name = $result[$key]["Name"];
$Price = $result[$key]["Price"];
$this->StoreProcessed($Name,$Price);
//This is where the Commands out of sync is returned
$Table = $Table. "<tr>
<td>$Name</td>
<td>$Price</td>
</tr>";
}
$Table = $Table. "</table>";
return $Table;
}
}
My php file then looks like this:
<?
$auto = new MyClass();
$table = $auto->Compare(14);
echo $table;
?>
I am using MYSQLI_USE_RESULT, after the array is filled, I am using the mysqli_free_result as well. What else should I do?
Many thanks!
I've found answer here . Just added this function:
function free_all_results(mysqli $dbCon)
{
do {
if ($res = $dbCon->store_result()) {
$res->fetch_all(MYSQLI_ASSOC);
$res->free();
}
} while ($dbCon->more_results() && $dbCon->next_result());
}
And I called it before returning the results:
public function CallStoredProc($query) {
// Connect to the database
$connection = $this -> connect();
// Query the database
$result = $connection -> query($query); //,
mysqli_store_result($connection);
if($result === false) {
return false;
}
while ($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
$this->free_all_results($connection);
return $rows;
}

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

Convert SQL results into PHP array

I'm fairly new to PHP and I've been looking around and can't seem to find the specific answer I'm looking for.
I want to make a SQL query, such as this:
$result = mysqli_query($connection, $command)
if (!$result) { die("Query Failed."); }
// Create my array here ... I'm thinking of maybe having to
// make a class that can hold everything I need, but I dunno
while($row = mysqli_fetch_array($result))
{
// Put the row into an array or class here...
}
mysqli_close($connection);
// return my array or class
Basically I want to take the entire contents of the result and create an array that I can access in a similar fashion as the row. For example, if I have a field called 'uid' I want to be able to get that via myData['uid']. I guess since there could be several rows, maybe something more like myData[0]['uid'], myData[1]['uid'], etc.
Any help would be appreciated.
You can do:
$rows = [];
while($row = mysqli_fetch_array($result))
{
$rows[] = $row;
}
You might try to use mysqli_result::fetch_all() for arrays:
$result = mysqli_query($connection, $command)
if (!$result) { die("Query Failed."); }
$array = $result->fetch_all();
$result->free();
mysqli_close($connection);
NOTE: This works with MySQLND only.
For class, you might try to use something like this:
$result = mysqli_query($connection, $command)
if (!$result) { die("Query Failed."); }
while($model = $result->fetch_assoc()){
// Assuming ModelClass is declared
// And have method push() to append rows.
ModelClass::push($model);
}
$result->free();
mysqli_close($connection);
OR this:
// Base Model - abstract model class.
class ModelClass extends BaseModel {
// constructor
public function __construct(mysqli &$dbms){
// $this->dbms is MySQLi connection instance.
$this->dbms = &$dbms;
// $this->models is buffer for resultset.
$this->models = array();
}
// destructor
public function __destruct(){
unset($this->dbms, $this->models);
}
public function read(){
$result = $this->dbms->query($command);
if($this->dbms->errno){
throw new Exception($this->dbms->error, $this->dbms->errno);
}
$this->models = $result->fetch_all();
$result->free();
}
}
//object oriented style mysqli
//connect to your db
$mysqli = new mysqli("host", "user", "password", "dbname");
$result = $mysqli->query("SELECT * FROM `table`");
//use mysqli->affected_rows
for ($x = 1; $x <= $mysqli->affected_rows; $x++) {
$rows[] = $result->fetch_assoc();
}
//this will return a nested array
echo "<pre>";
print_r($rows);
echo "</pre>";
edit this and put it on a class and just call it anytime you're going to make a query with your database.
fetch_array: https://www.php.net/manual/en/mysqli-result.fetch-array.php
$result = $mysqli_connection->query($sql);
$row = $result->fetch_array(MYSQLI_ASSOC);
print_r($row);

Run a call from a function PHP

i'm building an website using php and html, im used to receiving data from a database, aka Dynamic Website, i've build an CMS for my own use.
Im trying to "simplify" the receiving process using php and functions.
My Functions.php looks like this:
function get_db($row){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$row = $stmt->fetchAll();
foreach ($row as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Where i will get the rows content like this: $row['row'];
I'm trying to call it like this:
the snippet below is from the index.php
echo get_db($row['session_id']); // Line 22
just to show whats in all the rows.
When i run that code snippet i get the error:
Notice: Undefined variable: row in C:\wamp\www\Wordpress ish\index.php
on line 22
I'm also using PDO just so you would know :)
Any help is much appreciated!
Regards
Stian
EDIT: Updated functions.php
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Instead of echoing the values from the DB, the function should return them as a string.
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = '';
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result .= $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then call it as:
echo get_db();
Another option would be for the function to return the session IDs as an array:
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = array();
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result[] = $row['session_id'];
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then you would use it as:
$sessions = get_db(); // $sessions is an array
and the caller can then make use of the values in the array, perhaps using them as the key in some other calls instead of just printing them.
As antoox said, but a complete changeset; change row to rows in two places:
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
Putting this at the start of the script after <?php line will output interesting warnings:
error_reporting(E_ALL|E_NOTICE);
To output only one row, suppose the database table has a field named id and you want to fetch row with id=1234:
$stmt = $pdo->prepare("SELECT * FROM lp_sessions WHERE id=?");
$stmt->bindValue(1, "1234", PDO::PARAM_STR);
I chose PDO::PARAM_STR because it will work with both strings and integers.

Categories