echo database data to html php pdo - php

i have a database select on load of html on the select statement i select the last five in descending or here is the code
loadevent.php
<?php
function LoadEvent(){
global $dbh;
$stmt = $dbh->prepare("SELECT * FROM events ORDER by event_id DESC LIMIT 5") ;
//$stmt->bindValue(1,$eventwhat);
$stmt->execute();
while($selected_row = $stmt->fetch(PDO::FETCH_ASSOC)){
$_SESSION['searchresultwhat'] = $selected_row['event_what'];
$_SESSION['searchresultwhere'] = $selected_row['event_where'];
$_SESSION['searchresultwhen'] = $selected_row['event_when'];
$_SESSION['searchresultwho'] = $selected_row['event_who'];
$event = array($_SESSION['searchresultwhat'] => $selected_row['event_what'], $_SESSION['searchresultwhere'] =>$selected_row['event_where'], $_SESSION['searchresultwhen'] =>$selected_row['event_when'],$_SESSION['searchresultwho'] =>$selected_row['event_who']);
$_SESSION['arr'] = $event;
foreach ($_SESSION['arr'] as $_SESSION['searchresultwhat'] => $selected_row['event_what']){
echo $_SESSION['searchresultwhat'];
echo "<br/>\n";
}
}
}
?>
and in my html at top page i write
index.php
<?php include_once("include/loadevent.php");
LoadEvent();?>
in html my code is
<?php
foreach ($_SESSION['arr'] as $_SESSION['searchresultwhat'] => $selected_row['event_what']){
echo $_SESSION['searchresultwhat'];
echo "<br/>\n";
}
?>
when i do echo from loadevent.php i get the last five in descending order but in index all i get is the first event and nothing more why is it that way can anyone see where my mistake is?

You are doing some very odd things with the $_SESSION var, and as far as I can see there is no reason at all. Try this:
<?php
function LoadEvent()
{
global $dbh;
$stmt = $dbh->prepare("SELECT * FROM events ORDER by event_id DESC LIMIT 5") ;
$stmt->execute();
$events = array();
while ($selected_row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$events[] = array(
'searchresultwhat' => $selected_row['event_what'],
'searchresultwhere' => $selected_row['event_where'],
'searchresultwhen' => $selected_row['event_when'],
'searchresultwho' => $selected_row['event_who']
);
}
// Is this just for testing? Or should it be echoing stuff all the time?
// foreach ($events as $key => $value)
// {
// echo $value['searchresultwhat'];
// echo "<br/>\n";
// }
// This is completely optional and should be removed if you don't
// use the $_SESSION method later on in your HTML
$_SESSION['arr'] = $events;
return $events;
}
?>
...and then in your HTML, do this:
<?php
foreach ($_SESSION['arr'] as $value)
{
echo $value['searchresultwhat'];
echo "<br/>\n";
}
?>
Or, even better in your index.php do this:
<?php
include_once("include/loadevent.php");
?>
Then in your HTML, you can avoid the $_SESSION all together:
<?php
foreach (LoadEvent() as $value)
{
echo $value['searchresultwhat'];
echo "<br/>\n";
}
?>

The simple solution would be to replace $_SESSION['arr'] = $event; with $_SESSION['arr'][] = $event; AND
foreach ($_SESSION['arr'] as $_SESSION['searchresultwhat'] => $selected_row['event_what']){
echo $_SESSION['searchresultwhat'];
echo "<br/>\n";
}
with
foreach ($_SESSION['arr'] as $value){
echo $value[$_SESSION['searchresultwhat']];
echo "<br/>\n";
}

in your 'while' loop you overwrite values in $_SESSION superglobal:
while($selected_row = $stmt->fetch(PDO::FETCH_ASSOC)){
//it is overwritten each time you are in while loop
$_SESSION['searchresultwhat'] = $selected_row['event_what'];
(...)
foreach ($_SESSION['arr'] as $_SESSION['searchresultwhat'] => $selected_row['event_what']){
//in this place when you echo it, it echoes current loop iteration so it is executed 5 times
echo $_SESSION['searchresultwhat'];
echo "<br/>\n";
}
}
being at index.php you do echo of last value only from while loop.

Related

Filtering an array with foreach and for loop

