How would i retrieve the rows from Select Statement - php

I need to store the rows in an array but can't seem to get it to work, the code is below:
I am sure $result = $stmt->get_result(); does not work.
When i test in the browser output is empty.
<?php
include "connect.php";
$uid = $_REQUEST["U_ID"];
$stmt = $mysqli->prepare("SELECT * FROM U_User WHERE U_ID = ?");
$stmt->bind_param("d", $uid);
$stmt->execute();
$stmt->fetch();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc())
{
$users[] = $row;
}
$stmt->close();
$arr = array('user' => $users);
echo json_encode($arr);
mysqli_close($conn);
?>

Just like php_nub_qq said. I switched to PDO works great.
<?php
include "connect.php";
$uid = $_REQUEST["U_ID"];
$q = $conn->prepare("SELECT * FROM U_User WHERE U_ID = :uid");
$q->execute(array(':uid' => $uid));
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
$users[] = $r;
}
$q = $conn->prepare("SELECT * FROM P_Post u WHERE P_U_ID = :uid");
$q->execute(array(':uid' => $uid));
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
$posts[] = $r;
}
$q = $conn->prepare("SELECT * FROM T_Thread u WHERE T_U_ID = :uid");
$q->execute(array(':uid' => $uid));
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
$threads[] = $r;
}
$arr = array('user' => $users, 'post' => $posts, 'thread' => $threads);
echo json_encode($arr);
$conn = null;
?>

Related

PHP PDO fetch data from Array

This Code Works Perfectly For Mysqli
$sql = "SELECT * FROM 'mem_tree' ";
$res = mysqli_query($conn, $sql) or die("database error:".mysqli_error($conn));
while($row = mysqli_fetch_assoc($res)){
$data[] = $row;
}
$itemsByReference = array();
but When i'm trying to do with PDO it Doesn't Work
$sql = "SELECT * FROM 'mem_tree' ";
$stmt = $dbh->prepare($sql);
$stmt->execute();
while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)){
$data[] = $row;
}
$itemsByReference = array();
Here i found Solution of it
$sql = "SELECT * FROM mem_tree";
$stmt = $dbh->prepare($sql);
$stmt->execute();
$final_arr = array();
$data = array();
$final_arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
$data = $final_arr;
$itemsByReference = array();

Why is this piece of code giving me duplicate results?

This is probably really easy and I'm probably gonna kick myself up the arse after this, but I have the following code which displays either html or json of data from a table and returns it.
<?php
session_start();
$base = dirname(dirname(__FILE__));
include($base."/include/db.php");
global $conn;
$trees = [];
$treeBoxes = [];
if(isset($_SESSION['clientId'])) {
$clientId = $_SESSION['clientId'];
$query = $conn->prepare("SELECT * FROM ct_trees WHERE client_id=?");
$query->bind_param('i', $clientId);
$query->execute();
$result = $query->get_result();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tree_id = $row['id'];
$tree_name = $row['name'];
$query = $conn->prepare("SELECT id FROM ct_connections WHERE tree_id=?");
$query->bind_param('i', $tree_id);
$query->execute();
$result2 = $query->get_result();
$connections = $result2->num_rows;
array_push($treeBoxes, '<span class="checkbox abc-checkbox abc-checkbox-success">',
'<input id="tree'.$tree_id.'" type="checkbox" rel="'.$tree_id.'">',
'<label for="tree'.$tree_id.'">'.$tree_name.'</label>',
'</span>');
array_push($trees, ["id" => $tree_id, "name" => $tree_name, "connections" => $connections]);
if(isset($_GET['json'])) {
echo json_encode($trees);
} else {
echo join("", $treeBoxes);
}
}
}
}
?>
Now let's say for example, we want the json result, I'm getting the following string:
[{"id":1,"name":"My Tree","connections":4360}][{"id":1,"name":"My Tree","connections":4360},{"id":4,"name":"Another Tree","connections":0}]
Now for some reason, it's giving me the first result in one array, and then the same result, but with the other rows, in a separate array.
Fixed it, I knew it'd be silly:
<?php
session_start();
$base = dirname(dirname(__FILE__));
include($base."/include/db.php");
global $conn;
$trees = [];
$treeBoxes = [];
if(isset($_SESSION['clientId'])) {
$clientId = $_SESSION['clientId'];
$query = $conn->prepare("SELECT * FROM ct_trees WHERE client_id=?");
$query->bind_param('i', $clientId);
$query->execute();
$result = $query->get_result();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tree_id = $row['id'];
$tree_name = $row['name'];
$query = $conn->prepare("SELECT id FROM ct_connections WHERE tree_id=?");
$query->bind_param('i', $tree_id);
$query->execute();
$result2 = $query->get_result();
$connections = $result2->num_rows;
array_push($treeBoxes, '<span class="checkbox abc-checkbox abc-checkbox-success">',
'<input id="tree'.$tree_id.'" type="checkbox" rel="'.$tree_id.'">',
'<label for="tree'.$tree_id.'">'.$tree_name.'</label>',
'</span>');
array_push($trees, ["id" => $tree_id, "name" => $tree_name, "connections" => $connections]);
}
//Moved echo outside of while loop.
if(isset($_GET['json'])) {
echo json_encode($trees);
} else {
echo join("", $treeBoxes);
}
}
}
?>

