Output stops after a while loop, without using "or die()" - php

I know there is another question with the same topic, but that question involves the or die() statement. I have the same problem, but i'm not using a or die() statement on my while loop. The answer is probably pretty obvious, but i can't figure it out.
$Dates = "1";
$Select = $mysqli->query("SELECT * FROM ----");
while ($Dates != "") {
$Dates = $Select->fetch_assoc();
$Get = $mysqli->query("SELECT * FROM " . $Dates["Meeting_Date"] . " WHERE Last_Name='" . $LName . "'");
$Vals = $Get->fetch_assoc();
if ($Vals != "") {
$TimeIn = $Vals["Time_In"];
$TimeIn2 = explode(":",$TimeIn);
$TotIn = ($TimeIn2[0]*60)+$TimeIn2[1];
$TimeOut = $Vals["Time_Out"];
$TimeOut2 = explode(":",$TimeOut);
$TotOut = ($TimeOut2[0]*60)+$TimeOut2[1];
$TotTime = ($TotOut - $TotIn)/60;
$TotalTime = floor($TotTime) . " Hours " . ($TotTime-floor($TotTime))*60 . " Minutes";
echo "<tr><td>" . str_replace("_","/",$Dates["Meeting_Date"]) . "</td><td>" . $TimeIn . "</td><td>" . $TimeOut . "</td><td>" . $TotalTime . "</td></tr>";
}
if ($Vals == "") {
echo "<tr><td>" . str_replace("_","/",$Dates["Meeting_Date"]) . "</td><td colspan='3' style='background-color: rgba(0,0,0,0.25)'>Did not Attend</td></tr>";
}
}
Anything i put after the while loop, doesn't get executed, even though the while loop only executes 2 times like it is supposed to...
Any ideas are appreciated

