mysqli query inside a while and foreach - php

Here's my code:
while($listAll = $listAllHere->fetch_assoc()) {
$whos = array();
$j_out = array();
$whos[] = $listAll['user_id'];
$j_out[] = $listAll['j_out'];
foreach ($j_out as $time) {
$timeleft = $time - $now;
if ($timeleft >= 0) {
foreach ($whos as $ids) {
echo "<div class=\"col-xs-3\"><a href=\"#\" class=\"btn btn-default\"><b>".$ids."</b><br />";
echo "<div class=\"badge\">".$timeleft."s</div></a></div>";
}
} else {
foreach ($whos as $ids) {
$noone[] = $ids + 1;
}
}
}
}
How can I query other table using each $ids to get username and display them?

Related

I'm trying to convert an array to XML but I am failing to get it 100% correct

I need to output the response from the database in XML. So far I have gotten it to output this:
The outermost tag needs to match the name of the action query, it'll either be <courses> or <students>.
Here is my code:
<?php
require_once('./database.php');
if (isset($_GET['format'])) {
$format = filter_var($_GET['format']);
}
if (isset($_GET['action'])) {
$action = filter_var($_GET['action'], FILTER_SANITIZE_STRING);
$tableName = "sk_$action";
}
$query = "SELECT * FROM $tableName";
if (isset($_GET['course'])) {
$course = filter_input(INPUT_GET, 'course');
$query .= " WHERE courseID = :course";
}
function arrayToXml($arr, $i = 1, $flag = false)
{
$sp = "";
for ($j = 0; $j <= $i; $j++) {
$sp .= " ";
}
foreach ($arr as $key => $val) {
echo "$sp<" . $key . ">";
if ($i == 1) echo "\n";
if (is_array($val)) {
if (!$flag) {
echo "\n";
}
arrayToXml($val, $i + 5);
echo "$sp</" . $key . ">\n";
} else {
echo "$val" . "</" . $key . ">\n";
}
}
}
$statement = $db->prepare($query);
$statement->bindValue(':course', $course);
$statement->execute();
$response = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
if ($format == 'json') {
echo json_encode($response);
}
if ($format == 'xml') {
arrayToXml($response, 1, true);
}
I'm pretty new to PHP and have never worked with XML. All help is appreciated. Thanks.
function arrayToXml($arr, $collectionTag, $singleTag) {
$collection = new SimpleXMLElement("<$collectionTag/>");
foreach ($arr as $row) {
$element = $root->addChild($singleTag);
foreach ($row as $tag => $value) {
$element->addChild($tag, $value);
}
}
return $collection;
}
$courses = arrayToXml($response, 'courses', 'course');
echo $courses->asXML();
Tested with PHP 7.1.23. Output:
<?xml version="1.0"?>
<courses>
<course><courseID>cs601</courseID><courseName>Web Application Development</courseName></course>
<course><courseId>cs602</courseId><courseName>Server-Side Application Development</courseName></course>
<course><courseId>cs701</courseId><courseName>Rich Internet Application Development</courseName></course>
</courses>
(I added newlines because by default it doesn't add any.)

XML: Show two child nodes with the same name in php

I have a problem with showing my xml into a php page. I have an xml that looks like this (obviously its only a part of it because it really to long to post it all).
It all goes well until it cames to the "genre", I have two values for it and I don't know how to show them at the same time.
<movie>
<id>4441</id>
<title>Rudderless</title>
<title_long>Rudderless (2014)</title_long>
<year>2014</year>
<rating>7.5</rating>
<runtime>105</runtime>
<genres>
<genre>Comedy</genre>
<genre>Drama</genre>
</genres>
</movie>
(an important thing to notice is that not every movie will have two genre, sometimes there is only one and sometime two or three)
This is my code right now
$genere = array();
foreach ($xml->data->movies->movie->genres as $row) {
foreach ($row->children() as $key => $val) {
if ($key == "genre") {
$genere[] = $val;
}
}
}
//and then I'll print
for ($i = 0; $i < 20 ; $i++) {
echo "<div class=text><b>" . $genere[$i] . "</b></div>";
}
When I'm doing this it will print only for the first item of the array, and the others just give me a "Notice: Undefined offset: 1 in /path/ on line 53"
I've tried to follow some guides but it was a failure
What am I doing wrong?
/--Edit--/
<?php
$xml = simplexml_load_file("https://yts.to/api/v2/list_movies.xml")
$titolo = array();
$locandina = array();
$anno = array();
$durata = array();
$genere = array();
foreach ($xml->data->movies->movie as $element)
{
foreach($element->children() as $key => $val)
{
$chiave = $key;
$valore = $val;
if ($key == "title")
{
$titolo[] = $val ;
}
if ($key == "medium_cover_image")
{
$locandina[] = $val ;
}
if ($key == "year")
{
$anno[] = $val ;
}
if ($key == "runtime")
{
$durata[] = $val;
}
}
}
foreach ($xml->data->movies->movie->genres as $row)
{
foreach($row->children() as $key => $val)
{
if ($key == "genre")
{
$genere[] = $val;
}
}
}
var_dump($genere);
for ($i=0 ; $i<20 ; $i++)
{
echo "<div class=totbox>";
echo "<div class=box><img src=" . $locandina[$i] . "></div>";
echo "<div class=text><b>" . $titolo[$i] . "</b> - " . $anno[$i] . "</div>";
echo "<div class=text><b>" . $genere[$i] . "</b></div>";
echo "<div class=text><b> Durata:" . $durata[$i] . "</b></div>";
echo "</div>";
}
?>
UPDATED - Code fixed. Please, try now.
<?php
$xml = simplexml_load_file("https://yts.to/api/v2/list_movies.xml")
$titolo = array();
$locandina = array();
$anno = array();
$durata = array();
$genere = array();
$i = 0;
foreach ($xml->data->movies->movie as $element) {
foreach ($element->children() as $key => $val) {
$chiave = $key;
$valore = $val;
if ($key == "title") {
$titolo[] = $val;
}
if ($key == "medium_cover_image") {
$locandina[] = $val;
}
if ($key == "year") {
$anno[] = $val;
}
if ($key == "runtime") {
$durata[] = $val;
}
if ($key == "genres") {
for($g = 0; $g < count($xml->data->movies->movie[$i]->genres->genre); $g++) {
$genere[$i][] = $xml->data->movies->movie[$i]->genres->genre[$g];
}
}
}
$i++;
}
for ($i = 0; $i < count($titolo); $i++) {
echo "<div class=totbox>";
if (isset($locandina[$i])) {
echo "<div class=box><img src=" . $locandina[$i] . "></div>";
}
echo "<div class=text><b>" . $titolo[$i] . "</b> - " . $anno[$i] . "</div>";
foreach ($genere[$i] as $genResult) {
echo "<div class=text><b>" . $genResult . "</b></div>";
}
echo "<div class=text><b> Durata:" . $durata[$i] . "</b></div>";
echo "</div>";
}
I hope this helps!
Look on my code, based on yours. PHP file:
<?php
$xml = new SimpleXMLElement(file_get_contents('test.xml'));
$genere = array();
foreach ($xml->genres as $row) {
foreach ($row->children() as $key => $val) {
if ($key == "genre") {
$genere[] = $val;
}
}
}
//and then I'll print
foreach ($genere as $genre) {
echo "<div class=text><b>" . $genre . "</b></div>";
}
XML file:
<movie>
<id>4441</id>
<title>Rudderless</title>
<title_long>Rudderless (2014)</title_long>
<year>2014</year>
<rating>7.5</rating>
<runtime>105</runtime>
<genres>
<genre>Comedy</genre>
<genre>Drama</genre>
</genres>
</movie>
Its work fine, test it.
Based on your full xml file, look on this:
<genres>
<genre>Horror</genre>
</genres>
You have only one genre on first position, so its work fine. You need to loop on movie tag first, not genres. So put your genre tag inside movie foreach.
Like:
foreach($element->children() as $key => $val)
{
if ($key == "genres")
{
// your loop, based on $val variable!
}

Loop through mysqli results array once to get all information

I am querying the database for data, but in order to do what I need, I end up looping through that results array at least three times. How do I get all of the info I need out of the array without having to loop so many times? I need to get data from the array based on the results from the previous loops. The code below is the only way I could figure out in order to only query the database once.
$recordSQL = mysqli_query($link, $sqlString);
$resultMonths = array();
while($recordResult = mysqli_fetch_assoc($recordSQL)) $resultMonths[] = $recordResult['date'];
mysqli_data_seek($recordSQL, 0);
$uniqueMonths = array_unique($resultMonths);
foreach($uniqueMonths as $key => $date){
echo '</div><div class="current-month">'.translateDate($date, '').'</div>';
$resultCompanies = array();
while($companyResult = mysqli_fetch_assoc($recordSQL)){
if($companyResult['date'] == $date) $resultCompanies[] = $companyResult['company'];
}
mysqli_data_seek($recordSQL, 0);
$uniqueCompanies = array_unique($resultCompanies);
$oldco = '';
foreach($uniqueCompanies as $key => $company){
$x = 0;
while($typeResult = mysqli_fetch_assoc($recordSQL)){
if($typeResult['date'] == $date && $typeResult['company'] == $company){
if($oldco != $typeResult['company']){
if($x != 0) echo '</div>';
echo '<div class="company-record">'.$typeResult['name'].' - ';
}
if($x > 0) echo ', ';
echo translateID('Type', $typeResult['type']).'('.translateID('Section', $typeResult['section']).')';
$oldco = $typeResult['company'];
$x++;
}
}
echo '</div>';
mysqli_data_seek($recordSQL, 0);
}
}
FYI, you are actually looping N**3 times. Do it this way:
$month_company_rows = array();
while ($row = mysqli_fetch_assoc($recordSQL)) {
$month_company_rows[$row['date']][$row['company']][] = $row;
}
foreach ($month_company_rows as $date => $company_rows) {
echo '</div><div class="current-month">'.translateDate($date, '').'</div>';
foreach ($company_rows as $company => $rows) {
echo '<div class="company-record">'.$company.' - ';
foreach ($rows as $x => $row) {
if($x > 0) echo ', ';
echo translateID('Type', $row['type']).'('.translateID('Section', $row['section']).')';
}
echo '</div>';
}
}

Calculate max, min, and average for every column in a 2D array

I'm calculating the average,min,max for each column.
The 16th column value is coming wrong for max and min. Average is working perfectly fine, but wrong only for the last column with large arrays -- I also get a notice error.
My code:
mysql_connect("localhost", "root", "") or
die("Could not connect: " . mysql_error());
mysql_select_db("db");
$qry = mysql_query("select blob_field from table where id=1");
$arr = mysql_fetch_row($qry) ;
$rt = explode("\n",$arr[0]);
$header_arr1 = explode(',',$rt[0]);
$header1 = array();
$channels = count($header_arr1)-2 ;
$header1[] = join(',', array_slice($header_arr1, 2));
//Only Header
$arr_values = array_values($rt);
$array_slice = array_slice($arr_values, 1);
echo "<pre>";
//print_r($array_slice);
$result_array = array();
for($i=0;$i<count($array_slice);$i++)
{
//echo $i;
$result_array[] = join(',',array_slice(explode(',', $array_slice[$i]), 2));
}
//print_r($result_array);
//$array_combined = array_merge($header1,$result_array);
$token = array( 'Average', 'Max', 'Min');
foreach($result_array as $key=>$val)
{
$res_arr[] = explode(",",$val);
}
$avArray = array();
$res_arr= array(
0=>array(1,2,3,6,7,8,9,11,33,44,55,66,77,88,16,18),
1=>array(17,52,38,666,79,8,9,15,33,44,55,66,76,88,16,18),
2=>array(17,562,538,7666,579,688,9,15,933,44,55,660,76,808,106,108),
);
foreach ($res_arr as $k=>$subArray)
{
foreach ($subArray as $id=>$value)
{
//print_r($id);
$avArray[$id] += $value/count($res_arr); //Notice: Undefined offset: 3
}
}
$token = array( 'Average', 'Max', 'Min');
$num = $avArray;
$tc=16;
?>
<table border="1" style="border-collapse: collapse;">
<thead>
<tr>
<th>Channels</th>
<?php for($j=0;$j<=$tc-1;$j++):?>
<th>CH<?= $j+1;?></th>
<?php endfor;?>
</tr>
</thead>
<tbody>
<?php
echo "<tr><td>Average</td>";
for($i=0; $i<=$tc-1;$i++)
{
echo "<td>" .round($num[$i],2). "</td>";
}
echo "<tr><td>Max</td>";
$arr_max = array();
foreach($res_arr as $subArray)
{
foreach($subArray as $k=>$v) {
$arr_max[$k][] = $v;
}
}
$max_array = array_map('max', $arr_max);
for($i=0; $i<=$tc-1;$i++)
{
echo "<td>" .$max_array[$i]. "</td>";
}
echo "<tr><td>Min</td>";
$arr_min = array();
foreach($res_arr as $subArray)
{
foreach($subArray as $k=>$v1) {
$arr_min[$k][] = $v1;
}
}
$min_array = array_map('min', $arr_min);
for($g=0; $g<= $tc-1;$g++)
{
echo "<td>" .$min_array[$g]. "</td>";
}
?>
</tbody>
</table>
See inline comments for explanation.
$avArray = array();
$res_arr= array(
0=>array(1,2,3,6,7,8,9,11,33,44,55,66,77,88,16,18),
1=>array(17,52,38,666,79,8,9,15,33,44,55,66,76,88,16,18),
2=>array(17,562,538,7666,579,688,9,15,933,44,55,660,76,808,106,108),
);
/*
foreach ($res_arr as $k=>$subArray){
foreach ($subArray as $id=>$value){
// this causes "Notice: Undefined offset: 0...15" because you can't add to an undeclared value
$avArray[$id] += $value/count($res_arr);
}
}
*/
$res_count=count($res_arr); // declare this outside of the loop for efficiency
foreach ($res_arr as $k=>$subArray){
foreach ($subArray as $id=>$value){
if($k==0){
$avArray[$id]=$value; // declare first round of values
}else{
$avArray[$id]+=$value; // add to existing values
if($k==2){
$avArray[$id]=$avArray[$id]/$res_count; // only divide on the last iteration
}
}
}
}
print_r($avArray);
No matter how you want to present it, you are going to have to loop over the data set more than one. Once to calculate and once to display.
Here is another snippet: (Demo)
$array = [
[1,2,3,6,7,8,9,11,33,44,55,66,77,88,16,18],
[17,52,38,666,79,8,9,15,33,44,55,66,76,88,16,18],
[17,562,538,7666,579,688,9,15,933,44,55,660,76,808,106,108],
];
$count = count($array);
$mins = [];
$maxs = [];
$avgs = [];
foreach ($array as $i => $row) {
foreach ($row as $col => $value) {
$ch = $col + 1;
if (!$i) {
$mins[$ch] = $value;
$maxs[$ch] = $value;
$avgs[$ch] = $value;
} else {
if ($value < $mins[$ch]) {
$mins[$ch] = $value;
}
if ($value > $maxs[$ch]) {
$maxs[$ch] = $value;
}
$avgs[$ch] += $value;
if ($i === $count - 1) {
$avgs[$ch] = number_format($avgs[$ch] / $count, 2);
}
}
}
}
echo '<table border=1>';
printf(
'<tr><th>Channels</th><th>CH%s</th></tr>',
implode('</th><th>CH', array_keys($avgs))
);
printf(
'<tr><th>Average</th><td>%s</td></tr>',
implode('</td><td>', $avgs)
);
printf(
'<tr><th>Max</th><th>%s</td></tr>',
implode('</td><td>', $maxs)
);
printf(
'<tr><th>Min</th><td>%s</td></tr>',
implode('</td><td>', $mins)
);
echo '</table>';

php/mysql array or query with some values

Hello I have this query
$upit = "SELECT id from usluga";
$rezultat = mysql_query($upit);
while($red = mysql_fetch_object($rezultat))
{
echo "<li>{$red->id}</li>";
}
I want on exit to get this:
<li>1,2,3,4,5,6</li>
<li>7,8,9,10,11,12</li>
<li>13,14,15,16,17,18</li>
<li>19,20,21,22,23,24</li>
and so on..
Any help?
You can use the mod operator(%) or use array functions to achive this
$upit = "SELECT id from usluga";
$rezultat = mysql_query($upit);
while ($red=mysql_fetch_object ($rezultat)) {
$t[] = $red->id;
}
$chunks = array_chunk($t, 6);
foreach ($chunks as $chunk) {
echo "<li>" . join(",", $chunk) . "</li>";
}
try this..
$upit="SELECT id from usluga";
$rezultat=mysql_query($upit);
$i=0;
$liflag=0;
while ($red=mysql_fetch_assoc($rezultat))
{
if($i<6)
{
$liflag=1;
if($i==0)
{
echo "<li>$red->id";
$i++;
continue;
}
else
{
echo ",$red->id";
$i++;
continue;
}
}
else
{
echo ",$red->id</li>";
$i=0;
$liflag=0;
continue;
}
}
if($liflag==1)
{
echo "</li>";
}

Categories