How do I get a value outside the loop using PHP [duplicate] - php

This question already has answers here:
How to get comma separated values from database [duplicate]
(3 answers)
Converting MySQL results into comma separated values
(4 answers)
Can I concatenate multiple MySQL rows into one field?
(16 answers)
Closed 3 years ago.
I'm creating a small website using PHP, which is generally a site for showcasing the hospital, and I modified the code given in this example:
https://www.w3schools.com/php/php_mysql_select.asp
<?php
$query = "SELECT * FROM emp WHERE type = 'woman' ";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$cat = $row["cat"] . ',';
echo $cat;
////<---- echo on while (Loop)
}
}
The expected output would be as follows:
Output: 35,36
But I changed the code with the link above and it is as follows:
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$cat = $row["cat"] . ',';
}
echo $cat;
///// <---- echo Out of While (Loop)
}
Output: 35
My expecting output would be 35, 36 outside of "while" using "echo".
What code do you recommend to output "35,36" the same code above?

You can try the below code to achive your requirement
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result)) {
$data[] = $row["cat"];
}
}
echo implode(",",$data);

Related

Loop Through Array using PHP and MySQLi [duplicate]

This question already has answers here:
How to loop through a mysql result set
(6 answers)
Closed 3 years ago.
I'm trying to loop through a MySQL table using PHP, but it is only showing one line.
//Retrieve a list of outstanding developments
$sql = "SELECT * FROM tblDevelopment WHERE strStatus=?";
$statement = mysqli_stmt_init($conn);
//Check for any errors in the SQL statement
if (!mysqli_stmt_prepare($statement,$sql)){
//Report any errors with the prepared $statement
header("Location: ../sqlerror.php");
exit();
} else {
//If there are no errors, query the database for the username
mysqli_stmt_bind_param($statement,'s', $status);
mysqli_stmt_execute($statement);
$results = mysqli_stmt_get_result($statement);
if ($row = mysqli_fetch_assoc($results)) {
echo 'header';
while ($row = mysqli_fetch_assoc($results))
{
echo $row['strDetail'] . "</";
}
echo 'footer';
} else {
echo 'No results to display';
}
}
The code works when there are no results, but it only shows one result when there are more than one - any ideas what I'm doing wrong?
You are almost there... you need to keep calling mysqli_fetch_assoc until you reach the end of the result set. Changing your if to a while should be enough to get you rolling.
while (($row = mysqli_fetch_assoc($results)) !== null) {

json_encode doesn't display all array values [duplicate]

This question already has answers here:
php json_encode not working on arrays partially
(2 answers)
Closed 5 years ago.
I have a PHP script where it fetches all records from a table and encodes it to JSON. The table has a total of 246 records. echo count(); returns 246 as well.
The problem is, whenever I use json_encode, it doesn't display the values from the array at all, all I see is a blank page. But if I reduce the number of records to 13 instead of 246, it works and it displays the encoded JSON result. I have also tried to increase the memory_limit at my php.ini file to 4095M, but no avail.
$result = mysqli_query($con, "SELECT * FROM cities");
if (mysqli_num_rows($result) > 0) {
$response["cities"] = array();
$city = array();
while($row = mysqli_fetch_assoc($result)) {
$city[] = $row;
array_push($response["cities"], $city);
}
$response["success"] = 1;
echo json_encode($response);
}
Try below and you'll get to know what is happening exactly:
$json = json_encode($response);
if ($json)
echo $json;
else
echo json_last_error_msg();
json_last_error_msg() - Returns the error string of the last json_encode() or json_decode() call
Array "city" is expanding for each call and you are pushing the complete array on each iteration in loop .
Try :
while($row = mysqli_fetch_assoc($result)) {
array_push($response["cities"], $row);
}
It should work
Remove $response array push $row into $cities array. After pushing all city set the city and response in json_encode(); function like this echo json_encode(array("cities"=>$cities, "success"=>1));
if (mysqli_num_rows($result) > 0) {
$cities = array();
while($row = mysqli_fetch_assoc($result)) {
array_push($cities, $row);
}
echo json_encode(array("cities"=>$cities, "success"=>1));
}

SQL select as a PHP function [duplicate]

This question already has answers here:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in
(3 answers)
Closed 7 years ago.
I'm selecting data from MySQL. My code looks like this:
$sql = "SELECT oznacenie_odpadu FROM zdroj_dat ORDER by ID ASC";
if ($result = $conn->query($sql)) {
// fetch associative array
while($row = $result->fetch_assoc()) {
echo '<option value="'.$row['oznacenie_odpadu'].'" >'.$row['oznacenie_odpadu'].'</option>';
}
}
This part of code is in my code multiple times. I'm calling it 5times only string "oznacenie_odpadu" is changing. Therefore I made function:
function select($data) {
$sql = "SELECT rozmer FROM zdroj_dat ORDER by id ASC";
if ($result = $conn->query($sql)) {
// fetch associative array
while($row = $result->fetch_assoc()) {
echo '<option value="'.$row[$data].'" >'.$row[$data].'</option>';
}
}
}
Calling it with select("somevalue");
Syntax is ok because I didn't change anything but when I load the page the data from database are not retrieved.
You have a variable scope issue. $conn is not available inside of your function. You need to pass it as a parameter so ic an be used inside of your function.
function select($conn, $data) {
$sql = "SELECT rozmer FROM zdroj_dat ORDER by id ASC";
if ($result = $conn->query($sql)) {
// fetch associative array
while($row = $result->fetch_assoc()) {
echo '<option value="'.$row[$data].'" >'.$row[$data].'</option>';
}
}
}
Call it:
select($conn, "somevalue");

Concatenate All Rows From One Column With MYSQL [duplicate]

This question already has answers here:
SQL, How to Concatenate results?
(7 answers)
Closed 7 years ago.
I am trying to do something that I thought would be very simple but it's driving me crazy.
I have the following data:
ID --- Name
1 --- Joe
2 --- Bob
3 --- Jim
4 --- Mike
I want to be able to show the results of this from MYSQL as:
"Joe", "Bob", "Jim", "Mike"
I tried CONCATENATE tutorials, but they all seem to be for merging like ID's.
$sql = "SELECT names, CONCAT_WS('', 'names') as namelist FROM peoplenames";
$result = $conn->query($sql);
echo $row["namelist"];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$names = $row["nameslist"];
echo $names;
}
}
If I echo outside the loop I only get the most recent result.
Any ideas?
The problem is that you are overwriting the contents of $names each time round the loop.
Change your code like this
$sql = "SELECT names FROM peoplenames";
$result = $conn->query($sql);
$names = NULL;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$names .= sprintf('"%s",',$row['names']);
}
// output amalgamated date
rtrim($names, ',');
echo $names;
}
Change your query to SELECT names FROM peoplenames and use PHP concat for a string:
$names = "";
while($row = $result->fetch_assoc()) {
$names .= '"' . $row["names"] . '",';
}
echo $names;

