Foreach Loop only uses last value [duplicate] - php

This question already has answers here:
How to store values from foreach loop into an array?
(9 answers)
Closed 1 year ago.
Hi I am using the Calendar Code u can find down in the code. Now I am using Sql to get some days I want to mark in the calendar. In the foreach loop u can see me using the array $tage.
When I print_r($tage) it gives me following Information: Array ( [0] => 9 [1] => 8 [2] => 8 [3] => 8 [4] => 8 [5] => 11 )
Maybe there is a Problem with the returning values, but using only the unique values was not possible either.
Fyi the only highlight I always get is the last value 11.
I think the whole issue comes down to the combination of while foreach and elseif. I can't find any Solution to this. Maybe someone figures it out.
Thanks :)
<?php
error_reporting();
ini_set('display_errors', 1);
setlocale(LC_TIME, "de_DE");
class Calendar{
private $month;
private $year;
private $daysofweek;
private $numdays;
private $date_info;
private $day_of_week;
private $tnr;
public function __construct($month,$year,$days_of_week =array('So','Mo','Di','Mi','Do','Fr','Sa')){
$this->month =$month;
$this->year =$year;
$this->days_of_week =$days_of_week;
$this->num_days =cal_days_in_month(CAL_GREGORIAN, $this->month, $this->year);
$this->date_info =getdate(strtotime('first day of', mktime(0,0,0,$this->month,1,$this->year)));
$this->day_of_week =$this->date_info['wday'];
$this->monat = date("n", mktime(0, 0, 0, $this->month, 1, $this->year));
}
public function show($tnr) {
$monate = array(1=>"Januar",
2=>"Februar",
3=>"März",
4=>"April",
5=>"Mai",
6=>"Juni",
7=>"Juli",
8=>"August",
9=>"September",
10=>"Oktober",
11=>"November",
12=>"Dezember");
include '../include/myt.php';
// WERT 0 entfernen
// GRÖße des ARRAY
$size =sizeof($tnr);
$now_mon= $this->monat;
foreach($tnr as $tnrs){
$sql= "SELECT * FROM termin WHERE nr = '$tnrs' AND monat ='$now_mon' ";
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($query);
$tagdata = $row['tag'];
if($tagdata == ""){
"";
} else {
$tage[] = $tagdata;
}
}
$output= '<table id="table'. $this->monat . '" class="table table-striped">';
$output .= '<thead id="head'. $this->monat . '" style="text-align:center">'. $monate[$this->monat] . ' ' . $this->year . '</thead>';
$output .= '<tr>';
foreach( $this->days_of_week as $day)
{
$output .= '<th class="header center">' . $day . '</th>';
}
$output .= '</tr><tr>';
if($this->day_of_week > 0){
$output .= '<td colspan="' . $this->day_of_week . '"></td>';
}
$current_day =1;
while ( $current_day <= $this->num_days){
if($this->day_of_week ==7){
$this ->day_of_week =0;
$output .= '</tr></tr>';
}
///PROBLEM
print_r($tage);
foreach($tage as $tag){
if($current_day == $tag){
$current='style ="background: black;"';
} else {
$current= '';
}
}
///PROBLEM
$output .='<td class="day"'.$current.'>' . $current_day . '</td>';
$current_day++;
$this->day_of_week++;
}
if($this->day_of_week != 7){
$remaining_days = 7 - $this->day_of_week;
$output .= '<td colspan="' . $remaining_days . '"></td>';
}
$output .= '</tr>';
$output .= '</table>';
echo $output;
}
}
?>

Change your foreach loop as below:
foreach($tnr as $tnrs) {
$sql= "SELECT * FROM termin WHERE nr = '$tnrs' AND monat ='$now_mon' ";
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($query);
$tagdata = $row['tag'];
if(!empty($tagdata)) {
$tage[] = $tagdata;
}
}
Can you please check at line $output .='<td class="day"'.$current.'>' . $current_day . '</td>';
It should be $output .='<td class="day"'.$current.'">' . $current_day . '</td>';, You are forgot to add ".
May be it is help you.

Related

How to get the array values which the array created in function?

