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();
?>
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= ...
So I've got a form which has loads of different things that go into a database, when I added the date and time checkers into the form, they go into the database as a string
(Example: "2018-05-29" "10:47:00.000000" is how they look when they go in "Here")
I want to reformat these so that when they are inserted into the database they show up as actual words
(Example: "29th May 2018" "Tuesday 29th May" "10:47 AM/PM" something along these lines)
So that when I use my php and grab the data from the database and display it on the page it'll show the actual words instead of just numbers.
(Note: Yes I've tried going the other way around and converting it when it comes out of the database, but because of the way I'm displaying things, it won't work)
<?php
$servername = "";
$username = "";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Select Database
mysqli_select_db($conn, "czt_database");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$game = mysqli_real_escape_string($conn, $_POST['Game']);
$map = mysqli_real_escape_string($conn, $_POST['Map']);
$challenge = mysqli_real_escape_string($conn, $_POST['Challenge']);
$extra = mysqli_real_escape_string($conn, $_POST['Extras']);
$players = mysqli_real_escape_string($conn, $_POST['Players']);
$entryfee = mysqli_real_escape_string($conn, $_POST['Type']);
$entrycost = mysqli_real_escape_string($conn, $_POST['Fee']);
$prizemoney = mysqli_real_escape_string($conn, $_POST['Prize']);
$entrymax = mysqli_real_escape_string($conn, $_POST['Entries']);
$startdate = mysqli_real_escape_string($conn, $_POST['Start-date']);
$starttime = mysqli_real_escape_string($conn, $_POST['Start-time']);
$enddate = mysqli_real_escape_string($conn, $_POST['End-date']);
$endtime = mysqli_real_escape_string($conn, $_POST['End-time']);
$rules = mysqli_real_escape_string($conn, $_POST['Rules']);
$sql = "INSERT INTO tournaments (tournament_game, tournament_map, tournament_challenge, tournament_extra, tournament_players, tournament_entryfee, tournament_entrycost, tournament_prize, tournament_entrymax, tournament_startdate, tournament_starttime, tournament_enddate, tournament_endtime, tournament_rules)
VALUES ('$game', '$map', '$challenge', '$extra', '$players', '$entryfee', '$entrycost', '$prizemoney', '$entrymax', '$startdate', '$starttime', '$enddate', '$endtime', '$rules');";
mysqli_query($conn, $sql);
header("Location:../Create-A-Tournament.html");
?>
You can use code something like below
$startDate=date("l dS M Y", strtotime($_POST['start-date'])); //This will give result as Tuesday 7th May 2018.
$startTime=date("h:i A", strtotime($_POST['start-time'])); // This returns time as 04:56 AM/PM
$startdate = mysqli_real_escape_string($conn, $startDate);
$starttime = mysqli_real_escape_string($conn, $startTime);
Then you can use the above variables to store in DB.
Hope it helps.
I am trying to echo some text in PHP if current time IST is more than time stored in Mysql
Stored Time: 2017-09-24 16:36:15
Current Time (IST): 2017-09-24 16:46:15
I tried:
<?php
require_once 'vclass.php';
require_once 'message.php';
$vreg = new Validation();
$stmt = $vreg->runQuery("SELECT * FROM validation WHERE vid=1");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$vusrmaile = $row['svdate'];
$vusrmail = $row['vdate'];
date_default_timezone_set('Asia/Calcutta');
$date = date('Y-m-d h:i:s ', time());
if($date > $vusrmail){
$msg = "
<div class='alert alert-error'>
<strong><center>Process</center></strong>
</div>
";
}
?>
From the above code, I am not getting the result as expected.
You can convert the timestamp from your MySQL database into Unix Time and then compare with the current time (represented in Unix Time):
<?php
require_once 'vclass.php';
require_once 'message.php';
$vreg = new Validation();
$stmt = $vreg->runQuery("SELECT * FROM validation WHERE vid=1");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$vusrmaile = $row['svdate'];
$vusrmail = strtotime($row['vdate']); // Convert MySQL datetime string to Unix Time (this will depend on current timezone)
$date = time(); // Current Unix time (this is independent of timezone)
if($date > $vusrmail){
$msg = "
<div class='alert alert-error'>
<strong><center>Process</center></strong>
</div>
";
}
?>
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.
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);
}
}