SQL Syntax Error via php - php

I'm kinda new to php, this place has been a great help for me so far! Anyway, I have this code
$month = "
SELECT SUM(`duration`)
FROM `connlist` AS `month_sum`
WHERE `vatsimid` = '$vatsimid'
AND MONTH(atc_online) = " . $pmonth . "
AND YEAR(atc_online) = " . $year . "
";
That's what I get when I echo out $month
SELECT SUM(`duration`)
FROM `connlist` AS `month_sum`
WHERE `vatsimid` = '1070757'
AND MONTH(atc_online) = 07
AND YEAR(atc_online) = 13
When i use this directly into phpMyAdmin, works as a charm, but when I try to do it through a php webpage, I get the syntax error. I'm using php 5.4
Thanks!
Edit: Full Code:
<?php
//open MySQL connection
$mysql = mysqli_connect('host', 'un', 'pass', 'table')
or die ( "MySQL Error: ".mysqli_error() );
//Get and decode residents data
$jsonData = file_get_contents("link");
$phpArray = json_decode($jsonData, true);
//Start Operations
foreach ($phpArray as $key => $value) {
//Get controller hours for today
$vatsimid = $value[vatsimid];
//Get previous month
$pmonth = date("m", strtotime("-35 days") ) ;
$pmonthName = date("M", strtotime("-35 days") ) ;
echo $pmonth;
echo $pmonthName;
//This year or last year?
If (date("M") != "Jan") { //Checks that it's not January of the next year.
$year = date("y");
}
else {
$year = date("y", strtotime("-1 month") );
}
echo $year;
//Search and sum entries during last month
$month = "SELECT SUM(`duration`)
FROM `connlist` AS `month_sum`
WHERE `vatsimid` = '$vatsimid'
AND MONTH(atc_online) = " . $pmonth . "
AND YEAR(atc_online) = " . $year . "";
echo $month;
echo "</br> </br>";
$result = mysqli_query($mysql,$month);
$row = mysqli_fetch_assoc($result);
$month_sum = $row['month_sum'];
echo $month_sum;
//Updates data in atclist
$datainsert = "
UPDATE `atclist`
SET " . $monthName . "=" . $month_sum . "
WHERE vatsimid = " . $vatsimid . "";
$insert = mysqli_query($mysql,$datainsert);
if (!$insert)
{
die('Error: ' . mysqli_error($mysql));
}
}
/*

Did you mean:
SELECT SUM(duration) AS month_sum
FROM connlist
WHERE vatsimid = '1070757' AND MONTH(atc_online) = 07 AND YEAR(atc_online) = 13

It looks like $month_sum variable is not set or empty in your UPDATE query.
You can add single quotes like
$datainsert = "
UPDATE atclist
SET ".$monthName."= '".$month_sum."'
WHERE vatsimid= '".$vatsimid."'";

Related

Validating Date of birth using data from API call

I'm adding date of birth validation to my Twilio flow. Format is mm/dd/yyyy. So user would input 01021999 for Date of Birth: 01-02-1999.
I pass the input as a parameter to my validation script (PHP) on my VPS via and http request.
The problem is that if I manually set the $dob variable in my script it works, but if I pull that info from twilio there's an issue and the http request sends an error.
I know php treats numbers leading with zeros different and you have to pass them as strings. Tried using strval() to the dob variable to be able to use the input but haven't had any luck.
Works:
$account_number = 1234;
$dob = "01021999";
$dob_length = strlen($dob);
if ($dob_length = 8) {
echo $dob_month = substr($dob, 0, 2);
echo $dob_day = substr($dob, 2,2);
echo $dob_year = substr($dob, 4, 4);
echo $dob_full = $dob_month . "-" . $dob_day . "-" . $dob_year;
$sql1 = "SELECT * FROM accounts WHERE Acct_Nbr = '".$account_number."' AND Guar_DOB LIKE '%".$dob_full."%' ";
$rows = getRows($sql1);
Doesn't work (with or without turning the $dob to a string using strval() :
require_once('logs.php');
require_once('db.php');
require_once('rest.php');
$data = $_REQUEST;
start_log();
$filename = basename(__FILE__);
echo "<pre>".print_r($data,true)."</pre>";
end_log();
header("Content-Type: application/json; charset=UTF-8");
$rfields = explode(",","client_id,account_number,dob");
foreach($rfields as $rf){
if(!isset($data[$rf])){
$message = $rf." is required.";
$status = "error";
echo json_encode(compact('status','message')); die();
}
}
extract($data);
$dob_str = strval($dob);
$dob_length = strlen($dob_string);
if ($dob_length = 8) {
echo $dob_month = substr($dob_str, 0, 2);
echo $dob_day = substr($dob_str, 2,2);
echo $dob_year = substr($dob_str, 4, 4);
echo $dob_full = $dob_month . "-" . $dob_day . "-" . $dob_year;
$sql1 = "SELECT * FROM accounts WHERE Acct_Nbr = '".$account_number."' AND Guar_DOB LIKE '%".$dob_full."%' ";
$rows = getRows($sql1);
}
Try this
$dob = '01021999';
$account_number = 'whatever';
if (validateDate((string)$dob, 'dmY')) {
$date = DateTime::createFromFormat('dmY', $dob);
$final_date = $date->format('Y-m-d');
$sql1 = "SELECT * FROM accounts WHERE Acct_Nbr = '" . $account_number . "' AND Guar_DOB LIKE '%" . $final_date . "%' ";
$rows = getRows($sql1);
}
function validateDate($date, $format = 'Y-m-d H:i:s')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}

Dynamically change selected state of dropdown(s) for each row of data

I'd like to show dropdown menu(s) that contain the selected day based on what is recorded on the database.
Is there any efficient way to dynamically change the selected state of the dropdown menu based on the recorded data?
Thank you
note:
There will be many dropdown menu(s) if the recorded day of the following clinicID is more than one row
The $day is an integer, 1 for Sunday, 2 for Monday and so on
Here is mycode
// Check if any row existed
if ($count>0) {
// If row existed then start printing it
while($row = mysql_fetch_assoc($retval))
{
$day = $row['day'];
$startHour = $row['startHour'];
$startMin = $row['startMin'];
$endHour = $row['endHour'];
$endMin = $row['endMin'];
echo
"<span>" .
"<select name='day[]'>" .
"<option value='1' selected='selected'>Sunday</option>" .
"<option value='2'>Monday</option>" .
"<option value='3'>Tuesday</option>" .
"<option value='4'>Wednesday</option>" .
"<option value='5'>Thursday</option>" .
"<option value='6'>Friday</option>" .
"<option value='7'>Saturday</option>" .
"<option value='0'>Everyday</option>" .
"</select>"
//Please ignore this below
"<br>start : " . $startHour . "." . $startMin .
"<br>end : " . $endHour . "." . $endMin .
"<br><br>";
}
}
else {
}
If this is new code, please use PDO or MySQLi. mysql is depreciated and should not be used on new code php.net/manual/en/function.mysql-query.php Try this link, it helped me a lot: phpdelusions.net/pdo
Change your code to something like this (This code includes PDO implementation):
<?php
$db = new PDO('mysql:host=yourhost;dbname=dbname', 'username', 'password', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"));
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Printing schedule already in the database
$getbusinesshours = "select * from businesshours where clinicID = $clinicID";
$stmt = $db->prepare($getbusinesshours);
$stmt->execute();
$count = $stmt->rowCount();
// Check if any row existed
if ($count>0){
// If row existed then start printing it
foreach ($stmt as $row){
{
$day = $row['day'];
$startHour = $row['startHour'];
$startMin = $row['startMin'];
$endHour = $row['endHour'];
$endMin = $row['endMin'];
$i = 0;
$days = array('Everyday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
$select = '<span><select name="day[]">';
while($i <= 7){
if($i == $day){
$selected = 'selected="selected"';
}
else{
$selected = '';
}
$select = $select.
'<option value="'.$i.'"'.$selected.'>'.$days[$i].'</option'>
$i++;
}
$select = $select.'</select>';
echo $select;
//Please ignore this below
"<br>start : " . $startHour . "." . $startMin .
"<br>end : " . $endHour . "." . $endMin .
"<br><br>";
}
}
else {
}
?>
I hope this helps.

TimeClock Application: Get time difference between in/out punches

I am creating a time clock application. I have set it up so each user has their own table and it would select that table and all the rows in that table. I want to figure out how to get the difference between the in and next out punch. I am assuming that each in punch will correspond with the next out punch (the next row in the table (when ordering by ID)) I can only think of datediff. I know that is the case, but I have no clue how to implement. I am a very new php developer (Just this past week!) I have no clue how to calculate the difference between each in and out. I have looked at this question: calculate the difference of the time between In and out but couldn't figure it out there or here: mysql timeclock. Any help is appreciated.
My exact question is how to get the difference between each in and out punch in a table.
FILE:
<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', 0);
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();
$current = array('in'=>array(),'out'=>array(),'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;
#array_push($differs, );
}
}
?>
&nbsp
&nbsp
<form method="GET" action="http://example.com/time/panel.php">
<input type="submit" value="Go Home">
</form>
It will be much simpler to do this in PHP instead of in the database. Let's assume that you've pulled all the records into a variable, $allofit, and that the records are already sorted by your datetime field. Now you need to pair them up into in-out sets.
$inout = array();
$current = array('in'=>array(),'out'=>array(),'length'=>'');
foreach ( $allofit 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;
}
}
Note that your current schema can have mis-matched in-out sets. (in # 1:14, in # 1:15, out # 1:40) This code will silently drop the mismatches; you should probably do what you can to make sure mismatches don't happen in the first place.

Format Date in PHP m/d/y to Y-m-d?

I am trying to format a date string i rip from the web the date comes in as m/d/y and I need to insert it into MYSQL currently I get an error PHP Fatal error: Call to a member function format() on a non-object
Code:
<?php
include 'ganon.php';
$id = array(8573, 53816, 7746, 80748, 7714);
for($l=0; $l<sizeof($id); $l++) {
$html = file_get_dom("http://pregame.com/pregamepros/pro-bettor/picks.aspx?id=" . $id[$l]);
$picks = $html('div[class="div-table-col"]');
$array = array();
$j =0;
for($i=0; $i<sizeof($picks); $i+=8) {
$array[$j] = array("date" => trim($picks[$i]->getPlainText()),
"sport" => trim($picks[$i+1]->getPlainText()),
"pick" => trim($picks[$i+2]->getPlainText()),
"score" => trim($picks[$i+3]->getPlainText()),
"odds" => trim($picks[$i+4]->getPlainText()),
"size" => preg_replace('/\$/', "", $picks[$i+5]->getPlainText()),
"winloss" => trim($picks[$i+6]->getPlainText()),
"money" => (int)preg_replace('/\$/', "", $picks[$i+7]->getPlainText()));
$j++;
}
//enter picks into database
//make sure we do not add picks we already have
$mysqli = new mysqli("host", "user", "pass", "db");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
exit();
}
if($id[$l] == 8573) {
//$query = "SELECT `date` FROM `db`.`vegasrunner` where date=" . date('Y-m-d');
for($i=0; $i<sizeof($array); $i++) {
$query = "SELECT `date`,`pick` FROM `db`.`vegasrunner` where date=" . "'" . $array[$i]["date"] . "'" . " AND pick=" . "'" . $array[$i]["pick"] . "'";
$result = $mysqli->query($query);
$row = $result->fetch_row();
if(sizeof($row) < 1) {
$result->close();
$date = new DateTime();
$date = DateTime::createFromFormat('m/d/y', $array[$i]["date"]);
//$date = $array[$i]["date"];
$sport = $array[$i]["sport"];
$pick = $array[$i]["pick"];
$score = $array[$i]["score"];
$odds = $array[$i]["odds"];
$size = $array[$i]["size"];
$winloss = $array[$i]["winloss"];
$money = $array[$i]["money"];
echo $date->format('Y-m-d');
$query = "INSERT INTO `db`.`vegasrunner` (`date`, `sport`, `pick`, `score`, `odds`, `size`, `winloss`, `money`) VALUES (" . "'" . $date->format('Y-m-d') . "'" . ", '$sport', '$pick', '$score', '$odds', '$size', '$winloss', '$money')";
$mysqli->query($query);
}
} }
The only plausible explanation I can see is if createFromFormat() is failing, which might happen if the input date isn't in the format you're expecting.
Check that the input string is in the format you think, and alter your code to include a check for failure at the createFromFormat() call.
I ended up writing my own function to parse the date. It turns out there was a hidden space before the month.
function formatDate($date) {
//date = 07/12/13
$date = explode('/', $date);
//for some reason in ubuntu month had a space had to get last 2 characters
$month = substr($date[0], -2);
$day = trim($date[1]);
$year = date('y') == $date[2] ? date('Y') : date('Y');
return $year . "-" . $month . "-" . $day;
}

Query just day month year from now()

I am inserting a date into a database with NOW() then I query the result. Here is the code.
function get_content($id = ''){
if($id != ''):
$id = mysql_real_escape_string($id);
$sql = "SELECT * FROM cms_content WHERE id = '$id'";
$return = '<p>Back to Content</p>';
else:
$sql = "SELECT * FROM cms_content ORDER BY id DESC";
endif;
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res) != 0):
while($row = mysql_fetch_assoc($res)) {
echo '<h1> ' . $row['title'] . '</h1>';
echo '<p>' . stripslashes($row['body']) . '</p>';
**echo '<p>' . $row['date_posted'] . '</p>';**
}
else:
echo '<p> You broke it!, this post dosn\'t exsist!';
endif;
echo $return;
The
echo '<p>' . $row['date_posted'] . '</p>';
is where I echo the date. When I echo this from the database I get 2012-07-25 19:00:46, because that's what is in the database. My question is how would I echo the day, then echo the month, then the year. Ideally these would all be separate echos so I could style each differently.
This is alot more handy and less code.
$date = new DateTime($row['date_posted']);
$day = date->format('d');
$month = date->format('F');
$year = date->format('Y');
Resource: http://www.php.net/manual/en/class.datetime.php
Since the format is known, you can simply use this:
list($year,$month,$day) = explode("-",substr($row['date_posted'],0,10));
Then you can echo those variables however you want.
$date = strtotime($row['date_posted'];
echo date('d', $date);
echo date('m', $date);
echo date('Y', $date);
or
$date = new DateTime($row['date_posted']);
echo $date->format('Y');
etc
You would use php built in date() function: http://us.php.net/manual/en/function.date.php
echo "<p>".date('j M, Y', $row['date_posted'])."</p>";
// would output <p>25 July, 2012</p>
This can be modified into just about any format that you would like.
Another option is to do that directly in SQL, using the *date_format* function: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

Categories