When I think about the functional of array and I tried to create an array and store in the function acts as the clock but how can I get the array values outside the function?
function theClock($a,$b,$c){
$time['Hour'] = $a;
$time['Minute'] = $b;
$time['Seconds'] = $c;
return $time;
}
//How can I call the array values in there that $time is stored?
I am a beginner of PHP and I want to improve my concept, I am very grateful if anyone can helps, Cheers!
Sorry, I forgot to mention that I would like to use foreach() to shows the array values as the table form.
$show1 = '<table border ="1" >';
foreach($time as $ck => $tk){
$show1 .= '<tr><td>' . $ck . '</td><td>' . $tk . '</td></tr>';
}
$show1 .= '</table>';
$show2 = '<table border ="1">';
foreach($time as $tk){
$show2 .= '<td>' . $tk . '</td>';
$show2 .= '<td>:</td>';
}
$show2 .= '</table>';
echo $show1;
echo $show2;
theClock(11,12,13);
function clock($a,$b,$c){
$time['Hour'] = $a;
$time['Minute'] = $b;
$time['Seconds'] = $c;
return $time;
}
$time = clock(12, 30, 00);
$hour = $time['Hour'];
$minute = $time['Minute'];
$seconds = $time['Seconds'];
print $hour; // 12
print $minute; // 30
print $seconds; // 00
As per your edit, to use in a foreach loop:
$html = '<table border ="1" >';
foreach($time as $unit => $value){
$html .= "<tr><td>$unit:</td><td>$value</td></tr>";
}
$html .= '</table>';
You can do this by just calling your function with your parameters like
$time = clock(10,20,30);
try this
$vararr=clock($a,$b,$c);
$time = clock(12, 40, 15);
echo "<pre>";print_r($time);

sql query fetch error [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 3 years ago.
I'v got some code but keep getting error's also I'm new to php so any help would be great :)
Here's my code
<?php
// Create connection
$con = mysqli_connect("host","database","pswd");
// Database Connection Check
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
break;
}
echo "<table>";
echo nextweek("heren1kalender","Heren 1e Provinciale");
echo "</table>";
function nextweek($table, $ploegNaam) {
// Get this weeks dates (monday and sunday and month)
$current_day = date("N")
$days_to_sunday = 7 - $current_day;
$days_from_monday = $current_day - 1;
$monday = date("d", strtotime("- {$days_from_monday} Days"));
$sunday = date("d", strtotime("+ {$days_to_sunday} Days"));
$month = date("m", strtotime("+ {$days_to_sunday} Days"));
// SQL query
$result = mysqli_query($con,"SELECT datum, hoofd, thuisploeg, bezoekers FROM " . $table . " WHERE thuisploeg LIKE '%Lochristi%' OR bezoekers LIKE '%Lochristi%'");
while($row = mysqli_fetch_array($result)) {
$string ="";
// Get day and month from array
$dag = substr($row['datum'], 4, -6);
$maand = substr($row['datum'], 7, -3);
if ($dag >= $monday AND $dag <= $sunday AND $maand == $month) {
if (strpos($row['thuisploeg'],'Lochristi') !== false) {
$string .= "<tr>";
if (substr($row['hoofd'], 0, 1) >= 3) {
$string .= '<td class="win">' . $row['hoofd'] . "</td>";
}
else {
$string .= '<td class="loss">' . $row['hoofd'] . "</td>";
}
$string .= '<td>' . $ploegNaam . '</td>';
$string .= "<td><strong>VS</strong></td>";
$string .= '<td>' . $row['bezoekers'] . '</td>';
}
elseif (strpos($row['bezoekers'],'Lochristi') !== false) {
$string .= "<tr>";
if (substr($row['hoofd'], 0, 1) >= 3) {
$string .= '<td class="loss">' . $row['hoofd'] . "</td>";
}
else {
$string .= '<td class="win">' . $row['hoofd'] . "</td>";
}
$string .= '<td>' . $row['thuisploeg'] . '</td>';
$string .= "<td><strong>VS</strong></td>";
$string .= '<td>' . $ploegNaam . '</td>';
}
$string .= "</tr>";
}
}
return $string;
}
?>
And these are the PHP error's I'm getting:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/a2902119/public_html/test.php on line 24
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /home/a2902119/public_html/test.php on line 26
Thanks for the help!
After fixing the other issues: Variable scope. $con is not available in the functions. Pass it in as an arg or rework into classes or something.
Your SQL connection doesn't seem correct.
It should have 4 parts.
$con=mysqli_connect(hostaddress,dbuser,dbpass,databasename);

Convert 3D array into a HTML table

