php pdo oop fetch data not working - php

Class PHP
<?php
class product extends db {
function viewCat(){
$dbcon = new db();
$connn = $dbcon->dbcon();
try {
$stmt = $connn->prepare("SELECT * FROM `cat`");
$resultcat = $stmt->execute();
return $resultcat;
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
}
}
?>
the view
<?php
$menu = new product();
$resultmenux = $menu->viewCat();
foreach ($resultcatx as $row) {
print_r($row);
}
?>
the error i get is
Warning: Invalid argument supplied for foreach()

in your class file it should be, as I commented you are not fetching the data
$stmt = $connn->prepare("SELECT * FROM `cat`");
$stmt->execute();
$resultcat = $stml->fetchAll(PDO::FETCH_ASSOC); // this line was missing
return $resultcat;
and in view file as answered by shankhan
$resultmenux = $menu->viewCat();
foreach ($resultmenux as $row) {
print_r($row);
}

It should be like this:
$resultmenux = $menu->viewCat();
foreach ($resultmenux as $row) {
print_r($row);
}

Related

how to display multiple rows from mysql using php oop?

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;

foreach is not working in php with pdo

I am using PDO with my PHP project and I don't know why this is not working. It is not showing any error.
I have a function to read data from a database:
function Read_post($con,$table,$limit=6){
try {
$query = "SELECT * FROM {$table} ORDER BY id DESC LIMIT {$limit}";
$stmt = $con->prepare( $query );
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
return "ERROR". $e->getMessage();
}
}
and I use a foreach loop to display the data. But it is not showing anything:
<?php $posts = Read_post($con,"posts"); ?>
<?php foreach ($posts as $key) {
echo "something ";
echo $key["title"];
} ?>
It is not showing the other text as well like if i echo something else only text.
Inside your function Read_post, you have this line:
return $stmt->fetch(PDO::FETCH_ASSOC);
It will not return an array, it will return a PDO object. You can't iterate over a PDO object in the same way as an array. Try this:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result;
echo the $value of the array in foreach or var_dump($post) to check the array contains
something
<?php foreach ($posts as $value) {
echo "something ";
echo $value;
} ?>

Query return and empty array

The following script:
<?php
try
{
$db = new PDO("sqlite:./path/phrases");
$result = $db->query('SELECT * FROM phrases');
foreach($result as $row){
$row['phrase'];
$row['score'];
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
is returning:
Warning: Invalid argument supplied for foreach() in myscript.php on line 5
If I execute: Select * from phrases; in a SQL browser, I get back a long list of results, with regard to the columns phrase and score. What am I doing wrong?
There are 2 examples in this answer.
The first example I found at http://juanmanuelllona.blogspot.ca/
Am providing what I hope will be a solution.
1)
try {
$db = new PDO("sqlite:./path/phrases");
echo 'database open';
$sql = "SELECT * FROM phrases";
$obj= $db->query($sql) ;
foreach ($obj as $row)
{
print('Phrase ='.$row['phrase'].' Course='.$row['score']. '&ltbr/>'); // or <br/>
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
2)
And this suggestion taken from an example at http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=phrases", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM phrases";
foreach ($dbh->query($sql) as $row)
{
print $row['phrase'] .' - '. $row['score'] . '<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
You need to use echo statement:
$result = $db->query('SELECT * FROM phrases');
foreach($result as $row){
echo $row['phrase'];
echo $row['score'];
}
try
{
$db = new PDO("sqlite:./path/phrases");
$result = $db->query('SELECT * FROM phrases;'); // remove the Semicolon
foreach($result as $row){
$row['phrase'];
$row['score'];
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
try removing the Semicolon inside the statement.

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.

Create one instance of an array whilst in a foreach loop

I have myself in a unique situation here and I am not sure if this is the correct way to go about it; I am open to suggestions.
I have a function in which it grabs all of the table names in a database and stores them into an array. Next newly parsed items ($id) are passed against this table name array and any matches are unset from this array. This leaves me with the leftovers which are items that have been discontinued.
Code below:
function itemDiscontinued($dbh, $id, $detail) {
try {
$tableList = array();
$result = $dbh->query("SHOW TABLES");
while ($row = $result->fetch()) {
$tableList[] = $row[0];
}
$key = array_search($id, $tableList);
unset($tableList[$key]);
print_r($tableList);
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
The problem is that the array $tablelist keeps recreating itself due to the function being in a foreach loop (Parsing process). I only require one instance of it to work with once it is created. I apologise before hand if the problem is a bit hard to understand.
Yea, it's really hard to understand. Maybe you'll try this:
function itemDiscontinued($dbh, $id, $detail) {
static $tables = array();
if (!$tables) {
$tables = getTableList($dbh);
}
$key = array_search($id, $tables);
unset($tables[$key]);
print_r($tables);
}
function getTableList($dbh) {
try {
$tableList = array();
$result = $dbh->query("SHOW TABLES");
while ($row = $result->fetch()) {
$tableList[] = $row[0];
}
return $tableList;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
how about an array_push with an extra parameter
function itemDiscontinued($dbh, $id, $detail, $outputArray) {
try {
$result = $dbh->query("SHOW TABLES");
while ($row = $result->fetch()) {
array_push($outputArray, $row[0]);
}
$key = array_search($id, $outputArray);
unset($outputArray[$key]);
return $outputArray; // use this for subsequent run on the foreach statment
}
catch (PDOException $e) {
echo $e->getMessage();
}
}

Categories