This is the problem:
while ($Dates != "") {
$Dates = $Select->fetch_assoc();
$Get = $mysqli->query("SELECT * FROM " . $Dates["Meeting_Date"] . " WHERE Last_Name='" . $LName . "'");
When there are no more records, $Dates will be empty (NULL) so the next line will lead to a fatal error.
You can change it to:
while ($Dates = $Select->fetch_assoc()) {
$Get = $mysqli->query("SELECT * FROM " . $Dates["Meeting_Date"] . " WHERE Last_Name='" . $LName . "'");

Related

I have successfully queried my database in wordpress/php however it is just showing blank when I try to display the results in a table

For my website I am making a parametric search to filter through 100's of power supplies, filtering by voltage etc. When I did this locally it worked perfectly however I am struggling when it comes to implementing it to wordpress, here is the code below of my output/the query, I know its a lot of if statements to build up the query, any improvements are greatly appreciated too.
<html>
<?php
$voltage=$_POST["MaxVoltage"];
$sql = "SELECT * FROM powersupplies WHERE MaxVoltage >= '".$voltage."'";
if (!empty($_POST["MaxCurrent"])){
$current=$_POST["MaxCurrent"];
$currentquery = " AND MaxCurrent >= '".$current."'";
$sql = $sql.$currentquery;
}
if (!empty($_POST["Make"]) && ($_POST["Make"] != "Any")){
$make=$_POST["Make"];
$makequery = " AND Make = '".$make."'";
$sql = $sql.$makequery;
}
if (!empty($_POST["MaxPower"])){
$power =$_POST["MaxPower"];
$powerquery = " AND MaxPower >= '".$power."'";
$sql = $sql.$powerquery;
}
if (isset($_POST["Programmable"]) && ($_POST["Programmable"] != "Any")){
$programmable =$_POST["Programmable"];
$programmablequery = " AND Programmable = '".$programmable."'";
$sql = $sql.$programmablequery;
}
if (isset($_POST["Negative"])&& ($_POST["Negative"] != "Any")){
$negative =$_POST["Negative"];
$negativequery = " AND Negative = '".$negative."'";
$sql = $sql.$negativequery;
}
if (isset($_POST["Positive"])&& ($_POST["Positive"] != "Any")){
$positive =$_POST["Positive"];
$positivequery = " AND Positive = '".$positive."'";
$sql = $sql.$positivequery;
}
if (isset($_POST["Bipolar"])&& ($_POST["Bipolar"] != "Any")){
$bipolar =$_POST["Bipolar"];
$bipolarquery = " AND Bipolar = '".$bipolar."'";
$sql = $sql.$bipolarquery;
}
if (isset($_POST["Floating"])&& ($_POST["Floating"] != "Any")){
$floating =$_POST["Floating"];
$floatingquery = " AND Floating = '".$floating."'";
$sql = $sql.$floatingquery;
}
if (isset($_POST["Topology"])&& ($_POST["Topology"] != "Any")){
$topology =$_POST["Topology"];
$topologyquery = " AND Topology = '".$topology."'";
$sql = $sql.$topologyquery;
}
$sql = $sql.";";
$result = $wpdb->get_results($sql, ARRAY_A);
if ($wpdb->last_error) {
echo 'You done bad! ' . $wpdb->last_error;
}
echo count($result)." results have been found";
echo "<table>"
foreach ($result as $row){
echo "<tr><td>" . $row["PartNumber"].
"</td><td>" . $row["MaxVoltage"] .
"</td><td>" . $row["MaxPower"].
"</td><td>". $row["MaxCurrent"] .
"</td><td>". $row["Programmable"] .
"</td><td>". $row["Negative"] .
"</td><td>". $row["Positive"] .
"</td><td>". $row["Bipolar"] .
"</td><td>". $row["Floating"] .
"</td><td>". $row["Topology"] .
"</td><td>". $row["Make"] .
"</td></tr>";
}
echo "</table>"
?>
</html>

how to apply array_diff with php and sql

Hi im unable to apply array_diff() for when user edits the stockroom detail to replace with the new result.
Here is the edit function where i call out all the variables via sql.
function einv_editStockrm($srid,$code,$name,$desc,$remark,$cat)
{
//connect to database
base_connectDatabase();
$User = base_getUserDetail($_SESSION['uID']);
$Stockroom = einv_getStockrmDetail($srid);
base_executeSQL("UPDATE einv_stockroom
SET einv_stockrm_code='" . $code . "',
einv_stockrm_name='" . $name . "',
einv_stockrm_desc='" . $desc . "',
einv_stockrm_remark='" . $remark . "',
einv_stockrm_cat = '" . $cat . "'
WHERE einv_stockrm_id=" . $srid . "");
base_addTransactionLog('Manage Stock Room', 'Edit',
"
Stock Room Code = " . $code . " ||
Stock Room Name = " . $name . " ||
Stock Room Description = " . $desc . " ||
Stock Room Remark = " . $remark . " ||
Stock Room Category = " . $cat . "
");
Here is the array_diff() function. There may be unnecessary calling and/or lack of coding..not too sure. This set of codings result in no output. The server basically crashes. Any help on this?
//oldsr is existing stockroom data
//newsr is new stockroom data through edit function
//resultsr is the end result
<?php
$StockroomGetAllDetails = array();
$arr2 = einv_getStockrmDetailFromCode($stockroomCode);
$codearr = explode(",", $arr2['einv_stockrm_code']);
$oldsr = array($codearr);
$newsr = array($codearr);
$resultsr = array_diff($newsr, $oldsr);
if(!count(array_diff($oldsr, $newsr)) && !count(array_diff($newsr, $oldsr))) {
// Arrays are equal
} else {
// Array values are different
echo $resultsr;
}
?>
This code is for redirect.
//go to stock room page
echo '<script type="text/javascript">' . "\n";
echo 'window.location="../einventory/view_stockrm.php?id='. $srid .'";';
echo '</script>';
//close the database
base_closeDatabase();
}
This set of codes able to display the new datas added and removed accordingly :)
$oldCat = $Stockroom["einv_stockrm_cat"];
$oldCatArr = explode(",",$oldCat);
$newCatArr = explode(",",$cat);
//Debugging
//print_r($oldCatArr);
//print_r($newCatArr);
$resultCatAdd = array_diff($newCatArr, $oldCatArr);
$resultCatRemove = array_diff($oldCatArr, $newCatArr);
//Debugging
print_r($resultCatAdd);
print_r($resultCatRemove);

Date is not saving to database

I'm creating an appointment plugin, in that for already members and new members are there. in already member area the date entry is not entring into db. but when displaying the variale contains the date. i'm have been checking this from morning but didn't get what is the error. my code is:
$source = mysql_real_escape_string(trim($_POST['apdatetime']));
$datetime = explode(',', $source);
$dates = $datetime[0];
$app_time = $datetime[1];
if($app_time < 12){
$app_session = 'am';
}
else{
$app_session ='pm';
}
$splitdatet = explode('/', $dates);
$yyear = $splitdatet[2];
$mmonth = $splitdatet[1];
$ddate = $splitdatet[0];
$app_date = $yyear . "-" . $mmonth . "-" . $ddate;
if ($_POST['isnewpatient'] == "false") {
//$cSql = "select * from " . WP_contact . " where appointments_c_patientid='" . trim($_POST['ptntid']) . "' ";
$cSql = "select * from " . WP_eemail_TABLE_SUB . " where eemail_patient_id='" . trim($_POST['ptntid']) . "' ";
$data = $wpdb->get_results($cSql);
if (empty($data )) {
$err = 1;
echo "<div id='message' class='aerror'>No such patient ID exists....</div>";
} else {
#$mobile = htmlspecialchars(stripslashes($data[0]->eemail_mobile_sub));
#$email = htmlspecialchars(stripslashes($data[0]->eemail_email_sub));
#$name = htmlspecialchars(stripslashes($data[0]->eemail_name_sub));
$sqlss = "insert into " . WP_Appointments .
" (`appointments_patient_id`,`appointments_date`,`appointments_time`,`appointments_session`,`appointments_reg_date`) VALUES ('" .
mysql_real_escape_string(trim($_POST['ptntid'])) . "','" .
$app_date . "','" .
$app_time . "','" .
$app_session . "',CURRENT_TIMESTAMP() )";
$dd=$wpdb->get_results($sqlss);
var_dump($dd);
echo 'Date:'.$app_date;
// return $suc;
echo "<div id='message' class='asuccess' >Request has been sent for appointment</div>";
}
}
The output of the var_dump is array[0] and $app_date is Date:2014-10-22
The db entry is
appointments_id :393
appointments_patient_id : 9999999999
appointments_date : 0000-00-00
appointments_time : 9:00
appointments_session : am
appointments_reg_date : 2014-09-25 14:21:35
could anyone please point out the mistake in the code if any??
You should convert your string into date object like this:
$app_date = date('Y-m-d',strtotime($app_date));

Warning: Invalid argument supplied for foreach() in /path/time/processing/time/viewpunlist.php on line 54

I am trying to get this php code to run. I have made it output the table, however, I am getting this error:
Warning: Invalid argument supplied for foreach() in /path/time/processing/time/viewpunlist.php on line 54
I have been able to use the $row to get the values of it before and even reassigned it later to make sure that it wasn't only executing in WHILE. I have no clue what is going on there. Line 54 is the line:
foreach ( $row as $each)
Here is the file that I am using it in. Any help is appreciated on
a) how to make this file better and
b) getting the whole foreach statement working.
Thank you in advance!
<head>
<title>View My Punches</title>
<body bgcolor="#9966FF">
<link rel="icon" type="image/ico" href="http://example.com/time/favicon.ico"/>
</head>
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
define('DB_NAME', 'name');
define('DB_USER', 'user');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'host');
$link = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($link->connect_errno > 0){
die('Could not connect: ' .connect_error());
}
$userid_value = $_POST['userid'];
$table = "tc_".$userid_value;
$checkusersql = "SELECT * FROM tc_users WHERE userid = '$userid_value'";
$usercheck = $link->query($checkusersql);
$punchessql = "SELECT * FROM $table ORDER BY id";
$result = $link->query($punchessql);
$unixtime = time() + 60*60;
$time_value = date("h:i:s A", $unixtime);
$date_value = date("m/d/Y", $unixtime);
if ($usercheck->num_rows == 0) {
echo "Sorry, " . $userid_value . " is not a valid user ID. Please try again.";
}else {
echo "Punch Report for " . $userid_value . " | Generated at " . $time_value . " on " . $date_value;
echo "<p></p>";
if ($result->num_rows == 0) {
echo "<p></p>";
echo "No punches were found for " . $userid_value . ".";
}else{
echo "<table border=1>";
echo "<tr><th>Punch ID</th><th>Time</th><th>Punch Type</th><th>Group</th><th>Department</th><th>Notes</th></tr>";
while ($row = $result->fetch_array())
{
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['time'] . "</td><td>" . $row['punchtype'] . "</td><td>" . $row['groupname'] . "</td><td>" . $row['dept'] . "</td><td>" . $row['notes'] . "</td>";
}
echo "</table>";
}
}
$differs = array();
$inout = array();
$inarray = array();
$outarray = array();
$current = array('in'=>$inarray,'out'=>$outarray,'length'=>'');
foreach ( $row as $each)
{
if ( $each['punchtype'] == 'in' )
{
if ( empty($current['in']) )
{ $current['in'] = $each; }
}
else if ( $each['punchtype'] == 'out' )
{
if ( empty($current['out']) )
{ $current['out'] = $each; }
}
if (( !empty($current['in']) && !empty($current['out'])))
{
$in = new DateTime($current['in']);
$out = new DateTime($current['out']);
$current['length'] = $in->diff($out);
$inout[] = $current;
$stamp = $inout['length'];
$stampformat = $stamp->format('%s');
$stampint = intval($stampformat);
$stampintval = $stampint/3600;
echo $stampintval;
}
}
?>
&nbsp
&nbsp
<form method="GET" action="http://example.com/time/panel.php">
<input type="submit" value="Go Home">
</form>
You need to check if the argument passed through foreach is an array.
This can be done by using the function is_array()
if (is_array($variable)) {
foreach ($variable as $item) {
}
}
Unless I am missing something, which I do a lot, it seems to me that you've already iterated through your SQL results here,
if ($usercheck->num_rows == 0) {
echo "Sorry, " . $userid_value . " is not a valid user ID. Please try again.";
}else {
echo "Punch Report for " . $userid_value . " | Generated at " . $time_value . " on " . $date_value;
echo "<p></p>";
if ($result->num_rows == 0) {
echo "<p></p>";
echo "No punches were found for " . $userid_value . ".";
}else{
echo "<table border=1>";
echo "<tr><th>Punch ID</th><th>Time</th><th>Punch Type</th><th>Group</th><th>Department</th><th>Notes</th></tr>";
while ($row = $result->fetch_array())
{
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['time'] . "</td><td>" . $row['punchtype'] . "</td><td>" . $row['groupname'] . "</td><td>" . $row['dept'] . "</td><td>" . $row['notes'] . "</td>";
}
echo "</table>";
}
}
which means that the data is no longer available because you are not using a prepared statement in order to reuse it. You should be able to run another query for the foreach.
$punchessql = "SELECT * FROM $table ORDER BY id";
$result = $link->query($punchessql);
$row = $result->fetch_array();
foreach ( $row as $each) {
//your existing code.
}