I'm pulling data from mssql database into an array called
$results2
I need to echo out each 'Item' only one time, so this example should only echo out:
"52PTC84C25" and "0118SGUANN-R"
I can do this easily with:
$uniqueItems = array_unique(array_map(function ($i) { return $i['ITEM']; }, $results2));
The issue is when i try to echo out the other items associated with those values. I'm not sure how to even begin on echoing this data. I've tried:
foreach($uniquePids as $items)
{
echo $items."<br />";
foreach($results2 as $row)
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
}
}
This returns close to what I need, but not exactly:
This is what I need:
Assuming your resultset is ordered by ITEM...
$item = null; // set non-matching default value
foreach ($results2 as $row) {
if($row['ITEM'] != $item) {
echo "{$row['ITEM']}<br>"; // only echo first occurrence
}
echo "{$row['STK_ROOM']}-{$row['BIN']}<br>";
$item = $row['ITEM']; // update temp variable
}
The if condition in the code will check if the ITEM has already been printed or not.
$ary = array();
foreach($results2 as $row)
{
if(!in_array($row['ITEM'], $ary))
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
$ary[] = $row['ITEM'];
}
}

using foreach multiple times

How can I use foreach multiple times?
<?php
$query = $db->query('SELECT tbl_stok.id_stok,
tbl_stok.id_provinsi,
tbl_stok.id_kabupaten,
tbl_stok.tanggal,
tbl_stok.mie_instan,
tbl_stok.beras,
tbl_stok.telur
FROM `tbl_stok` INNER JOIN tbl_wilayah ON tbl_stok.id_provinsi = tbl_wilayah.id_user
');
$query->fetchAll;
?>
I want to use the first foreach to show the data tables:
<?php foreach($query as $row){
echo $row['beras'];
}?>
Then I want to use the second foreach for chart:
<?php foreach($query as $row){
echo $row['telur'];
}?>
However, this foreach works only once.
You can do this:
1) save your data to an array.
foreach($query as $row){
$data[]= $row;
}
2) use your array in every loop you want as many time you want
foreach($data as $row){
echo $row['beras'];
}
foreach($data as $row){
echo $row['telur'];
}
Use foreach only once and store all values you need, like this:
<?php
$beras_array = array();
$telur_array = array();
foreach($query as $row){
$beras_array[] = $row['beras'];
$telur_array[] = $row['telur'];
}
//you can use `for` explained later instead of two `foreach`
foreach($beras_array as $b){
echo $b;
}
foreach($telur_array as $t){
echo $t;
}
//With this method you can also use only one for instead of two foreach
$limit = count($beras_array);
for($i=0; $i<$limit; $i++){
echo $beras_array[$i];
echo $telur_array[$i];
}
?>
I hope it helps

How can I re-organize php array of sports

I'm trying to list sport league offerings for intramurals. My current php foreach spits out all the leagues and offerings. Great.
Now I want to only show 1 instance of the sport (course), like "Basketball" and then list the multiple league offerings (offering) in columns.
I can't do another loop based on
if $nt['course'] == "Basketball" because these will change
Not sure if my mssql query needs to change or if I can use another foreach loop?
query
$sql2 = SELECT category
,course
,offering
,Semester
,spots
,registerLink from dbtable WHERE semester like "%Fall 2016%" and category like "%Leagues%" ORDER BY course
$rs= mssql_query ($sql2, $con)
or die("Error!");
$result = array();
if (mssql_num_rows($rs)) {
while ($row = mssql_fetch_assoc($rs)) {
$result[] = $row;
}
}
return $result;
exit();
my foreach loop in view:
<?php
foreach ($data as $nt) {
echo "<div class='col-md-2'>";
echo "<h2><a href='#'>".$nt['course']."</a></h2>";
echo "<h3>".$nt['offering']."</h3>";
echo "<h4>".$nt['Semester']."</h4>";
echo "<p>".$nt['spots']."</p>";
echo "<button>".$nt['registerLink']."</button>";
echo "</div>";
}
So just to clarify:
category = "Leagues" which is in my query
course = Basketball and Flag Football, etc
It's very simple:-
instead of
$result[] = $row;
do
$result[ $row['course']][] = $row;
Simple solution:
$result = array();
if (mssql_num_rows($rs)) {
while ($row = mssql_fetch_assoc($rs)) {
if(!in_array($row["course"], $result))
{
array_push($result, $row["course"]);
}
array_push($result[$row["course"]], $row);
}
}
return $result;
And loop in view:
foreach($data as $key => $value)
{
echo "<h1>".$key."</h1>";
foreach($value as $nt)
{
echo "<div class='col-md-2'>";
echo "<h3>".$nt['offering']."</h3>";
echo "<h4>".$nt['Semester']."</h4>";
echo "<p>".$nt['spots']."</p>";
echo "<button>".$nt['registerLink']."</button>";
echo "</div>";
}
}

MYSQLi Multiple Records Outputs Duplicates

