PHP-PDO fetch data using loop structure - php

I am practicing using PDO fetch methods to retrieve data from the table. I would like to a counter in a while loop to retrieve data one row at a time. Please give me some advise how to accomplish this. Thanks!
Here are my 2 code samples using PDO::Query() and PDO::fetch() method.
code sample 1 using PDO::Query() Method
$sql = 'select first_name, last_name, pd, b_month, b_day, b_year from reg_data';
$birth_date = '';
try
{
foreach($con->query($sql) as $row)
{
print $row['first_name'] . " ";
print $row['last_name']. " ";
print $row['pd'] . " ";
$birth_date = $row['b_month'] . "-". $row['b_day'] . "-". $row['b_year'];
print "$birth_date";
}
}
catch(PDOException $e)
{
echo " There is a problem with you db connection";
echo $e->getMessage();
}
sample 2 using PDO::fetch() method
try {
$con = new PDO ($dns, $db_uid, $db_pd, $option);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "select * from reg_data";
$stmt = $con->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
//using cursor to interate through array
while($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
$data = $row[0].$row[1]. $row[2] .$row[3].$row[4].$row[5];
print $data;
}
$stmt = null; //close the handle
}
catch(PDOException $e)
{
echo " There is a problem with you db connection";
print $get->getMessage();
}

I think you need PDO::fetchAll.
A code example straight from the tag wiki:
//connect
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,'root','', $opt);
//retrieval
$stm = $pdo->prepare("select * from reg_data");
$stm->execute();
$data = $stm->fetchAll();
$cnt = count($data); //in case you need to count all rows
//output
?>
<table>
<? foreach ($data as $i => $row): ?>
<tr>
<td><?=$i+1?></td> <!-- in case you need a counter for each row -->
<td><?=htmlspecialchars($row['first_name'])?></td>
</tr>
<? endforeach ?>
</table>

You can use a variable and increment it in the loop
$counter++ ;

Related

Array won't print row data