ARRAY
$array['1'] = null;
$array['2']['21'] = null;
$array['3']['31'] = null;
$array['3']['32'] = null;
$array['4']['41'] = null;
$array['4']['42']['421'] = null;
$array['4']['42']['422'] = null;
$array['5']['51'] = null;
$array['5']['52'] = null;
$array['5']['53']['531'] = null;
$array['5']['53']['532'] = null;
$array['5']['53']['533'] = null;
$array['6']['61']['611'] = null;
$array['6']['62'] = null;
$array['6']['63']['631'] = null;
$array['6']['63']['632'] = null;
$array['6']['63']['633'] = null;
$array['6']['63']['634'] = null;
$array['7']['71']['711'] = null;
$array['8']['81']['811'] = null;
$array['8']['81']['812'] = null;
$array['9']['91']['911'] = null;
$array['9']['91']['912'] = null;
$array['9']['92']['921'] = null;
$array['9']['92']['922'] = null;
I'm trying to convert array above into a HTML table. I need to add rowspan to get output like shown as image below but run out of juice.
PHP
//If condition is satistied
if (isset($array) && count($array) > 0)
{
//echo '<pre>'; print_r($array); exit;
//Initiate variables
$row = null;
$level_one_array = $array;
//Iterate through menu level one
foreach ($level_one_array as $level_one_name => $level_two_array)
{
//If level two is an array
if (is_array($level_two_array))
{
//Iterate through menu level two
foreach ($level_two_array as $level_two_name => $level_three_array)
{
//If level two is an array
if (is_array($level_three_array))
{
//Iterate through menu level three
foreach ($level_three_array as $level_three_name => $null)
{
$row .= '<tr>';
$row .= '<td class="td_data">' . $level_one_name . '</td>';
$row .= '<td class="td_data">' . $level_two_name . '</td>';
$row .= '<td class="td_data">' . $level_three_name . '</td>';
$row .= '</tr>';
}
}
//If level two is not an array
else
{
$row .= '<tr>';
$row .= '<td class="td_data">' . $level_one_name . '</td>';
$row .= '<td class="td_data">' . $level_two_name . '</td>';
$row .= '<td class="td_data"> </td>';
$row .= '</tr>';
}
}
}
//If level two is not an array
else
{
$row .= '<tr>';
$row .= '<td class="td_data">' . $level_one_name . '</td>';
$row .= '<td class="td_data"> </td>';
$row .= '<td class="td_data"> </td>';
$row .= '</tr>';
}
}
$table = '<table>';
$table .= '<tr><td class="td_title">Menus</td><td class="td_title">Submenus/Items</td><td class="td_title">Items</td></tr>';
$table .= $row;
$table .= '</table>';
echo $table;
}
else
{
echo '<center>No record found</center>';
}
WHAT I NEED IS THIS:
I wrote new code that will do the trick. Working with rowspan is very tricky. The key elements are calculate_rowspan() and the flag $on_level_X_row to determine whether or not it is necessary to add <tr>.
It was necessary to detach the output from the most inner foreach because you have to handle multiple rows with it. Also I added "\n" after each </tr> to make the output a little more human readable.
function calculate_rowspan($array)
{
if (!is_array($array) || count($array) == 0)
return 1;
$rowspan = 0;
foreach ($array as $key=>$value)
{
$rowspan++;
if (is_array($value) && count($value) > 0)
{
$rowspan += count($value);
// -1 because first element is one same row
$rowspan--;
}
}
return $rowspan;
}
if (is_array($array) && count($array) > 0)
{
$output = '';
foreach ($array as $level_one_name => $level_two_array)
{
if (!is_array($level_two_array) || count($level_two_array) == 0)
{
$output .= '<tr><td>';
$output .= $level_one_name;
$output .= '</td><td></td><td></td></tr>'."\n";
}
else
{
$output .= '<tr>';
$output .= '<td rowspan="'.calculate_rowspan($level_two_array).'">';
$output .= $level_one_name;
$output .= '</td>';
$on_level_one_row = TRUE;
foreach ($level_two_array as $level_two_name => $level_three_array)
{
if ( ! $on_level_one_row)
$output .= '<tr>';
else
$on_level_one_row = FALSE;
if (!is_array($level_three_array) || count($level_three_array) == 0)
{
$output .= '<td>';
$output .= $level_two_name;
$output .= '</td><td></td></tr>'."\n";
}
else
{
$output .= '<td rowspan="'.calculate_rowspan($level_three_array).'">';
$output .= $level_two_name;
$output .= '</td>';
$on_level_two_row = TRUE;
foreach ($level_three_array as $level_three_name => $null)
{
if ( ! $on_level_two_row)
$output .= '<tr>';
else
$on_level_two_row = FALSE;
$output .= '<td>';
$output .= $level_three_name;
$output .= '</td></tr>'."\n";
}
}
}
}
}
print '<table>'."\n";
print $output;
print '</table>';
}