How to Merge PDO Mysql Array Data using Php

I need to merge categories and subcategories into one array. Here is code.
$sql = 'select * from category where id = ?';
$q = $db->prepare($sql);
$q->bindParam(1, $id);
$q->execute();
while($rows = $q->fetch()){
$cat[] = $rows['id'];
$s = 'select * from category where category_id = ?';
$q = $db->prepare($s);
$q->bindParam(1, $rows['id']);
$q->execute();
while($row = $q->fetch()){
$list[] = $row['id'];
}
$data = array_push($cat, $list);
echo $data;
}
I am getting 2 value when printing instead ids numbers
are you want to merge $cat and $list?
you can try:
array_merge($cat, $list);
I solved this problem with the help of this post combine-results-from-two-pdo-queries
$id = '1';
$results = array();
$sql = 'select * from category where id = ?';
$q = $db->prepare($sql);
$q->bindParam(1, $id);
$q->execute();
while($rows = $q->fetch(PDO::FETCH_ASSOC)){
$results[] = $rows['id'];
}
$s = 'select * from category where category_id = ?';
$q = $db->prepare($s);
$q->bindParam(1, $id);
$q->execute();
while($row = $q->fetch(PDO::FETCH_ASSOC)){
$results[] = $row['id'];
}
var_dump($results);
I think what you want is this:
$sql = 'select * from category where id = ?';
$q = $db->prepare($sql);
$q->bindParam(1, $id);
$q->execute();
$data = array();
while($rows = $q->fetch()){
$cat[] = $rows['id'];
$s = 'select * from category where category_id = ?';
$q = $db->prepare($s);
$q->bindParam(1, $rows['id']);
$q->execute();
while($row = $q->fetch()){
$list[] = $row['id'];
}
$data = array_merge($data, $cat, $list);
//$data = array_unique($data);
print_r($data);
}
Notice the $data = array(); before the while loop. With array_merge you merge categories and subcategories with the $data array into the data array.
If you happen to get duplicted value you do not need or want, simply uncomment $data = array_unique($data); and it will erase duplicated entries for you.
Please clarify your question, if I do not address your problem and I will update my answer.
Have fun, may the source be with you.

Returning mysqli results outside of function

Given the following code:
function fetchData($mysqli){
$sql = "select * from `test`";
$result = mysqli_query($mysqli,$sql);
return $result;
}
$result = fetchData($mysqli);
while($row = mysqli_fetch_array($result)){
echo $row['id'];
}
My code is obviously more complicated than this. It loops itself until it yields some results changing some variables at each iteration.
$result is empty. What am I doing wrong? Thank you!
FULL CODE:
function fetchItem($itemID, $period, $mysqli){
$periodArray = array('7', '30', '60', '90', '180');
while (current($periodArray) !== $period) next($periodArray);
$currentPeriod = current($periodArray);
$sql = "SELECT * from `test` where `period` = '$period'";
$result = mysqli_query($mysqli,$sql);
$row_count = $result->num_rows;
if($row_count < 5){
$currentPeriod = next($periodArray);
fetchItem($itemID, $currentPeriod, $mysqli);
} else if($row_count >= 5){
$currentPeriod = current($periodArray);
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
// var_dump($rows); <-- returns all results
return $rows;
}
}
$output = fetchItem($itemID, $period, $mysqli);
echo '<pre>';
print_r($output); <-- NULL
echo '</pre>';
As you can see if I don't get results for a given period it moves onto the next one.
Your code should be:
function fetchData($mysqli){
$sql = "select * from `test`";
$init = mysqli_query($mysqli, $sql);
$result = $init->fetch_array(MYSQLI_ASSOC);
return $result;
}
$result = fetchData($mysqli);
foreach($result as $row){
echo $row['id'];
}

Logic in while-statement

For a search I am using this code snippet:
$stmt = $dbh->prepare('SELECT id,username FROM `users` WHERE `username` LIKE :keyword');
$keyword = "%".$data."%";
$stmt->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['user'] = utf8_encode($row['username']);
array_push($return_arr,$row_array);
}
Instead of getting only those value´s which are "LIKE keyword", I get every result from my table "users", why is this happening?
You should check if $data is empty before preparing the query:
if(!empty($data) && is_string($data)){
$stmt = $dbh->prepare('SELECT id,username FROM `users` WHERE `username` LIKE :keyword');
$keyword = "%".$data."%";
$stmt->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['user'] = utf8_encode($row['username']);
array_push($return_arr,$row_array);
}
} else {
// Do something else
}

Categories