PHP is updating a database index that doesn't exist

On my main page, when someone signs-in, i have jQuery using AJAX to 'talk' to a PHP file, and the same for when they sign-out. But, when they sign out, it is supposed to update a database index with the time they left. If they database entry for their last name doesn't exist (meaning, they didn't sign-in), it is supposed to return an error. Instead, the PHP file is saying that it IS updating a non-existant database index. i am using IF statements to achieve this. and for some reason it thinks the index does exist. I've checked the database that it is writing to and the indexes it's supposed to be updating don't exist.
Here's my code:
if ($Type == 1)
{
$mysqli = new mysqli("localhost","----","----", "----");
if (!$mysqli)
$Type = 3;
$Select = $mysqli->query("SELECT Time_Out FROM " . $Date . " WHERE Last_Name = '" . $LName . "'");
$Row = $Select->fetch_assoc();
$Row2 = $Row['Time_Out'];
if ($Row2 !== "-1") $Type = 4;
if ($Type == 1)
{if ($mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'"))
{}
else
{$Type = 5;}
}
$Select = $mysqli->query("SELECT Time_In FROM " . $Date . " WHERE Last_Name='" . $LName . "'");
$Row = $Select->fetch_assoc();
$Row2 = $Row['Time_In'];
$Time2 = explode(":",$Row2);
$Hour2 = $Hour - $Time2[0];
if ($mysqli->query("SELECT Hours FROM Names WHERE Last_Name='" . $LName . "'"))
{$Select = $mysqli->query("SELECT Hours FROM Names WHERE Last_Name='" . $LName . "'");
$Row = $Select->fetch_assoc();
$Row3 = $Row['Hours'];
$Auto += 1;}
$Time3 = 60-$Time2[1];
if ($Hour != 21) $Time4 = $Min;
$Time5 = $Time3+$Time4;
if ($Time2[0]+1 != $Hour)
{$Time5 = $Time5+60;}
$Total = $Time5+intval($Row3);
if ($Type == 1)
{
if ($mysqli->query("UPDATE Names SET Hours = '" . $Total . "' WHERE Last_Name = '" . $LName . "'"))
{$Auto += 1;}
else
{$mysqli->query("INSERT INTO Names (Last_Name, First_Name, Hours) VALUES ('" . $LName . "', '" . $FName . "', '" . $Total . "')");}
}
$mysqli->close();
}
if ($Type == 1) echo "Thank you " . $FName . " " . $LName . " for signing out! See you next time!";
if ($Type == 2) echo "The entered Student ID# is invalid. Please try again!";
if ($Type == 3) echo "An unexpected error has occured. Please try again!";
if ($Type == 4) echo "You have already signed out today!" . $Auto;
if ($Type == 5) echo "You didn't sign in today.";
The UPDATE sql statement will return true, even if it doesn't find any matches (it still runs correctly, it just updates 0 rows).
Change this:
if ($Type == 1)
{if ($mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'"))
{}
else
{$Type = 5;}
}
To this:
if ($Type == 1) {
if ($mysqli->query("SELECT * FROM " . $Date . " WHERE Last_Name='" . $LName . "'")->num_rows > 0)
$mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'");
else
$Type = 5;
}
You run the select query to first determine if the record exists (if num_rows property of the result is > 0) and based on that either update the record or set your return value to 5.

Categories