How to call multiple values from array in while loop in php - php

How to add multiple values in while loop, I can only add two values as per my level, one is id and other one is title, I want to add more fields like I am getting from the server please help anyone
$limitStart = $_POST['limitStart'];
$limitCount = 15;
if(isset($limitStart) || !empty($limitstart)) {
$con = mysqli_connect($hostname, $username, $password, $dbname);
$query = 'SELECT id, title, caption, description, featured_image, logo, category_sku, industry_sku
FROM works ORDER BY title limit '.$limitStart.','.$limitCount .'';
$result = mysqli_query($con, $query);
$res = array();
while ($resultSet = mysqli_fetch_assoc($result)) {
$res[$resultSet['id']] = $resultSet['featured_image'];
}
echo json_encode($res);
}

Maybe something like:
$res = array();
while ($resultSet = mysqli_fetch_assoc($result)) {
foreach($resultSet as $key => $value) {
$res[$key] = $value;
}
}
will do the trick?

Just add them all as the $resultSet is already an associative array:
while ($resultSet = mysqli_fetch_assoc($result)) {
$id = $resultSet['id'];
unset($resultSet['id']); // <-- add this is if you don't want the id in the final set as it's now the key.
$res[$id] = $resultSet;
}
Or to pick an choose certain fields, just do some basic PHP, add the additinonal fields as a new associative array.
Here's an example with adding caption and featured_image:
while ($resultSet = mysqli_fetch_assoc($result)) {
$res[$resultSet['id']] = ['featured_image'=>$resultSet['featured_image'],
'caption' => $resultSet['caption']];
}

If your $limitStart is 14 and your $limitCount is 15 it should return one id.
$limitStart = $_POST['limitStart']; // What is this number?
$limitCount = 15;
There is a typo in your if statement, see below.
Also your code is vulnerable for SQL-injection because you don't prepare your statements.
if( isset( $limitStart ) || !empty( $limitStart ) ) { // Typo here. (small s)
$mysqli = mysqli_connect($hostname, $username, $password, $dbname);
$sql = "SELECT id, title, caption, description, featured_image, logo, category_sku, industry_sku
FROM works ORDER BY title limit ".$limitStart.",".$limitCount."";
$stmt = $mysqli->prepare($sql); // Prepare the statement
$stmt->bind_param("ii", $limitStart, $limitCount); // Bind the parameters
$stmt->execute(); // Execute the query
// Bind the result
$stmt->bind_result($id, $title, $caption, $description, $featured_image, $logo, $category_sku, $industry_sku);
$result = $stmt->get_result();
$res = array();
while ($resultSet = $result->fetch_assoc()) {
$res[$resultSet['id']] = $id;
}
$stmt->close(); // Close the statement
$mysqli->close();
echo json_encode($res);
}

Related

PDO While loop only gets the last data

I am trying to display a nested json as seen in this picture
JSON Ouput
However it only gets the last data. I am sure that the 1st id has a data. Please see the code below
<?php
include 'conn2.php';
$pdo = new PDO($dsn, $user, $passwd);
$stmt = $pdo->prepare("CALL sp_foods_display();");
$stmt->execute();
$stmt->bindColumn('bar_name',$bar_name);
$stmt->bindColumn('address',$address);
$stmt->bindColumn('id',$post_id);
$response = array();
$result = array();
while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
$temp["bar_name"] = $bar_name;
$temp["address"] = $address;
$temp["item_details"] = getItem($post_id);
array_push($result, $temp);
}
$response["result"] = $result;
echo "<pre>" . json_encode($response,JSON_PRETTY_PRINT) . "</pre>";
function getItem($id) {
global $pdo;
$stmt = $pdo->prepare("SELECT * FROM fct_menu_foods WHERE post_id = :cur_post_id ORDER BY id ASC");
$stmt->bindParam(":cur_post_id",$id,PDO::PARAM_INT);
$stmt->execute();
$food_details = array();
$stmt->bindColumn('food_name',$food_name);
$stmt->bindColumn('price',$price);
$stmt->bindColumn('img_name',$img_name);
while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
$temp = array();
$temp["food_name"] = $food_name;
$temp["price"] = $price;
$temp["img_name"] = $img_name;
array_push($food_details, $temp);
}
return $food_details;
}
?>
my target output is to display all data in nested.
I found a solution. My bad. You have to closeCursor(); for every query and use fetchAll for getting the data.