mysqli_fetch_array while loop columns [duplicate]

This question already has answers here:
get array of rows with mysqli result
(2 answers)
Closed 2 months ago.
Should be pretty basic, but I can't get it to work. I have this code to iterate over a mysqli query:
while($row = mysqli_fetch_array($result)) {
$posts[] = $row['post_id'].$row['post_title'].$row['content'];
}
It works and returns:
Variable #1: (Array, 3 elements) ↵
0 (String): "4testtest" (9 characters)
1 (String): "1Hello world!Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!" (99 characters)
2 (String): "2Sample PageThis is an example page. It's different from a blog post because it will stay in one place and will show up in
your site navigation (in most themes)." (161 characters)
The problem is that it puts all three colums into one column, so I can't access them seperatly.
This for example:
0 (String): "4testtest" (9 characters)
Should be seperated into 4, test, test
When I do this:
while($row = mysqli_fetch_array($result)) {
$posts['post_id'] = $row['post_id'];
$posts['post_title'] = $row['post_title'];
$posts['type'] = $row['type'];
$posts['author'] = $row['author'];
}
It only outputs 1 row instead of all three …
Any help is greatly appreciated!
Get all the values from MySQL:
$post = array();
while($row = mysqli_fetch_array($result))
{
$posts[] = $row;
}
Then, to get each value:
<?php
foreach ($posts as $row)
{
foreach ($row as $element)
{
echo $element."<br>";
}
}
?>
To echo the values. Or get each element from the $post variable
This one was your solution.
$x = 0;
while($row = mysqli_fetch_array($result)) {
$posts[$x]['post_id'] = $row['post_id'];
$posts[$x]['post_title'] = $row['post_title'];
$posts[$x]['type'] = $row['type'];
$posts[$x]['author'] = $row['author'];
$x++;
}
I think this would be a more simpler way of outputting your results.
Sorry for using my own data should be easy to replace .
$query = "SELECT * FROM category ";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result))
{
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
echo $cat_id . " " . $cat_title ."<br>";
}
This would output :
-ID Title
-1 Gary
-2 John
-3 Michaels
Both will works perfectly in mysqli_fetch_array in while loops
while($row = mysqli_fetch_array($result,MYSQLI_BOTH)) {
$posts[] = $row['post_id'].$row['post_title'].$row['content'];
}
(OR)
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$posts[] = $row['post_id'].$row['post_title'].$row['content'];
}
mysqli_fetch_array() - has second argument $resulttype.
MYSQLI_ASSOC: Fetch associative array
MYSQLI_NUM: Fetch numeric array
MYSQLI_BOTH: Fetch both associative and numeric array.
Try this :
$i = 0;
while($row = mysqli_fetch_array($result)) {
$posts['post_id'] = $row[$i]['post_id'];
$posts['post_title'] = $row[$i]['post_title'];
$posts['type'] = $row[$i]['type'];
$posts['author'] = $row[$i]['author'];
}
$i++;
}
print_r($posts);
Try this...
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

Categories