HTML select not inflating correctly from PHP array - php

I am trying to create a drop down menu of usernames or a <select> as it's known in HTML. However I am only getting the last value back from my array and I can't figure out why.
PHP
function getUserName($db) {
try {
$sql = 'SELECT members.name FROM members';
$query_an = $db->query($sql);
$count = $query_an->rowCount();
if ($count > 0) {
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names = array();
$names[] = $row['name'];
}
return $names;
}
} catch(PDOException $e) {
die($e->getMessage());
}
}
HTML
<select>
<?php $names = getUserName($db); foreach($names as $key => $value) { ?>
<option value="<?php echo $key ?>"><?php echo $value ?></option>
<?php }?>
</select>
I'm fairly sure the HTML section of my code is solid. I think the error lies in how I'm adding values to my $names array but after staring at it for a half an hour I can't see it. Thanks for any help/fresh eyes.

You need to declare your array outside the loop
if ($count > 0) {
$names = array();
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
return $names;
}

this is emptying your array every time : $names = array();
use this :
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}

You are creating a new $names array every row then returning the last one. You need to declare the array outside the while loop. The following should work:
function getUserName($db) {
try {
$sql = 'SELECT members.name FROM members';
$query_an = $db->query($sql);
$count = $query_an->rowCount();
if ($count > 0) {
$names = array();
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
return $names;
}
} catch(PDOException $e) {
die($e->getMessage());
}
}

The problem is you're re-initializing the array on every loop:
See:
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names = array();
$names[] = $row['name'];
}
return $names;
Should be:
$names = array();
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
return $names;

Related

Selected values as json_encode data

I've got two foreach() loops in my php to fetch MySQL data from 2 different dbs.
foreach ($result as $val) {
$country = $val["count"]; //results fetched successfully
$number = $val["tel"];
}
foreach ($rslt as $dta) {
$score = $dta["score"]; //results fetched successfully
$rank = $dta["rnk"];
}
I want to pass the results from both foreach loops as json_encode() data.
My question is, how do I pass $number , $score and $rankas json_encode()?
I tried the below at the bottom of the code, but did not work.
$data = array();
$data[$val] = $val["tel"];
$data[$dta] = $dta["score"];
$data[$dta] = $dta["rnk"];
echo json_encode($data);
Expecting output:
[{"tel":"123456","score":"785","rnk":"135"}]
$dta and $val are only in the loops scope. You assign variables within the loop, so use them.
$data = array();
$data['tel'] = $number;
$data['score'] = $score;
$data['rnk'] = $rank;
echo json_encode($data);
You can also assign $data within your foreach loop.
$data = array();
foreach ($result as $val) {
$data['country'] = $val["count"]; //results fetched successfully
$data['tel'] = $val["tel"];
}
foreach ($rslt as $dta) {
$data['score']= $dta["score"]; //results fetched successfully
$data['rank'] = $dta["rnk"];
}
echo json_encode($data);
try this
$data = array();
foreach ($result as $val) {
$data['tel'][] = $val["tel"];
$country = $val["count"]; //results fetched successfully
$number = $val["tel"];
}
foreach ($rslt as $dta) {
$data['score'][] = $dta["score"];
$data['rnk'][] = $dta["rnk"];
$score = $dta["score"]; //results fetched successfully
$rank = $dta["rnk"];
}
echo json_encode($data);
Added an extra [] if array size of $val["tel"],$dta["score"],$dta["rnk"] is greater than 1 else you can remove [] if array size is 1

How do I display all the values of a multi dimentional array?

Hey I have an array that contains an array:
$outPutResults = array();
while($row = mysqli_fetch_array($results))
{
$outPutResults[] = $row['industry'];
$outPutResults[] = $row['location'];
$outPutResults[] = $row['title'];
$outPutResults[] = $row['description'];
}
$searchResults[] = $outPutResults;
I am little confused how I would echo the contents.
As far as I am aware $outputresults[] should now be contained within $searchresults[].
To output the content I'm using :
foreach ($searchResults[0] as $item) {echo $item;}
But this is only echoing the first set of results so rather than having to repeat the above and changing the number (0) each time how would i do it so it outputs all the sub arrays?
Just nest your foreach:
foreach ($searchResults as $row) {
foreach($row as $item) {
echo $item;
}
}
$outPutResults = array();
$i = 0;
while($row = mysqli_fetch_array($results))
{
$outPutResults[$i] = $row;
$i++;
}
foreach ($outPutResults as $items)
foreach($items as $item)
echo $item;
Why are you doing
$searchResults[] = $outPutResults;
instead of just
$searchResults = $outPutResults;
Then you don't have to worry about nesting your foreach statements.
You should nest two loops. For example like this:
foreach ($searchResults as $array) {
foreach ($array as $item){
echo $item;
}
}

problem in the output of query - php+json

function tableOne() {
$query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());
$i = 0;
while($row = mysql_fetch_assoc($query)) {
$arr[] = array($row[valor]);
++$i;
}
echo json_encode($arr);
}
}
the output will be
[["15573"],["31978"],["11227"],["5752"],["20817"],["32182"]]
i need something like:
["15573","31978","11227","5752","20817","32182","10935"]
i tried some changes in the code but the output is not what i want.
thanks
You are placing sub-arrays in each element of your array. You should replace
$arr[] = array($row[valor]);
with
$arr[] = $row[valor];
The [] in $arr[] already adds each entry as an element of the array.
$query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());
$arr = array();
while ($row = mysql_fetch_assoc($query)) {
$arr[] = $row['valor']; // get rid of the array() wrapper
}
echo json_encode($arr);

How to add a <br/> after each result, but not last result?

This is my partial code:
while($row = $db->fetch_array($query))
{
echo $row['row_name'];
}
How can I make it so it will add a break tag after each result, but not the last result?
Put the output into an array, then join the array with implode:
$rows = array();
while($row = $db->fetch_array($query))
{
$rows[] = $row['row_name'];
}
echo implode('<br/>', $rows);
You could do this. No arrays or counters.
if($row = $db->fetch_array($query))
{
do {
echo $row['row_name']
} while($row = $db->fetch_array($query) && print("<br />"));
}
for ($idx = 0; $row = $db->fetch_array($query); $idx++)
{
if ($idx > 0) { echo "<br/>"; }
echo $row['row_name'];
}

php function to return SQL results

This is what i have
function GetEventsList(){
$result = mysql_query("SELECT * FROM `events`") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$en = $row['name'];
$endt = $row['date'];
$push = "<option value=$id>$en - $endt</option>";
return $push;
}
}
Its only returning 1 result, when there are 3 in the table
That's because you're returning from the function at the end of the first iteration. Try:
function GetEventsList() {
$result = mysql_query("SELECT * FROM `events`") or trigger_error(mysql_error());
$push = '';
while ($row = mysql_fetch_array($result)) {
foreach($row AS $key => $value) {
$row[$key] = stripslashes($value);
}
$id = $row['id'];
$en = $row['name'];
$endt = $row['date'];
$push .= "<option value=$id>$en - $endt</option>";
}
return $push;
}
On a side note: if you used good formatting/indenting that would've been far easier for you to spot.
Also, are you sure you need to use stripslashes()?
If I'm reading the code correctly, return $push; is exiting the while loop prematurely. You want to return only after all results are gathered and stored in something.
Either use echo $push in your foreach loop; or put each iteration of the option element into an array, then insert the array as needed.

Categories