sql query fetch error [duplicate] - php

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);

Related

Incredible behaviour with strftime

I have this code:
function calendarDay ($month, $year)
{
$num = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$today = strtotime(date("Y-m-d"));
$result = array();
$str = "";
$strMonth = "";
for ($i = 0; $i < $num; $i++) {
$date = strtotime($year . "-" . $month . "-" . ($i + 1));
$day=strftime("%a", $date);
$month = strftime("%b", $date);
if ($today == $date) {
if ($day == "Sat" || $day == "Sun") {
$str .= "<th style='background-color:mediumseagreen'>" . $day. "</th>";
$strMonth = $strMonth . "<th style='background-color:mediumseagreen'>".($i + 1) . "-" . $month." ". "</th>";
}
else {
$str .= "<th style='background-color:#888888'>" . $day. "</th>";
$strMonth = $strMonth . "<th style='background-color:#888888'>".($i + 1) . "-" . $month." ". "</th>";
}
}
else if ($today != $date) {
if ($day == "Sat" || $day == "Sun") {
$str .= "<th style='background-color:mediumseagreen'>" . $day. "</th>";
$strMonth = $strMonth . "<th style='background-color:mediumseagreen'>".($i + 1) . "-" . $month." ". "</th>";
}
else {
$str .= "<th>" . $day. "</th>";
$strMonth = $strMonth . "<th>".($i + 1) . "-" . $month." ". "</th>";
}
}
$result = array_merge($result, array("Month" => $strMonth));
$result = array_merge($result, array("Day" => $str));
}
return $result;
}
When I delete the line which convert my numeric $month from parameters to string with strftime("%b", $date), It gives the good behaviour.
And when I add this line the var $day began to repeat 9 times the first day of the month... which is Tuesday, and can't get the solution, its a bug for me...
You're replacing the variable that you use in:
$date = strtotime($year . "-" . $month . "-" . ($i + 1));
So on the 2nd day of the month, instead of trying to parse 2019-1-2 you're parsing 2019-Jan-1. I'm not sure why, but when you use this format with a single-digit day, it always parses as if it's 2019-01-01.
The solution is to use a different variable.
function calendarDay ($month, $year)
{
$num = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$today = strtotime(date("Y-m-d"));
$result = array();
$str = "";
$strMonth = "";
for ($i = 0; $i < $num; $i++) {
$date = strtotime($year . "-" . $month . "-" . ($i + 1));
$day=strftime("%a", $date);
$monthName = strftime("%b", $date);
if ($today == $date) {
if ($day == "Sat" || $day == "Sun") {
$str .= "<th style='background-color:mediumseagreen'>" . $day. "</th>";
$strMonth = $strMonth . "<th style='background-color:mediumseagreen'>".($i + 1) . "-" . $monthName." ". "</th>";
}
else {
$str .= "<th style='background-color:#888888'>" . $day. "</th>";
$strMonth = $strMonth . "<th style='background-color:#888888'>".($i + 1) . "-" . $monthName." ". "</th>";
}
}
else if ($today != $date) {
if ($day == "Sat" || $day == "Sun") {
$str .= "<th style='background-color:mediumseagreen'>" . $day. "</th>";
$strMonth = $strMonth . "<th style='background-color:mediumseagreen'>".($i + 1) . "-" . $monthName." ". "</th>";
}
else {
$str .= "<th>" . $day. "</th>";
$strMonth = $strMonth . "<th>".($i + 1) . "-" . $monthName." ". "</th>";
}
}
$result = array_merge($result, array("Month" => $strMonth));
$result = array_merge($result, array("Day" => $str));
}
return $result;
}
Replace the code
$date = strtotime($year . "-" . $month . "-" . ($i + 1));
into
$date = strtotime($year . "-" . $month . "-" .str_pad(($i + 1), 2, '0', STR_PAD_LEFT) );
Oh my go thanks you all !!! a lot, i was searching what i'm doing wrong since several days...
Just a var name conflict with my numeric $month and the string month with strftime. So i replaced the name of the string one.
Bad mistake ! ^^

Why can't get the value of weekend in php