Display a table in while loop

I am trying to display a table in while loop with 3 rows and 3 td for each row. But I am confusing how to archived thit.
This is my code so far:
while($row = mysqli_fetch_array($result)){
$testimonial = $row['testimonial'];
$cityName = $row['city_name'];
$name = $row['name'];
$imageName = $row['image_name'];
$member = $row['membership_type'];
$testimonial = nl2br($testimonial);
//Create new testimonial output
$output = "<table>\n";
$output .= " <tr>\n";
$output .= " <td>\n";
$output .= " <p>\n";
$output .= " <img src=\"".UPLOAD_DIR.$imageName."\" />";
$output .= " {$testimonial}";
$output .= " </p>\n";
$output .= " <p class=\"name\">{$name}<br />\n";
$output .= " <span>A Teacher - From {$cityName}</span></p>\n";
$output .= " </td>\n";
$output .= " </tr>\n";
$output .= "</table>\n";
echo $output;
}
The above code given me a table with multiple rows and 1 td for each row. But it is not my expecting result.
Can anybody tell me how can I display such a table in my While loop?
The current code creates a new table for every single entry. What you want is to move the <table> and </table> pieces outside of the loop, then you want a counter to keep track of how many cells you've handled. If it's even, start a new <tr>. Otherwise, end the current </tr>. Make sure you check at the end to see if you've finished a </tr>, and optionally add an empty <td></td> if needed.
this aught to do it
<?php
echo "<table>\n";
$cells = $total = 0;
$total_cells = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result))
{
$testimonial = nl2br($row['testimonial']);
$cityName = $row['city_name'];
$name = $row['name'];
$imageName = $row['image_name'];
$member = $row['membership_type'];
if ($cells === 0)
echo "<tr>\n";
//Create new testimonial output
$output = " <td>\n";
$output .= " <p>\n";
$output .= " <img src=\"".UPLOAD_DIR.$imageName."\" />";
$output .= " {$testimonial}";
$output .= " </p>\n";
$output .= " <p class=\"name\">{$name}<br />\n";
$output .= " <span>A Teacher - From {$cityName}</span></p>\n";
$output .= " </td>\n";
echo $output;
$cells++;
$total++;
if ($cells === 3 || $total === $total_cells)
{
echo "</tr>\n";
$cells = 0;
}
}
echo "</table>\n";
?>
Try this
$i = 0;
echo "<table>\n<tr>";
while($row = mysqli_fetch_array($result)){
$testimonial = $row['testimonial'];
$cityName = $row['city_name'];
$name = $row['name'];
$imageName = $row['image_name'];
$member = $row['membership_type'];
$testimonial = nl2br($testimonial);
//Create new testimonial output
$output .= " <td>\n";
$output .= " <p>\n";
$output .= " <img src=\"".UPLOAD_DIR.$imageName."\" />";
$output .= " {$testimonial}";
$output .= " </p>\n";
$output .= " <p class=\"name\">{$name}<br />\n";
$output .= " <span>A Teacher - From {$cityName}</span></p>\n";
$output .= " </td>\n";
echo $output;
if( $i %2 == 1 )
echo "</tr><tr>\n";
$i++;
}
echo "</tr>\n</table>\n";
EDIT
In general, for displaying n cells per row, change the if statement to
if( $i % n == (n - 1) )

Ajax mouseover show function alignment

