MySQL mysqli_fetch_assoc field name & value. How? - php

The following code returns the field names of a result set. I also want it to return the values. How can I do this?
while ($row = mysqli_fetch_assoc($result)) {
foreach( $row as $field => $name) {
echo $field."<br>";
}
}

If we assume that your array looks like this:
$row["first_name"] = "John";
$row["last_name"] = "Doe";
$row["username"] = "john.doe";
Using this code:
while ($row = mysqli_fetch_assoc($result)) {
foreach( $row as $field => $value) {
echo "{$field} - {$value}<br>";
}
}
You will get an output like this:
first_name - John
last_name - Doe
username - john.doe
When you iterate through an array, using => operator, you are iterating in a "key-value" pair style. Every iteration holds the key and value as you can see.
Take a look at foreach for more information.

you are getting the value in $name variable
foreach( $row as $field => $name) {
echo $field . " = " . $name . "<br>";
}

Related

Loop through Object in PHP

I am trying to read each element of an Object array, the code reads values from an excel file and then assign the values to a variable.
for ($row = 1; $row <= $highestRow; ++ $row) {
$fname = $worksheet->getCellByColumnAndRow(0, $row);
echo '<td>' . $fname . '<br></td>';
}
The output of 'fname' is four different names, however I want to read each value using a loop and then assign them to a link as follows:
www.example.com/fname so that four different links get opened up when I execute the code. I just can't figure out how to access each element of 'fname' object one by one. I read over examples available online, but to no avail. Please bear in mind I am a newbie to PHP. Thanks
Check if this works,
foreach($fname as $values)
{
$value1 = $values->keyname1;
$value2 = $values->keyname2;
$value3 = $values->keyname3;
$value4 = $values->keyname4;
}
$url = "http://example.com/".$value1;
If $fname contains a space delimited list of names like Tim John Sam Tom then you can use explode() to turn that STRING into an array of strings.
for ($row = 1; $row <= $highestRow; ++ $row) {
$fname = $worksheet->getCellByColumnAndRow(0, $row);
$names = explode(' ', $fname);
foreach ( $names as $name ) {
echo '<td>' . $name . '</td>';
}
}
So if you use the $names array
$names[0] would be `Tim`
$names[1] would be `John`
$names[2] would be `Sam`
$names[3] would be `Tom`

Foreach is showing "Array" instead of selected items from dynamically generated checkboxes

