I am trying to switch over from mysql to mysqli as I have been getting a large amount of grief for using mysql to start. I have been looking at examples and thought that I had it right. However, I don't. When I try to add a punch, it doesn't add. I just get a white screen. No error message or the redirect that I request after the punch is added. I have edited the file to hide some sensitive data, but nothing neccessary to trouble shoot. I have looked at the examples multiple times and I can not seem to figure out what is wrong. The punches are added just fine when using mysql. If any one can enlighten me on how to fix this, I would greatly appreciate it. Thank you!
<head>
<title>Process Punch</title>
<body bgcolor="#9966FF">
<link rel="icon" type="image/ico" href="favicon path"/>
</head>
<?php
define('DB_NAME', 'dbname');
define('DB_USER', 'dbuser');
define('DB_PASSWORD', 'dbpass');
define('DB_HOST', 'dhbost');
$link = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($link->connect_errno > 0){
die('Could not connect: ' .$link->connect_error);
}
$userid_value = $_POST['userid'];
$punchtype_value = $_POST['punchtype'];
$group_value = $_POST['group'];
$dept_value = $_POST['dept'];
$notes_value = $_POST['notes'];
$table = "tc_".$userid_value;
$unixtime = time();
$unixtime = $unixtime + 3600;
$date_value = date('m/d/Y h:i:s A', $unixtime);
$checkusersql = "SELECT * FROM tc_users WHERE userid = '$userid_value'";
$usercheck = $link->query($checkusersql);
if ($usercheck->num_rows) == 0) {
echo "Sorry, " . $userid_value . " is not a valid user ID. Please try again.";
}else {
$sql = "INSERT INTO $table (time, punchtype, groupname, dept, notes) VALUES ('$date_value','$punchtype_value', '$group_value', '$dept_value', '$notes_value')";
$link->query($sql);
}
header( 'Location: punch path');
$link->close();
?>
Two things:
if ($usercheck->num_rows) == 0)
^-- this one should be removed
has one bracket too many.
Use ($usercheck->num_rows == 0)
As for your date/time issue; you're using m/d/Y h:i:s instead of date("Y-m-d H:i:s")
MySQL is expecting a numeric representation of the format 2014-07-07 19:30:13 as an example.
So do date("Y-m-d H:i:s A") or date("Y-m-d H:i:s") which is why you're getting all zeros.
Use either H or h: (as per the manual)
h - 12-hour format of an hour with leading zeros 01 through 12
H - 24-hour format of an hour with leading zeros 00 through 23
You could leave it the way it is and set your time column to VARCHAR but that would defeat the purpose.
I believe your script is failing on the mysqli query, but you don't have any way of knowing because there is not error reporting in place. Try this and see what it shows.
$checkusersql = "SELECT * FROM tc_users WHERE userid = '$userid_value'";
if (!$usercheck = $link->query($checkusersql)) {
printf("Error: %s\n", $usercheck->error);
}
if ($usercheck->num_rows == 0) {
echo "Sorry, " . $userid_value . " is not a valid user ID. Please try again.";
}else {
$sql = "INSERT INTO $table (time, punchtype, groupname, dept, notes) VALUES ('$date_value','$punchtype_value', '$group_value', '$dept_value', '$notes_value')";
if (!$link->query($sql)) {
printf("Error: %s\n", $link->error);
}
}
Related
Need get info, is EndDate expired or not (EndDate is row, where typed info about date of buyed user premium)
connectuser2db();
$bile_sql = "SELECT EndDate FROM tbl_rfuser WHERE Serial = '" . $userdata['serial'] . "'";
if (!($bile_result = mssql_query($bile_sql))) {
echo "Unable to select query the Billing table";
exit;
}
$bilel = mssql_fetch_array($bile_result);
$userdata['Enddate'] = $bilel['EndDate'];
$t_logd = $bilel['EndDate'];
echo $t_logd;
result like Jul 14 2020 02:36:00:000PM (if EndDate in smalldatetime data type)
$time = date("Y-m-d H:i:s");
echo $time;
result like 2020-07-15 14:51:21
If i use $time in this row, it update enddate to curent time:
$t_login = $userdata["lastlogintime"]; // last user login in game (from mssql) Jul 15 2020 02:36:00:000PM
$t_logd = $bilel['EndDate']; // Premium EndDate (from mssql) Jul 14 2020 02:36:00:000PM
$time = date("Y-m-d H:i:s"); // current time (from php) like 2020-07-15 14:51:21
if( $t_logd <= $t_login )
{ connectuser2db();
$user_update = "UPDATE tbl_rfuser SET EndDate='" . $time . "' WHERE Serial= '" . $userdata["serial"] . "'";
mssql_query($user_update); }
It succesfully compare "lastlogin" and "enddate", and if account is new or user be online last time before EndDate expired - change EndDate to current time, that succesfully takes from $time.
But if user login after EndDate, it not works
Want this compare:
if( $t_logd <= $t_login ) //working now
Change to compare like:
if( $t_logd <= $time ) // not working now
Help please
How can I take current time from mssql or change $time for something, that can compare?
Tried strtotime, but can't do it (sql server check it in miliseconds, but my php old and can't use date("Y-m-d H:i:s:v") format)
Note, that the MSSQL PHP extension is not available anymore on Windows with PHP 5.3 and removed in PHP 7.0.0, but if you want a solution, you may try the following:
Specify how the datetime values are returned from the SQL Server by setting the mssql.datetimeconvert option in your php.ini file to Off. When this option is On the datetime values are returned converted to SQL server settings. When this option is Off the datetime values are returned in YYYY-MM-DD hh:mm:ss format.
Use date_create() to create and compare the dates as PHP datetime objects.
The next simplified example demonstrates this approach (tested with PHP 5.2.9):
<?php
// Connection
$server = 'server,port';
$username = 'username';
$password = 'password';
$database = 'database';
$conn = mssql_connect($server, $username, $password);
if (!$conn) {
echo "Error (sqlsrv_connect): ".mssql_get_last_message();
exit;
}
mssql_select_db($database, $conn);
// Statement
$sql = "SELECT DATEADD(day, -1, GETDATE()) AS [DateTime]";
$stmt = mssql_query($sql, $conn);
if (!$stmt) {
echo "Error (sqlsrv_query): ".mssql_get_last_message();
exit;
}
// Results
while ($row = mssql_fetch_assoc($stmt)) {
$datetime1 = date_create($row['DateTime']);
}
$datetime2 = date_create();
// Compare dates
echo ($datetime1 <= $datetime2) ? 'Result: <=' : 'Result: >';
// End
mssql_free_result($stmt);
mssql_close($conn);
?>
Just use GETDATE:
UPDATE tbl_rfuser SET EndDate=GETDATE() WHERE Serial= ...
My database data are table of dates. I want to create a list to report entries of expired dates.
for that, I used the following php script:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Batch#, Date1, Date2 FROM users";
$result = $conn->query($sql);
$now= strtotime("-1 Months");
if ($result->num_rows > 0) {
$Date1= $row["Date1"];
$Date2= $row["Date2"];
echo "<table id='t1'><tr><th>Alert</th><th>Action</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
if($Date1 >= $now)
echo "<tr><td>One month or less to expiry date of product with batch# " . $row["Batch#"]. "</td><td>Please take an action</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
I kept getting an error: "Notice: Trying to get property of non-object in C:\xampp\htdocs\Testing\AlertTest.php on line 17
0 results"
I couldn't figure out what that means or how to fix it. I've been this method before and this is the first time I get such an error.
As you are comparing the dates, you have to mind that the both dates are in same format (Date string or time stamp). For comparison both the format as timestamp is best. So using the PHP function timestamp() just convert your database time to a unique number.
Your comparison:
if($Date1 >= $now){
....
}
Here The $Date1 is a string like '2016-07-07' and the $now something like '1468057029', so the condition not goes correct / success. What you have to do is just convert both time into timestamp and execute the comparison.
$Date1 = strtotime($row["Date1"]);
$Date2 = strtotime($row["Date2"]);
Hope this helped you.
EDIT:
So I looked up PDO Insert statements. Still kind of confusing. so now my code reads:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test14.php</title>
</head>
<?php
$servername = "server";
$username = "username";
$password = "password";
$dbname = "dbname";
//Setup for endDate value
date_default_timezone_set("America/Denver");
$startDate = new DateTime('12:00:00');
echo "<p>Today is: {$startDate->format( 'l Y-m-d g:i:s' )}</p>";
// N gives a numeric day to the days of the week
// 2 means Tuesday
while ( $startDate->format( 'N' ) != 2 )
$startDate->modify( '+1 days' );
echo "<p>Start date is: {$startDate->format('l Y-m-d g:i:s')}</p>";
//Set endDate at Tuesday
$endDate = $startDate ->modify("+2 Weeks");
echo "<p>End date is: {$endDate->format('l Y/m/d g:i:s')}</p>";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $conn->prepare("INSERT INTO wp_awpcp_ads (ad_enddate)
VALUES (:end_date)
");
$sql->bindParam(':end_date',strtotime($endDate), PDO::PARAM_STR);
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
<body>
</body>
</html>
I'm getting 2 warnings:
Warning: strtotime() expects parameter 1 to be string, object given in [site_url]/test14.php on line 40
Warning: PDO::exec() expects parameter 1 to be string, object given in [site_url]/test14.php on line 42
New record created successfully
and I'm still getting all zeros in my table. Does it matter if it's a wordpress table? I'm not having any issues with the now() functions just DateTime()functions. Is there another way to setup a date like this?
I have been trying to find a way to add a custom end date value to a mysql database field with the type "DateTime"
Specifically, the customer wants all ads to be "ended" on a tuesday at noon following 2 weeks of activity. so far I've been helped at phphelp forums and have this snippet:
<?php
$servername = "server";
$username = "username";
$password = "password";
$dbname = "dbname";
//Setup for endDate value
date_default_timezone_set("America/Denver");
$startDate = new DateTime('12:00:00');
echo "<p>Today is: {$startDate->format( 'l Y-m-d H:i:s' )}</p>";
// N gives a numeric day to the days of the week
// 2 means Tuesday
while ( $startDate->format( 'N' ) != 2 )
$startDate->modify( '+1 days' );
echo "<p>Start date is: {$startDate->format('l Y-m-d H:i:s')}</p>";
//Set endDate at Tuesday
$endDate = $startDate ->modify("+2 Weeks");
echo "<p>End date is: {$endDate->format('l Y/m/d H:i:s')}</p>";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO wp_awpcp_ads
(
ad_contact_name,
ad_contact_email,
ad_contact_phone,
ad_title,
ad_category_id,
ad_item_price,
ad_details,
disabled,
disabled_date,
ad_postdate,
ad_startdate,
ad_last_updated,
ad_enddate
)
VALUES
(
'$_POST[name]',
'$_POST[email]',
'$_POST[phone]',
'$_POST[title]',
'$_POST[category]',
'$_POST[price]',
'$_POST[details]',
1,
now(),
now(),
now(),
now(),
$endDate->format('Y-m-d H:i:s'))";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
This works fine except my ad_enddate row shows 0000-00-00 00:00:00 and i'm at wit's end to solve this issue. I've changed my code to msqli to pdo, and nothing. I'm completely new to php and need this by last week.
this enter link description here can help You with date problem, I think it's due to $end_date format.
And this is great answer about SQL Injections in PHP :)
enter link description here
hey everyone thanks for the help. I was able to get it working after rewriting my code. the key I was missing to make it work is: '".$tuesday."'
here's my final code:
//----------------------------------------------------
//today is Tuesday
if (2 == date('N')){
$tuesday = time('12:00:00');
}else{
$tuesday = strtotime('last Tuesday');
}
$tuesday = strtotime('+2 week', $tuesday);
//echo date('d-m-Y', $tuesday) . '<br>';
$tuesday = date("Y-m-d H:i:s", $tuesday);
//----------------------------------------------------
if(isset($_REQUEST['submit_ad']))
{
// prepare and bind
$stmt = $conn->prepare("INSERT INTO wp_awpcp_ads
(
ad_contact_name,
ad_contact_email,
ad_contact_phone,
ad_category_id,
ad_title,
ad_details,
disabled,
disabled_date,
ad_postdate,
ad_startdate,
ad_enddate
)
VALUES
(?,?,?,?,?,?,1,now(),now(),now(),'".$tuesday."')");
$stmt->bind_param("ssssss",$name,$phone,$email,$category,
$adtitle,$addetails);
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$category = $_POST['category'];
$adtitle = $_POST['adtitle'];
$addetails = $_POST['addetails'];
$stmt->execute();
echo "New ads created successfully";
}
$conn->close();
?>
Hi friends i have a php program where user can upload excel file and data w illbe stored in php database, it works as i expected but the problem is date stored in database is totally different from what i entered in excel
i have used the following codes to read the value from excel..
include("excel/reader.php");
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('CP1251');
$data->read($_POST['upload']);
$conn = mysql_connect("localhost","root","");
mysql_select_db("mydatabase",$conn);
$a="TRUNCATE TABLE `sheet`";
mysql_query($a);
for ($x = 2; $x <= count($data->sheets[0]["cells"]); $x++)
{
$inv = $data->sheets[0]["cells"][$x][1];
$ds = $data->sheets[0]["cells"][$x][2];
$dosstr=strtotime($ds);
$dos=date('Y-m-d',$dosstr);
$ptname = $data->sheets[0]["cells"][$x][3];
$bal = $data->sheets[0]["cells"][$x][4];
$proname = $data->sheets[0]["cells"][$x][5];
$sql = "INSERT INTO sheet (INV,DOS,PTNAME,BAL,PROV)
VALUES ('$inv','$dos','$ptname','$bal','$proname')";
mysql_query($sql);
}
header('location:exsheet2.php');
?>
i have the following dates stored in excel
9/1/2014,
28/12/2013 ,
27/9/1991 ,
1/1/2015 ,
31/12/2014 ,
1/1/2012 ,
5/9/2001 .
but what is being stored in database is
1970-01-01 ,
1970-01-01 ,
1970-01-01 ,
1970-01-01 ,
1970-01-01 ,
1970-01-01 ,
1970-01-01 ,
1970-01-01.
please assist me with this issue thanks
for ($x = 2; $x <= count($data->sheets[0]["cells"]); $x++)
{
$inv = $data->sheets[0]["cells"][$x][1];
$ds = $data->sheets[0]["cells"][$x][2];
echo $ds;
echo "<br>";
if(ctype_digit($ds))
{
date_default_timezone_set("Asia/Kolkata");
$dDate = date_create('1900-01-01');
$dDate = date_modify($dDate, '+'.($ds-2).' day');
if($dDate!="")
{
$dos = date_format($dDate,'Y-m-d');
echo "IF".$dos;
echo "<br>";
}
else
{
$dos=$ds; //not able to convert date so show it directly
echo "Else".$dos;
echo "<br>";
}
}
else
{
$dos=$ds;
echo"if Else".$dos;
}
$ptname = $data->sheets[0]["cells"][$x][3];
$bal = $data->sheets[0]["cells"][$x][4];
$proname = $data->sheets[0]["cells"][$x][5];
$sql = "INSERT INTO sheet (INV,DOS,PTNAME,BAL,PROV)
VALUES ('$inv','$dos','$ptname','$bal','$proname')";
mysql_query($sql);
}
Found the actual problem is in your date function. You cannot use these php functions coz these are for unix timestamp. And excel returns date as integer values. The no of days since 1/1/1900, including first and last day
so replace these lines:
$dosstr=strtotime($ds);
$dos=date('Y-m-d',$ds);
to
date_default_timezone_set("Asia/Kolkata");
$dDate = date_create_from_format('Y-m-d', '1900-01-01');
$dDate=date_add($dDate, date_interval_create_from_date_string(($ds-2).' days'));
$dos=$dDate->format('Y-m-d');
PHP 5.2 version:
date_default_timezone_set("Asia/Kolkata");
$dDate = date_create('1900-01-01');
if($dDate = date_modify($dDate, '+'.($ds-2).' day'))
$dos = date_format($dDate,'Y-m-d');
else $dos=$ds; //not able to convert date so show it directly
OR safe code:
if(ctype_digit($ds)){
date_default_timezone_set("Asia/Kolkata");
$dDate = date_create('1900-01-01');
$dDate = date_modify($dDate, '+'.($ds-2).' day');
if($dDate!="") //if($dDate) //is_a($dDate,'DateTime')) //get_class($dDate)=='DateTime' //if ($dDate instanceof DateTime)
$dos = date_format($dDate,'Y-m-d');
else $dos=$ds;
}
else $dos=$ds;
And reason of problem of getting incorrect date which have day greater than 12 is: You have dates stored in excel as Indian dates. But your laptop's default date and time are US or UK...
you need to change it first (in Region and Language Settings).
1) click on time shown at right of taskbar, in windows.
2) under the calendar you'll see a link "change date and time settings". open it.
3) click "change date and time" button -> then click change calendar settings link.
4) probably two more window will open. close the customized format window and go to "Region and Language".
5) Select "English(India)" as Format and "dd-MM-yyyy" as short date.
6) click OK. Then try again, if any problem, comment.
Print the sql query and check what values are inserted in the query. The date format should be "Y-m-d".
Just remove all the formatting from the date column of the excel sheet. Then try again. This may help you PHP Spreadsheet_Excel_Reader always reading date as Nov 30, 1999, http://dirtyhandsphp.blogspot.in/2012/03/phpexcelreader-uses-and-problems.html
So in my database i've got regdate (date type), but no matter what date it is, the code keeps returning 1.
<?php
$con = mysqli_connect("localhost","root","","login");
if (mysqli_connect_error()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM users");
$row = $result->fetch_array();
$date1 = new DateTime($row['regdate']);
$date2 = new DateTime("now");
$interval = $date1->diff($date2);
echo "It has been " .$interval->d." days ";
//$interval is supposed to be difference between regdate and todays date
I hope I'm not missing something stupid. Thank you for your anwers.
SOLVED
I belive this might be more easier.
SELECT DATEDIFF(NOW(),$row['regdate']);
and I think you need a while loop to find all the records.