I am trying to open a box by using mouseover function, however the box always shows on the right part of the object. Hence when the object is right end of the page, the whole box cannot be seen as shown in this photo.
https://rapidshare.com/files/998669066/problem.png
Here is my ajax code:
$(document).ready(function() {
$('.date-available').click(function() {
alert($(this).attr('id'));
});
$('.rezerve-td').mouseover(function() {
$(this).children().show();
}).mouseout(function() {
$(this).children().hide();
});
});
What should i do in order prevent it? Thanks.
Here is the html part of my code:
require_once 'class.dates.php';
require_once 'class.generic.php';
require_once 'connection.php';
$query = mysql_query("SELECT * FROM egitim_salonu", $baglanti);
while ($row = mysql_fetch_object($query)) {
$salonlar[$row->id] = array('ad' => $row->ad, 'detay' => $row->detay);
}
$query = mysql_query("SELECT * FROM salon_rezervasyonu", $baglanti);
while ($row = mysql_fetch_object($query)) {
$rezervasyonlar[$row->salon_id.'%'.$row->gun.'%'.$row->tip] = array('salon_id' => $row->salon_id, 'gun' => $row->gun, 'tip' => $row->tip, 'rezerve_edildigi_egitim' => $row->rezerve_edildigi_egitim);
}
$month = date('m', strtotime($_POST['d']));
$year = date('Y', strtotime($_POST['d']));
$date = date('F Y', strtotime('01-'.$month.'-'.$year));
if ($month == 1 || $month == 3 || $month == 5 || $month == 7 || $month == 8 || $month == 10 || $month == 12) {
$numberOfDays = 31;
} else if ($month == 4 || $month == 6 || $month == 9 || $month == 11) {
$numberOfDays = 30;
} else if (date('L', strtotime($year.'-01-01'))) {
$numberOfDays = 29;
} else {
$numberOfDays = 28;
}
// Tabloyu aç, başlığı hazırla
$output = '<table class="calendar" id="salon-rezervasyon-table">
<thead>
<tr><th rowspan="2">Salon</th><th colspan="'.(2 * $numberOfDays).'">'.$date.'</th></tr>
<tr>';
for ($i = 1; $i <= $numberOfDays; $i++) {
$output .= '<th width="10" colspan="2" class="day-th">'.$i.'</th>';
}
// Başlığı kapat, gövdeyi aç
$output .= '</tr></thead><tbody>';
// Her salon için...
foreach ($salonlar as $salonKey => $salonValue) {
$output .= '<tr id="salon-'.$salonKey.'"><td class="calendar-salon-column">'.$salonValue['ad'].'<br />'.$salonValue['detay'].'</td>';
// ... o ay içindeki günleri kontrol et. Burada kontrol için şunu yapıyoruz: salon id'si, tarih ve gün içerisindeki saati (öğleden önce, öğleden sonra)
// birleştirerek bir index (bu index unique bir index) oluşturuyoruz ve bu index yukarıdaki rezervasyonlar dizisinde tanımlanmış mı diye kontrol ediyoruz.
for ($i = 1; $i <= $numberOfDays; $i++) {
$dateCheck = date('Y-m-d', strtotime($i.'-'.$month.'-'.$year));
$rIndexOO = $salonKey.'%'.$dateCheck.'%Öğleden önce';
$rIndexOS = $salonKey.'%'.$dateCheck.'%Öğleden sonra';
//Öğleden önce
if(isset($rezervasyonlar[$rIndexOO])) {
$egitimPlaniQuery = mysql_query("SELECT * FROM egitim_plani WHERE id = ".$rezervasyonlar[$rIndexOO]['rezerve_edildigi_egitim'], $baglanti);
$egitimPlani = mysql_fetch_object($egitimPlaniQuery);
$output .= '<td id="'.$dateCheck.'%o" class="calendar-td rezerve-td">';
$output .= '<div class="rezerve">'.date('d-m-Y', strtotime($dateCheck)).' Öğleden Önce<br /><br />'.$egitimPlani->egitim_adi.'</div>';
$output .= '</td>';
} else {
$output .= '<td id="'.$dateCheck.'%o" class="date-available calendar-td">';
$output .= '';
$output .= '</td>';
}
//Öğleden sonra
if(isset($rezervasyonlar[$rIndexOS])) {
$egitimPlaniQuery = mysql_query("SELECT * FROM egitim_plani WHERE id = ".$rezervasyonlar[$rIndexOO]['rezerve_edildigi_egitim'], $baglanti);
$egitimPlani = mysql_fetch_object($egitimPlaniQuery);
$output .= '<td id="'.$dateCheck.'%s" class="calendar-td rezerve-td">';
$output .= '<div class="rezerve">'.date('d-m-Y', strtotime($dateCheck)).' Öğleden Sonra<br /><br />'.$egitimPlani->egitim_adi.'</div>';
$output .= '</td>';
} else {
$output .= '<td id="'.$dateCheck.'%o" class="date-available calendar-date-separator">';
$output .= '';
$output .= '</td>';
}
}
$output .= '</tr>';
}
$output .= '</tbody></table>';
echo $output;
You could probably fix this with some css.
div.rezerve {
position: absolute
}
If it still shows up off the page, you can add something like this to your javascript
....
var doc_width = $(document).width();
var rezerve_child = $(this).children();
rezerve_child.show();
var position = rezerve_child.offset();
var rezerve_child_width = rezerve_child.width();
if (position.left + rezerve_child_width > doc_width) {
$(this).css('right', '2px');
}
....
The jQuery Tooltip plugin would also probably be helpful.
http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/

Categories