I got this simple PHP code to print a Column from a database and it isn't working unfortually. Any ideas on what to do right?
I've tried to work on the while loop I have in the if statement but no luck
What im trying to get array to print like :
<?php
$input = $_POST['input'];
$servername = "localhost";
$username = "hawk_manager";
$password = "hawk_eyes";
try {
$pdo = new PDO("mysql:host=$servername;dbname=HawkCenter", $username, $password);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
if ($input == "RoomNumber") {
$query = 'SELECT RoomNumber FROM rooms';
$statement=$pdo->prepare($query);
$statement->execute();
$roomnumbers=$statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
while( $roomnumbers=$statement->fetchAll(PDO::FETCH_ASSOC)){
echo "{$statement['RoomNumber']}";
}
}
$conn = null;
?>
You are doing it wrong, it should be
1. Selecting multiple rows
$data = $pdo->query("SELECT RoomNumber FROM rooms")->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $row) {
echo $row['RoomNumber ']."<br />\n";
}
2. Prepared Statements::
$stmt = $pdo->prepare("SELECT RoomNumber FROM rooms WHERE id=?");
$stmt->execute([$id]);
$user = $stmt->fetch();
OR
$stmt = $pdo->prepare("$stmt = $pdo->prepare("SELECT RoomNumber FROM rooms LIMIT :limit, :offset");
$stmt->execute(['limit' => $limit, 'offset' => $offset]);
$data = $stmt->fetchAll();
foreach ($data as $row) {
echo $row['RoomNumber']."<br />\n";
}

pdo statement to return more than 1 column in php

I am trying to fetch values from a mysql query using PDO...it works with one column but I need to return 2 columns from the query. Below is the piece of code I have made...
try {
$conn = new PDO('mysql:host=localhost;dbname=****', 'root', '****'>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$sth = $conn->prepare("select distinct prod_url,ean from tab_nl where ean in (select ean1 from test_sku where sku='$sku') and prod_url like '%prijzen%'");
$sth->execute();
$urlsku = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
$urlean = $sth->fetchAll(PDO::FETCH_COLUMN, 1);
echo $sku;
echo $urlsku;
echo $urlean;
It returns me some array values...which I really can't figure out. Can anyone please help me with this.
If you use fetch() with the PDO::FETCH_ASSOC style it is easy to get both columns:
while($row = $sth->fetch(PDO::FETCH_ASSOC) {
echo $row['prod_url'];
echo $row['ean'];
}
By placing the fetch in a loop all of the rows will be returned which you can then limit as you see fit.
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
echo $data[0]['prod_url'];
echo $data[0]['ean'];
Add LIMIT 2 in the query , to get two sets of result :)
try {
$conn = new PDO('mysql:host=localhost;dbname=****', 'root', '****'>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$sth = $conn->prepare("select distinct prod_url,ean from tab_nl where ean in (select ean1 from test_sku where sku='$sku') and prod_url like '%prijzen%' LIMIT 2");
$sth->execute();
$urlsku = $sth->fetchAll(PDO::FETCH_ASSOC, 0);
$urlean = $sth->fetchAll(PDO::FETCH_ASSOC, 1);
print_r($urlsku);
print_r($urlean);

PDO Read From Database

I have made a code using PDO to read a table from a database.
I try to echo my result but I get a blank page without error.
My Code Is:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>
But the echo is empty without any error.
What I am doing wrong?
Thank you All!
Few things to change:
dont forget $
if your going to catch the error, catch the whole pdo code
You can use rowCount() to count the rows
echo something if the record count is 0
include 'config.php';
$id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->rowCount() != 0)
{
$row = $result->fetch(PDO::FETCH_BOTH);
echo $row['Data1'];
echo $row['Data2'];
}else{
echo 'no row found';
}
}catch(PDOException $e){
echo "error " . $e->getMessage();
}
Also use prepared statements for example:
$result = $conn->prepare("SELECT * FROM mytable WHERE id=:id");
$result->execute(array(':id'=>$id));
I'm assuming there's only one record with the id "264540733647332".
The issue is that $result->fetchColumn() call reads first row in the result set and then advances to the next result. Since there's only one of the results, the subsequent call to $result->fetchAll() returns nothing, hence no data displayed.
To fix this replace fetchColumn with rowCount:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>

How to count rows in a while loop using pdo fetch

I was using mysqli_fetch_array and the counting was right until I changed to fetch(), which now only returns the total number of rows instead of returning each number for each row.
So for row one, I want to echo "1", and so on.
NEW NOTE :Everything else inside the while statement is returning correct values, except the counter which returns the total number of rows whereas I want a row number in the order that it was selected from the sql statement.
As requested. This is my connection.
I don't know if i'm suppose to be checking " $e->getMessage();" on every query since I'm using this connection for all my queries.
try {
$dbh = new PDO('mysql:host=localhost;dbname=my_db;charset=utf8', 'usr', 'pwd',
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);
} catch (PDOException $e){
echo $e->getMessage();
}
This worked
$query = mysqli_query($con, 'SELECT * FROM music');
$count = 0;
while($row = mysqli_fetch_array($query)){
$count++;
echo $count;
}
The new doesn't work.
$query = $dbh->query('SELECT * FROM music');
$count = 0;
while($row = $query->fetch()){
$count++;
echo $count;
}
Works fine, use a try catch do see if your PDO connection is working.
try {
$dbh = new PDO('mysql:host=localhost;dbname=db', 'root', 'root',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$sql = 'SELECT * FROM music';
$sth = $dbh->query($sql);
$count = 0;
while($row = $sth->fetch()){
$count++;
echo $count;
}
I've just tested this and it works fine. Either your PDO connection is incorrect or your query returns no results. I suggest you var_dump($dbh) and see if it returns a PDO object or check that your query is correct. Is your table called music? It is case sensitive.
You also need to change your connection form mysqli to PDO
$mysqli = new mysqli("localhost", "user", "password", "database");
to
$dbh = new PDO('mysql:host=localhost;dbname=database', 'user', 'password');
You can also throw PDO exceptions to see if any are occuring:
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
$conn->exec("SET CHARACTER SET utf8");
http://coursesweb.net/php-mysql/pdo-select-query-fetch
What about:
if ($pdo){
$query=$pdo->prepare("SELECT count(*) as cnt FROM music");
if($query->execute()){
$count = $query->fetch()[0];//or fetch()['cnt']
echo $count;
}
}
PDO have a little different behavior. This is a replacement for your mysqli.
try {
$dbh = new PDO('mysql:host=localhost;dbname=database', 'user', 'password',array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// optional
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
));
$count = 0;
foreach ($dbh->query("SELECT * FROM `music`") as $row) {
$count++;
echo $count;
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
exit();
}
I hope that helped.
Try using PDO::FETCH_NUM to get the row count directly :-
$countquery = $dbh->query('SELECT COUNT(1) FROM music');
$rowCount = 0;
$rowCount = $countquery ->fetch(PDO::FETCH_NUM);
echo $rowCount;
//And then do another query for the real data if need be
* This makes use of a query to get the row count, and saves you the time taken by the while loop.

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