mysqli query only returning first row - php

I am migrating from mysql to mysqli, and I am having trouble returning more than one row from the database in a query.
$db = new mysqli($hostname, $sql_us, $sql_us_pwd, $sql_db); // This is already connected
function db_query($db, $query, $type = 'object') {
global $db;
$result = $db->query($query);
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
return $row;
}
} else {
while($row = $result->fetch_object()) {
return $row;
}
}
mysqli_free_result($result);
}
$query = "SELECT * FROM `users`";
$user = db_query($db, $query);
print_r($user); // This is only returning the first row of results
I'm obviously trying to make a function where I can query the database and either return the results in an associative array or as an object. What am I doing wrong?

Use this code:
$rows = array();
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
while($row = $result->fetch_object()) {
$rows[] = $row;
}
}
return $rows;
You are using the return inside the while and return terminates the while loop after first iteration that's why you are getting only one row.

You need to store while loop values into array try this
$rows = array();
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
while($row = $result->fetch_object()) {
$rows[] = $row;
}
}
return $rows;

When you return in a function it stops executing at that point and goes back to the where it was called from with the value that you are returning.
In your case when you do a return $row, you are getting out of the function as soon as the first row is read.
Fix is:
$result = array();
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
$result[] = $row;
}
} else {
while($row = $result->fetch_object()) {
$result[] = $row;
}
}
return $row;

You are only returning the first row. You have to return an array.

$arr = array();
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
$arr[] = $row;
}
}
else {
while($row = $result->fetch_object()) {
$arr[] = $row;
}
}
return $arr;

Related

fetch_assoc() returning only first row [duplicate]

This question already has answers here:
return inside foreach php and laravel
(2 answers)
Closed 3 years ago.
Im fairly new to OOP way of coding and I want to fetch a record of users in my DB
This is my code below:
$con = new mysqli('localhost', 'root', '', 'goldpalace');
class User {
public $connect;
public function get_users() {
$sql = "SELECT * from users";
$result = $this->connect->query($sql);
$num_rows = $result->num_rows;
if ($num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row;
return $data;
}
}
}
}
$obj = new User();
$obj->connect = $con;
$user_data = $obj->get_users();
foreach ($user_data as $value) {
echo $value['name']."<br>";
}
I have a lot of records in my DB but it only returns the first row.
That's because you return the value of $data immediately after you retrieve one row. return will return that value and stop execution of that method. You need to return that value after you are done retrieving your values.
class User {
public $connect;
public function get_users() {
$sql = "SELECT * from users";
$result = $this->connect->query($sql);
$num_rows = $result->num_rows;
$data = [];
if ($num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
return $data;
}
}
FYI, you can use fetch_all() here to make this a bit simpler:
class User {
public $connect;
public function get_users() {
$sql = "SELECT * from users";
$result = $this->connect->query($sql);
$num_rows = $result->num_rows;
$data = [];
if ($num_rows > 0) {
$data = $result->fetch_all(MYSQLI_ASSOC);
}
return $data;
}
}
For you return in the first cycle in while
while ($row = $result->fetch_assoc()) {
$data[] = $row;
return $data;
}
just move the return out of while loop
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
return $data;

PHP json_encode doesn't print anything

I'm running PHP and MySQL and have the following code:
$data = array();
$result = mysql_query($search_query);
if ($result){
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
if (sizeof($data) > 0) {
//var_dump($data);
echo json_encode($data);
} else {
echo 'empty';
}
}
If my query has no rows I do get empty returned.
But if there's any records I get a Resource has no content in Safari.
But if I uncomment my //var_dump($data); then I do get a nice array of values.
Try this:
// Database connection.
$mysqli = new mysqli('localhost', 'user', 'password', 'db_name');
// Your query.
$search_query = "SELECT * FROM yuor_table";
$data = array();
$result = $mysqli->query($search_query);
if ($result){
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
if (sizeof($data) > 0) {
//var_dump($data);
echo json_encode($data);
} else {
echo 'empty';
}
}
This is very simple solution. I would suggest to use "mysqli".

Php function that takes SQL query as a parameter and returns JSON string

This is my function so far, how do I convert the item to json and print it?
$query = 'SELECT * FROM department';
function dataGenerator($query) {
$conn = oci_new_connect('u','p','h') or die ("dbdn");
$stid = oci_parse($conn, $query);
$r = oci_execute($stid);
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
foreach ($row as $item) {
print ($item); }
}
}
dataGenerator("SELECT * FROM department");
use json_encode and your function should have a return
function dataGenerator($query) {
$conn = oci_new_connect('u','p','h') or die ("dbdn");
$stid = oci_parse($conn, $query);
$r = oci_execute($stid);
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
$result[] = $row;
}
return json_encode($result);
}
make array of items and then use json_encode to generate the json as string
$items = [];
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
foreach ($row as $item) {
$items[] = $item;
}
}
$json = json_encode(array("items" => $items))

