Add query results to arrary PDO - php

I am trying to add query results to an array. My while statement works but I am not getting anything in my array. Here is my code:
$res=$pdo->query("select * from questions where category_id='$category' ORDER BY RAND()");
$rows = $res->rowCount();
if ($rows < 1){
echo "There is no question in the database";
exit();}
$questionsArray = array();
while ($item = $res->fetch(PDO::FETCH_ASSOC)){
$questionsArray[] = $item;
echo "There should be some info here<br>";
}

You might want to consider something like this, with thru PDO prepared statements.
Also, a while loop with a fetch is bad and slow and was good 15 years ago with MySQL.
Here is the proper way to do it.
define("SQLHOST", "127.0.0.1");
define("SQLUSER", "user");
define("SQLPASS", "password");
define("SQLSGBD", "database");
try {
$con = new PDO('mysql:host=' . SQLHOST . ';dbname=' . SQLSGBD . ';charset=UTF8', SQLUSER, SQLPASS);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
var_dump('Connection failed: ' . $e->getMessage());
}
$categories = ['A', 'B', 'C'];
$questionsArray = array();
$stmt = $con->prepare("select * from questions where category_id=? ORDER BY RAND()");
foreach ($categories as $key => $cat) {
$stmt->bindParam(1, $cat, PDO::PARAM_STR);
$stmt->execute();
$obj = $stmt->fetchall(PDO::FETCH_ASSOC);
if (count($obj) !== 0) {
foreach ($obj as $key2 => $item) {
$questionsArray[] = [$cat => $item];
}
}
}

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

Php pdo foreach

Here I have php pdo function to get json from database
try {
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->prepare("SELECT id_tabele,naziv FROM track_aktivnosti WHERE prvi=:prvi AND id_akt=:id_akt AND tabela=:tabela");
$result->execute(array(':prvi' => $_POST['prvi'], ':id_akt' => $_POST['id_akt'], ':tabela' => $_POST['tabela']));
$result = $result->fetchAll();
foreach($result as $r) {
$temp = array();
$temp[] = array('id' => (int) $r['id_tabele'], 'ime_prezime' => (string) $r['naziv']);
}
$table = $temp;
$jsonTable = json_encode($table);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo $jsonTable;
but I get just one result, one element in json etc.
[{"id":1,"ime_prezime":"Pera Peric"}]
other element I can't get. WHY?
I must get json like this:
[{"id":1,"ime_prezime":"Pera Peric"},[{"id":2,"ime_prezime":"Laza Lazic"}] ]
but I get only 1.st element and other not ...
You are overwriting the array inside the foreach on each iteration. This essentially means that the array is emptied on each iteration. The array will only contain the values from the last iteration. Move the $temp = array(); declaration outside the loop to fix this:
$temp = array(); // intialize the array
foreach($result as $r) {
$temp[] = array(
'id' => (int) $r['id_tabele'],
'ime_prezime' => (string) $r['naziv']
);
}
The above fix will make your code work, but I recommend using the approach using SQL aliases as shown in #YourCommonSense's answer below.
You are doing a whole lot of useless operations. It's no wonder why you got lost.
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$sql = "SELECT id_tabele id, naziv ime_prezime FROM track_aktivnosti
WHERE prvi=? AND id_akt=? AND tabela=?";
$stmt = $conn->prepare($sql);
$stmt->execute(array($_POST['prvi'], $_POST['id_akt'], $_POST['tabela']));
echo json_encode($result->fetchAll());
declare
$temp = array();
out side the loop since you have this inside the loop and on each iteration its declared as new array and previous entries are wiped.
i.e.
$temp = array();
foreach($result as $r) {
$temp[] = array('id' => (int) $r['id_tabele'], 'ime_prezime' => (string) $r['naziv']);
}

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.

PHP-PDO fetch data using loop structure

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

php: convert pdo content to mysqli

I am using a nice piece of code to reorder db content using drag and drop. I can get it to work locally by enabling the PDO extension in the php.ini file but my hosting package (shared) does not allow PDO and MySQLi simultaneously. I am unfamiliar with PDO and I would appreciate any help in rewriting the following segment to work with MySQLi, if possible.
Thanks.
<?php
if (isset($_POST['orders'])) {
} else {
echo json_encode(array('error' => true));
}
$orders = explode('&', $_POST['orders']);
$array = array();
foreach($orders as $item) {
$item = explode('=', $item);
$item = explode('_', $item[1]);
$array[] = $item[1];
}
try {
$objDb = new PDO('mysql:host=localhost;dbname=test', 'user', 'pw');
$objDb->exec("SET CHARACTER SET utf8");
foreach($array as $key => $value) {
$key = $key + 1;
$sql = "UPDATE `artwork`
SET `listorder` = ?
WHERE `id` = ?";
echo $sql;
$objDb->prepare($sql)->execute(array($key, $value));
}
echo json_encode(array('error' => false));
} catch(Exception $e) {
echo json_encode(array('error' => true));
}
My recommendation? Find another host. Going from PDO to mysqli is not a good idea, because you will waste time porting code into a less portable state.
-- Edit --
You can try the following code snippet, if it doesn't work it should get you started. I couldn't test it because none of my servers have mysql* modules compiled.
$dbo = new mysqli('localhost', 'user', 'password', 'database');
if (mysqli_connect_error()) {
echo sprintf('Unable to connect: ErrNo: (%d), ErrMsg: (%s)', mysqli_connect_errno, mysqli_connect_error());
exit;
}
foreach ($array as $key => $value) {
$key = $key + 1;
$sql = "UPDATE `artwork` SET `listorder` = " . (int) $key . " WHERE `id` = " . (int) $value;
$dbo->query($sql);
}
$dbo->close();
You can get more information on mysqli query and other functions here.
Anyway, good luck.

Categories