I'm trying to capture a user's checkbox selection from a dynamically generated list of options but I'm getting "Array" instead of the names selected.
In my last test, I checked 2 of the three boxes and got 3 instances of "Array" back.
This is my query that finds the names:
$query = "SELECT id, first_name, last_name
FROM users WHERE location_id = " . $location_id;
$result = mysqli_query($connection, $query);
if (!$result)
{
die("Database query failed: " . mysqli_error($connection));
}
while ($row = mysqli_fetch_array($result))
{
$name = $row['first_name'] . " " . $row['last_name'];
echo '<label><input type="checkbox" name="emp_name[]" id="emp_name[]" value="' . $name . '"> ' . $name . '</label>';
}
I then post the array of names like this:
$attendee = $_POST['emp_name'];
And try to generate the list of names for my email like this:
$values = ('emp_name');
foreach ($values as $value) {
$$value = (array)$_POST[$value];
}
for($i = 0; $i < count($attendee); $i++){
$attendees = array();
foreach ($values as $value) {
$attendees[] = ${$value}[$i];
}
Can someone help me see what's wrong?
I changed my code and included a part of the html that I'm trying to render:
foreach ($attendee as $name) {
$attendees[] = $name;
$htmlBody .= "<tr><td>{$attendees}</td></tr>";
}
But it still returns Array.
Not sure why you do this:
$attendee = (array)$_POST['emp_name'];
Try to replace it with:
$attendee = $_POST['emp_name'];
From your question it's not too clear, but I think you're creating an array within an array,and that that's the issue.
If the above doesn't help, try to var_dump() the variable that gives you "Array" response, and you'll see what's within it.
EDIT: In addition to the change above, try to make this change too:
Replace all this code:
$values = ('emp_name');
foreach ($values as $value) {
$$value = (array)$_POST[$value];
}
for($i = 0; $i < count($attendee); $i++){
$attendees = array();
foreach ($values as $value) {
$attendees[] = ${$value}[$i];
}
with:
foreach ($_POST['emp_name'] as $name) {
$attendees[] = $name;
}
EDIT #2:
According to your code:
foreach ($attendee as $name) {
$attendees[] = $name;
$htmlBody .= "<tr><td>{$attendees}</td></tr>";
}
It's totally normal that you're getting Array instead of a name. See, by writing:
$attendees[] = $name;
you're implying to php that it's an array. On the other hand the foreach loop does the opposite thing, it takes each of the values from $attendee array and makes it available to you as $name variable. So you're basically doing the right thing, and then reverting it back to array for no reason.
SOLUTION:
Replace {$attendees} with {$name}. And it should work.
You can write that with alot less code.
$attendees will now contain your checked checkboxes.
$attendees = array()
foreach($_POST['emp_name'] as $name){
$attendees[] = $name;
}

How to convert mysql_fetch_assoc array to [column,column] Format in PHP

This is my function
$dataArray = array();
$results = mysqli_query($mysqli, ("SELECT CONCAT ('US-', medicare_provider_charge_inpatient_drg100_fy2011.`Provider State`) AS `Provider State`,
sum(ROUND(medicare_provider_charge_inpatient_drg100_fy2011.`Total Discharges`, 2)) AS `Total Discharges`
FROM medicare_provider_charge_inpatient_drg100_fy2011
WHERE medicare_provider_charge_inpatient_drg100_fy2011.`Provider Name` LIKE '%" . $hospital_name . "'
GROUP BY CONCAT ('US-', medicare_provider_charge_inpatient_drg100_fy2011.`Provider State`)"));
while ($row = mysqli_fetch_assoc($results)) {
$dataArray[] = $row;
}
I want to display data in following format
[Provider State, Total Discharges],
[US-AL,2051],
[US-TN,6982]
the dump of $dataArray gives me
Array
(
[0] => Array
(
[Provider State] => US-AL
[Total Discharges] => 2051.00
)
[1] => Array
(
[Provider State] => US-TN
[Total Discharges] => 6982.00
)
)
while ($row = mysqli_fetch_assoc($results)) {
$dataArray[] = $row["Provider State"]. "," .$row["Total Discharges"];
}
That should make your data into a single-dimensional-array.
You just need to work with the data to display the way you want. Print first the column names and then the data. I made this example to work for any number of fields:
// Print the first row with column names
$firstRow = array_keys(reset($dataArray));
$output = array();
foreach($firstRow as $val) {
$output[] = $val;
}
echo '['.implode(',',$output).']'."\n";
// Print all the data
foreach($dataArray as $row) {
$output = array();
foreach($row as $col) {
$output[] = $col;
}
echo '['.implode(',',$output).']'."\n";
}
If you need such structure of array, use this (but it is strange):
$newStructure = array();
$newStructure[] = "Provider State, Total Discharges";
while ($row = mysqli_fetch_assoc($results)) {
$newStructure[] = $row['Provider State'] . ',' . $row['Total Discharges'];
}
If you want to just display data, use this:
echo "Provider State, Total Discharges";
while ($row = mysqli_fetch_assoc($results)) {
echo = $row['Provider State'] . ',' . $row['Total Discharges'];
}

mysql query to php array and display the array

$query2 = "SELECT * FROM `Listing` WHERE listingid = '{$myID}'";
if(!($result2 = # mysql_query($query2,$connection)))
echo "query failed<br>";
$result_array = array();
while($row2 = mysql_fetch_assoc($result2))
{
$result_array[] = $row2;
}
foreach ($result_array as $key => $val) {
echo "$key = $val\n";
}
Listing (Table) has 7 fields.
I get a bunch of "0 = Array"
How do I store mysql query results into php array and display them?
I want to have it as array first so i can sort them.
You are actually storing them. The code you have listed is storing them in array of arrays to see them you can modify the for with:
foreach ($result_array as $key => $val) {
echo "$key = " . print_r($val, true) . "\n";
}
$val is actually an array containing all the fields of a row.

How to implode array that uses array_push in foreach loop

My tags are showing in the inner foreach loop in the right order.
I would like to comma separate them but am not sure how.
Is there a better way to display my tags without using the second foreach loop?
$people = array();
while($row = mysqli_fetch_array($rs, MYSQLI_ASSOC)){
if(!isset($people[$row["id"]])){
$people[$row["id"]]["id"] = $row["id"];
$people[$row["id"]]["tag"] = $row["tag"];
$people[$row["id"]]["tags"] = array();
}
array_push($people[$row["id"]]["tags"], array("id"=>$row["tags_id"],"tag_name"=>$row["tag"]));
}
foreach($people as $pid=>$p){
echo "(#{$p['id']}) ";
foreach($p["tags"] as $tid=>$t){
echo "<a href='#'>{$t['tag_name']}</a> ";
}
echo "<br><br>";
}
You don't need to use array_push, since you're only adding one element to the array. You can save the overhead of calling a function by using the syntax:
$people[ $row["id"] ]["tags"][] = array(...);
My answer depends on the necessity of the variables saved from the database. In your supplied code, you're only using the id and tag values from the database in the nested foreach loops. If this is this case, then you can simplify your arrays so you can use implode() on a new tags array. I have not tested this since I do not have your database schema, but I believe it will work.
<?php
$people = array();
$tags = array();
while( ($row = mysqli_fetch_array( $rs, MYSQLI_ASSOC)))
{
if( !isset( $people[$row['id']]))
{
$people[ $row['id'] ] = array( 'id' => $row['id'], 'tag' => $row['tag']);
$tags[ $row['id'] ] = array();
}
$tags[ $row['id'] ][] = $row['tag'];
}
foreach( $people as $pid => $p)
{
echo "(#{$p['id']}) ";
echo '' . implode( '', $tags[ $p['id'] ]) . '';
echo '<br /><br />';
}

Categories