PHP MySQLi function get user data can't work

i am using This code for showing user data record but this code is not work on my side
I want to echo out specific user data. I created a function where I insert multiple arguments (each argument represents a column in the database) and then echo whichever column I want with a simple line of code.
Index.php
include('function.php');
$conn = new MySQLi(localhost, root, password, database);
$user_id = $_SESSION['login_user']; // like 1
$user = user_data($conn, $user_id, 'login', 'pass', 'nikename', 'email');
if(empty($user)){
echo 'error'; // always showing this error
}else{
echo $user['nickename'];
}
Always Showing echo 'error';
function user_data($conn, $user_id){
$data = array();
$user_id = (int)$user_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 1) {
unset($func_get_args[0]);
unset($func_get_args[1]);
$valid = array('login', 'pass', 'nikename', 'email');
$fields = array();
foreach($func_get_args as $arg) {
if(in_array($arg, $valid)) $fields[] = $arg;
}
$fields = '`' . implode ('`, `', $fields) . '`';
if($stmt = $conn->prepare("SELECT $fields FROM `users` WHERE `user_id` = ?")) {
$stmt->bind_param('si', $fields, $user_id);
$stmt->execute();
//here I am trying to convert the result into an array
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch()) {
foreach($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
return $results;
$stmt->close();
}
}
}
Seeing and analyzing your code several times, I think the below will solve your issue.
Add this before your while/fetch loop
$row = array();
stmt_bind_assoc($stmt, $row);
so your code will look like this
$row = array();
stmt_bind_assoc($stmt, $row);
while ($stmt->fetch()) {
foreach($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
Also make sure you read the full documentation of bind_param on php.net here
Thanks and Best Regards
I guess, instead of
if($stmt = $conn->prepare("SELECT $fields FROM `users` WHERE `user_id` = ?")) {
$stmt->bind_param('si', $fields, $user_id);
you should go with
if($stmt = $conn->prepare("SELECT $fields FROM `users` WHERE `user_id` = ?")) {
$stmt->bind_param('i', $fields, $user_id);
Bind parameters. Types: s = string, i = integer, d = double, b = blob
As far as you have one argument with type INT you need to pass 'i' as a first parameters.
Try debugging over line by line in that function where you will get exact flaw by var_dump().

Mysqli with unknown bind_results

Ok, I thought I had this, but I can't see why it's not working...
I have a SELECT with a variable table, hence my columns (bind_result) is going to be variable.
I need to adjust for any number of columns coming back, and fetch as an associated array, since there will be multiple rows coming back:
// Get table data
$mysqli = new mysqli('host','login','passwd','db');
if ($mysqli->connect_errno()) { $errors .= "<br>Cannot connect: ".$mysqli->connect_error()); }
$stmt = $mysqli->prepare("SELECT * FROM ?");
$stmt->bind_param('s', $table);
$stmt->execute();
// Get bind result columns
$fields = array();
// Loop through columns, build bind results
for ($i=0; $i < count($columns); $i++) {
$fields[$i] = ${'col'.$i};
}
// Bind Results
call_user_func_array(array($stmt,'bind_result'),$fields);
// Fetch Results
$i = 0;
while ($stmt->fetch()) {
$results[$i] = array();
foreach($fields as $k => $v)
$results[$i][$k] = $v;
$i++;
}
// close statement
$stmt->close();
Any thoughts are greatly appreciated ^_^
EDIT: New code:
$mysqli = new mysqli('host','login','passwd','db');
if ($mysqli->connect_errno)) { $errors .= "<br>Cannot connect: ".$mysqli->connect_error()); }
$stmt = "SELECT * FROM ".$table;
if ($query = $mysqli->query($stmt)) {
$results = array();
while ($result = $query->fetch_assoc()) {
$results[] = $result;
}
$query->free();
}
$mysqli->close();
You can not bind the table name. Bind_param accept the column name and its datatype.
To use the table name dynamically use the below code:
$stmt = $mysqli->prepare("SELECT * FROM ".$table);

Returning Multiple Rows with MySqli and Arrays

For the past two days or so I've been converting my functions to mysqli. I've run into a problem. I have a function that returns an array containing a row from the database. However, I want the array to contain multiple rows versus one. Also, how would I be able to echo out the individual posts. Here is my failed attempt that only displays one row in the array.
$mysqli = new mysqli("localhost", "user", "password", "database");
function display_posts ($mysqli, $user_id) {
$fields = "`primary_id`, `poster_id`, `profile_user_id`, `post`";
$user_id = (int)$user_id;
$query = "SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id
LIMIT 4";
if ($result = $mysqli->query($query)) {
$row = $result->fetch_assoc();
return $row;
$result->free();
$stmt->close();
}}
Here I am trying to display the data.
$user_id = 1;
$posts = display_posts($mysqli, $user_id);
//Not sure what to do with $posts. A While loop perhaps to display each post?
You have to use a loop to get them all at once:
<?php
function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$query = 'SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id LIMIT 4';
$result = $mysqli->query($query);
$rows = resultToArray($result);
var_dump($rows); // Array of rows
$result->free();
Why not use directly like this:
$result = mysqli_fetch_all($mysqli->query($query), MYSQLI_ASSOC);
I'm late, but I believe this is what you wanted to achieve:
$mysqli = new mysqli("localhost", "user", "password", "database");
$fields = "`primary_id`, `poster_id`, `profile_user_id`, `post`";
function display_posts () {
global $mysqli;
global $fields;
$query = "SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id LIMIT 4";
$posts = $mysqli -> query($query) or die('Error: '.$mysqli -> error);
if ($posts -> num_rows > 0) {
while ($row = $posts -> fetch_assoc()) {
$value = $row['/*The table column here (You can repeat this line with a different variable e.g. $value 2, $value 3 etc and matching them with the respective table column)*/'];
echo $value./*Concatenate the other variables ($value 1 etc) here*/'<br />';
}
}else {
echo 'No records found.';
}
}
//Call the function
display_posts ();

PHP PDO can't update records in foreach loop

Script searchs through DB and fix broken links. Search and replace functionality works fine, but when trying to save updated data scripts wrights only first raw. I'm stucked! I can use simple mysql_query commands to update data, but needs PDO...
header('Content-Type: text/html; charset=UTF-8');
error_reporting(E_ALL);
echo "Welcome";
$mysql = new PDO('mysql:host=localhost;dbname=db_name;charset=UTF-8','user','12345');
if (!$mysql) die('Can\'t connect');
$tables = array(
'categories',
'news',
'pages'
);
function getContent($table) {
global $mysql;
$fieldnum = 0;
$fields = array();
$vals = array();
$st = $mysql->query("SHOW FIELDS FROM `{$table}`");
while ($row = $st->fetch(PDO::FETCH_ASSOC)) {
$fields[$fieldnum]=$row["Field"];
$fieldnum++;
}
$totalfields=$fieldnum;
$res = $mysql->query("SELECT * FROM `{$table}`");
$sql = "UPDATE `:table` SET :field = ':val' WHERE `:idf` = :id;";
while ($row = $res->fetch(PDO::FETCH_NUM)) {
for ($j=0; $j<$res->columnCount();$j++) {
$rs = str_replace('index.php/','',$row[$j],$m);
if ($rs && $m>0) {
if ($table == 'categories')
$prim= 'cat_id';
elseif($table == 'news') $prim= 'news_id';
elseif($table == 'pages') $prim= 'page_id';
else $prim= $table.'_id';
$upd = $mysql->prepare($sql);
$update = $upd->execute(array(
':table'=>$table,
':field'=>$fields[$j],
':val'=>$rs,
':idf'=>$prim,
':id'=>$row[0]
));
}
}
}
}
foreach ($tables as $t) {
getContent($t);
}
Need help to fix it!
try to fetch all and then go through array
and you do not need to use prepare every time - just once see Example #2
....
$res = $mysql->query("SELECT * FROM `{$table}`");
$rows = $res->fetchAll(PDO::FETCH_NUM);
$sql = "UPDATE `:table` SET :field = ':val' WHERE `:idf` = :id;";
$upd = $mysql->prepare($sql);
foreach ($rows as $row) {
foreach ($row as $col_name => $value) {
......
prepare outside the loop! you are loosing its value this way, also try $upd->debugDumpParams(); and binding before execution, maybe the values u r binding is not right.

Categories