I don't know what are the errors of this code because it's suddenly not accurate the showing value to the user like this:
$holidays = array();
$query_holiday = "SELECT * FROM holiday_tbl";
$result = mysqli_query($dbcon, $query_holiday);
while($row_holiday = mysqli_fetch_assoc($result))
{
array_push($row_holiday, $holidays);
}
if(strtotime(date("Y-m-d")) > strtotime($row['due_date']))
{
$currentDate = date("Y-m-d");
$days = (strtotime($currentDate) - strtotime($row['due_date'])) / 86400;
$daysTemp = $days;
for($i=1;$i<$days;$i++)
{
$currentDay = date("D", strtotime("+ ".$i." days"));
$date_loop = date("Y-m-d", strtotime("+ ".$i." days"));
if($currentDay == "Sun" || $currentDay == "Sat")
{
$daysTemp--;
}
else if(in_array($date_loop, $holidays))
{
$daysTemp--;
}
}
echo $daysTemp;
}
The current implementation is rather convoluted. In these cases I find it's always better to start over and try to simplify the logic as much as possible. Here is my take on your problem:
function calculate_days_late($due_date = '', $holidays = array(), $current_date = 'today') {
$days_late = 0;
// Get the timestamps for due date and current date
$current_date_ts = strtotime($current_date);
$due_date_ts = strtotime($due_date);
// If current date is not after due date then not late
if ($current_date_ts <= $due_date_ts) {
return $days_late;
}
$loop_date_ts = $current_date_ts;
while ($loop_date_ts > $due_date_ts) {
// If the looping date is not a weekend or holiday then count it
if ( ! in_array(date('D', $loop_date_ts), array('Sat','Sun'))
&& ! in_array(date('Y-m-d', $loop_date_ts), $holidays)) {
$days_late++;
}
$loop_date_ts = strtotime('-1 day', $loop_date_ts);
}
return $days_late;
}
// Test
echo '2017-09-05 = ' . calculate_days_late('2017-09-05', array(), '2017-09-05') . "\n";
echo '2017-09-06 = ' . calculate_days_late('2017-09-05', array(), '2017-09-06') . "\n";
echo '2017-09-07 = ' . calculate_days_late('2017-09-05', array(), '2017-09-07') . "\n";
echo '2017-09-08 = ' . calculate_days_late('2017-09-05', array(), '2017-09-08') . "\n";
echo '2017-09-09 = ' . calculate_days_late('2017-09-05', array(), '2017-09-09') . "\n";
echo '2017-09-10 = ' . calculate_days_late('2017-09-05', array(), '2017-09-10') . "\n";
echo '2017-09-11 = ' . calculate_days_late('2017-09-05', array(), '2017-09-11') . "\n";
echo '2017-09-12 = ' . calculate_days_late('2017-09-05', array(), '2017-09-12') . "\n";
echo '2017-09-13 = ' . calculate_days_late('2017-09-05', array(), '2017-09-13') . "\n";
Working example: https://eval.in/856018

Foreach Loop only uses last value [duplicate]

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.

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);

formatting date string for html table

Can someone show me how to change this date stamp and print this in an html table?
I have an input file with this time stamp format:
4-Start=20100901180002
This time format is stored like this in an array.
I print out the array like so to create an html table:
foreach ($data as $row){
$counter ++;
$class = $counter % 2 === 0 ? 'alt1' : 'alt2';
echo '<tr class="' . $class . '">';
foreach ($keys as $column)
if (isset($row[$column])){
echo '<td>' . $row[$column];
} else {
echo '<td>' . '' . '</td>';
}
}
echo '</table>';
How do I change the timestamp in this table to this? 2010-09-01 18:00:02
This is what you are looking for,
http://de2.php.net/manual/en/function.strtotime.php
There is a similar question you can get more inputs from there as well..
How do I format the date and time That is received from database
EDIT:
Yes you can use it an echo as well
echo date("Y-m-d H:i:s",strtotime('20100901180002')) ; // 2010-09-01 18:00:02
You can even use CreateFromFormat as RC said, this is using CreateFromFormat in Procedural style.
$date = date_create_from_format("YmdHis", '20100901180002');
echo date_format($date, 'Y-m-d H:i:s'); // 2010-09-01 18:00:02
Refer to http://php.net/manual/en/datetime.createfromformat.php
This part is strange, the elseif is never reached in my opinion.
if (isset($row[$column])){
echo '<td>' . $row[$column] . '</td>';
} elseif ($column == 'Condition') {
echo '<td> Error </td>';
} else {
echo '<td> </td>';
}
Regarding your format issue:
// PHP > 5.2
$date_s = "" . $row['Start'];
$date = DateTime::createFromFormat("YmdHis", $date_s);
echo $date->format("Y-m-d H:i:s"); // 2010-09-01 18:00:02

Categories