Pass table variable to SELECT function

I have a getData() function, and a database with two tables: employers and members.
I would like to pass a variable containing the table name, so inside an "if" I could execute the appropriate SELECT statement. My problem I believe that after the "if" the $stmt->bind_param(); doesn't know which $stmt to bind the take.
Any ideas on how I could achieve this?
Thanks
public function getData($table)
{
if ($table == "employers")
{
$stmt = $this->link->prepare("SELECT * FROM employers ");
}
else
{
$stmt = $this->link->prepare("SELECT * FROM members ");
}
$stmt->bind_param();
if ($stmt->execute())
{
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$row = array_map('stripslashes', $row);
$dataArray[] = $row;
}
}
return $dataArray;
}
No, since you aren't binding anything, that ->bind_param method is superfluous. Just take that off.
public function getData($table)
{
$dataArray = array();
$t = ($table === 'employers') ? 'employers' : 'members';
$query = "SELECT * FROM $t";
$stmt = $this->link->prepare($query);
if($stmt->execute()) {
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$row = array_map('stripslashes', $row);
$dataArray[] = $row;
}
}
return $dataArray;
}
Sample Usage:
$data = $aministrator_query->getData('members');
$tbody = '';
foreach($data as $row) {
$tbody .= "<tr><td>{$row['user_id']}</td><td>{$row['user_password']}</td><td>{$row['user_first_name']}</td><td>{$row['user_last_name']}</td></tr>";
}
$table = sprintf('<table><thead><tr><th>ID</th><th>Password</th><th>First Name</th><th>Last Name</th></tr></thead><tbody>%s</tbody></table>', $tbody);
echo $table;

return values from two nested loops

I have a while loop nested in another while loop. The first while will give me 5 elements, and for each element I have to go to the second while and get 2 elements.
The problem is I have to return all 10 values to a function.
How can I make it?
I tried to merge two arrays but it didn't work.
function ShowCustomers()
{
while($row2 = mysql_fetch_array($result2))
{
while($row3 = mysql_fetch_array($result3))
{
$res = array($row2['f_name'], $row3['name'], $row3['s_name']);
$res1 = array_merge($res1,$res);
}
}
return $res1;
}
If all you want to do is put all the results into one array and return it, you can use array_push(), or the shorthand: $your_array[] = ...:
function ShowCustomers()
{
$result_array = array();
while($row2 = mysql_fetch_array($result2))
{
while($row3 = mysql_fetch_array($result3))
{
$res = array($row2['f_name'], $row3['name'], $row3['s_name']);
$result_array[] = $res;
}
}
return $result_array;
}
You need to declare $res1 outside the scope of your loops so that it keeps its value after each iteration:
function ShowCustomers()
{
$res1 = array();
while($row2 = mysql_fetch_array($result2))
{
while($row3 = mysql_fetch_array($result3))
{
$res = array($row2['f_name'], $row3['name'], $row3['s_name']);
$res1 = array_merge($res1,$res);
}
}
return $res1;
}

Categories