Issue:
I've continuously looked over my code and cannot find why the array is duplicating the data. A single entry into the database has a correct output, however if there is more than one it will duplicate those before it as well as the next one.
My Code:
global $connection;
//Query database & retrieve results.
$search = $connection->query('SELECT * FROM users WHERE country= "'.$country.'"');
echo '<table><tr><th>Username</th><th>Email</th><th>Country</th></tr>';
while ($result = $search->fetch_assoc())
{
$total[] = $result;
foreach ($total as $rows)
{
echo '<tr>';
echo '<td>'.stripslashes($rows['username']).'</td>';
echo '<td>'.stripslashes($rows['email']).'</td>';
echo '<td>'.stripslashes($rows['country']).'</td>';
echo '</tr>';
}
}
echo '</table>';
Output:
This will return the following form -
Username Email Country
exampleUser1 exampleEmail1#example.com United States
exampleUser1 exampleEmail1#example.com United States
exampleUser2 exampleEmail2#example.com United States
You can see the first line is repeated then the new entry is there, it will continue on from this the more it goes on.
Additional Info:
This is placed inside of a function and is executed when $_POST['country'] is submitted - $country is just $_POST['country'] with a real_escape_string.
$connection is just a new mysqli(localhost, user, pass, database) referenced in the script - it is globalised because this is wrapped inside a function.
Any help would be appreciated.
<?php
//... Your code
while ($rows = $search->fetch_assoc()) {
$rows = array_map('stripslashes', $rows);
echo '<tr>';
echo '<td>'.$rows['username'].'</td>';
echo '<td>'.$rows['email'].'</td>';
echo '<td>'.$rows['country'].'</td>';
echo '</tr>';
}
//... Your code
if you need to save and return from function this rows just create array $total and add $total[] = $rows; after echo '</tr>';
As mentioned in my comment, put the foreach outside your while loop like this:
echo '<table><tr><th>Username</th><th>Email</th><th>Country</th></tr>';
while ($result = $search->fetch_assoc()) {
$total[] = $result;
}
foreach ($total as $rows) {
echo '<tr>';
echo '<td>'.stripslashes($rows['username']).'</td>';
echo '<td>'.stripslashes($rows['email']).'</td>';
echo '<td>'.stripslashes($rows['country']).'</td>';
echo '</tr>';
}
echo '</table>';
Another solution is to just redeclare your $total all the time.. Just keep your code then and do:
$total = $result;

how do I look an array to extract data

Hi all Im trying to query a database and store the results ($searchResults[]) as an array :
<?php
if(isset($_POST['indexSearchSubmit']))
{
foreach($_POST['industryList'] as $selected)
{
$_POST['industryList'] = $selected;
$locationListResults = $_POST['locationList'];
$results = mysqli_query($con,"SELECT * FROM currentListings
WHERE location = '$locationListResults' AND industry = '$selected'");
$searchResults = array();
while($row = mysqli_fetch_array($results))
{
$searchResults[] = $row['industry'];
$searchResults[] = $row['location'];
$searchResults[] = $row['title'];
$searchResults[] = $row['description'];
}
}
mysqli_close($con);
}
?>
the problem im getting is when I try to echo the result:
<?php
echo $searchResults[0];
?>
its only bringing back 1 result not displaying all the results in the arrray as i want it to.
Could anybody please point out what it is im doing wrong.
Any help would be greatly appreciated
Do like this
<?php
print_r($searchResults); // Prints all array elements
?>
Alternatively, you can make use of a for loop to echo all elements too..
foreach($searchResults as $k=>$v)
{
echo $v;
echo "<br>";
}
Your code puts your data into 1D array. You probably want sth else so instead of this:
$searchResults[] = $row['industry'];
$searchResults[] = $row['location'];
$searchResults[] = $row['title'];
$searchResults[] = $row['description'];
do this:
$tmp = array();
$tmp['industry'] = $row['industry'];
$tmp['location'] = $row['location'];
$tmp['title'] = $row['title'];
$tmp['description'] = $row['description'];
$searchResults[] = $tmp;
or just this (thanks to Barmar):
$searchResults[] = $row;
This way you store your data as 2D array. So every row you obtain remains in one subarray.
To print the row (which is now in 2D array) iterate over subarrayw:
foreach($one_of_searchResult_rows as $k => $v)
{
// do whatever you need with $k and $v
}
I think you want a 2d array. Try this code snippet :
$searchResults = array();
while($row = mysqli_fetch_array($results))
{
array_push($searchResults,$row);
}
This should push each row as an associative array in every cell of your final searchResuts array. You could then access the values like:
echo $searchResults[0]['industry']; //and so on
echo $searchResults[0]; //Should print out the first match/row of the sql result
Lets make it simple :
$serach_result=mysqli_fetch_all ($result,MYSQLI_NUM);
//you should use print_r while trying to print an array
print_r($search_result[0]);
Reference : mysqli_fetch_all

Categories