What I'm trying to do is insert credit card info from a form to my mysql database.
First of all,
the input format for the expire date will be MM / YY(with or without spaces) on the form and i'm trying to concat the "20" string to the year but I always get "20 YY" as a result, which cannot be recognised from mysql as a date.
I want to get the expire date to fit a format so later on it can be altered into a MySQL format. Any ideas?
This is my code so far:
<?php
$cc_number="";
$cc_expire="";
$cc_cvc="";
$cc_number=$_POST['number'];
$cc_expire=$_POST['expiry'];
$cc_cvc=$_POST['cvc'];
$cc_pid=$_SESSION['pid'];
/*edit the expire date*/
$pieces=explode("/", $cc_expire);
$expire_dd="01";
$expire_mm=$pieces[0];
$expire_yy="20".$pieces[1];
$expire_yy=trim($expire_yy, "\x00..\x1F");
//$cc_expire = $expire_yy.$expire_mm.$expire_dd;
//$cc_expire = date('Y-m-d', strtotime(str_replace('-', '/', $cc_expire)));
echo "expire_yy = ".$expire_yy;
//echo "cc_expire = ".$cc_expire;
if (isset($_POST["submit"])) {
if (empty($cc_number) || empty($cc_cvc) || empty($cc_expire)) {
echo "<p align='center'><font color='red'><br><br><br><br>All fields are mandatory.</font></p>";
}
else {
$cc_expire = date('Y-m-d', strtotime($cc_expire));
$sql = "INSERT INTO credit_card (credit_card_number, cvc, expiration_date, pid)
VALUES ('$cc_number', '$cc_cvc', '$cc_expire', $cc_pid)";
if ($dbconn->query($sql)) {
//echo "<script> window.location.assign('../card.php'); </script>";
}
else {
echo "<p align='center'><font color='red'><br><br><br><br>Something went wrong.</font></p>";
}
}
}
?>
I want for all the cards to get a mySql DATE format which will be 01-MM-YYYY.
strtotime() should work for you. learn more here http://www.w3schools.com/php/func_date_strtotime.asp
Depending on how the data looks like in $cc_expire you may need to parse it first so this first:
$cc_expire = "28-".str_replace(" ","-",cc_expire);
Which should give dd-mm-yyyy format (I've had a issue using '/' before when changing dateformat)
Then do:
$mysqldate = date("Y-m-d H:i:s", strtotime($cc_expire));
This should convert the cc_expire to mysql format ready for insertion.
Related
Ive checked the leads here and have not found the right solution,
<?php
$mysqldate = $row['callbackdate'];
$phpcurrentdate = strtotime( $mysqldate );
if ( $phpcurrentdate == date("Y-m-d") ) {
echo $row['last_name'];
}else{
echo "Nothing";
}
?>
The date field in sql is date and the format is YYYY-mm-dd. The answer always being returned is "Nothing". I know this sort of question has many variations but Ive had no luck finding this type. Im not looking for a range sort just a simple match is all... and the data $row['callbackdate']is functioning as Ive tested all other connections.
So Id appreciate any help! Thanks,
Les
$mysqldate = "2017-08-28"; //example
$phpcurrentdate = DateTime::createFromFormat('Y-m-d', $mysqldate); //put your format
$today= new DateTime("now");
if ( $phpcurrentdate == $today ) {
echo 'last_name';
}else{
echo "Nothing";
}
The dates are stored as string in your database. As possible solution to this is formatting both as dateTime for example:
$today = date('Y-m-d H:i:s');
$databaseDate = '2017-08-06 20:50:38';
var_dump(new DateTime($today) > new DateTime($databaseDate)) // returns true
var_dump(new DateTime($today) < new DateTime($databaseDate)) // returns false
Another way to do this is to make your columns type in the database a DateTime. This way you only have to format the current date as a DateTime and then you can compare them
I require a date to be entered in the correct format, and if it isn't then an error is shown. My PHP program looks like this:
if (empty($_POST["date"])) {
$dateErr = "Date is required";
} else {
$date = test_input($_POST["date"]); etc
This is just the standard way of showing error for an improper date format. But my problem is that even though an error is shown, there is nothing that is stopping that date (in the wrong format) from being passed into the database. When I check my database, I see that date and it is not what I want. Is there a way that a date written in the wrong format can be blocked from ending up on my database? Like a filter, I mean.
Use the powerful DateTime class, DateTime::createFromFormat is useful here, it returns a new DateTime instance or FALSE on failure.
So it will go this way:
if (empty($_POST["date"])) {
$dateErr = "Date is required";
} else {
$format = 'Y-m-d'; // write your format here
$date = DateTime::createFromFormat($format, $_POST["date"]);
if($date)
{
// add to database
}
Also your database field should be set as datetime which has the format Y-m-d, so before you insert it you have to format it to Y-m-d using PHP, like:
$date->format('Y-m-d');
That will return a proper string to insert in your database.
You should use a function to check whether the date given is in the appropriate format before you begin your db transaction. You can do this in the following approach using regular expressions as #Subhanker mentioned to match to the following format YYYY-MM-DD:
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $_POST['date']))
{
//Start DB transaction here
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$form_date = mysqli_real_escape_string($con, $_POST['date']);
$sql="INSERT INTO dates_table (dates)
VALUES ('$form_date')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}else{
$dateErr = "Date is required";
}
Please let me know if you have any questions!
You can use strtotime to do your checking. No regex needed
$date = strtotime($_POST["date"]);
if($date === false) $dateErr = "Unrecognized Date format";
else $date = date('m/d/Y', $date); // Set your own date format here
if (preg_match("/^(19|20)\d\d[\-\/.](0*[1-9]|1[012])[\-\/.](0*[1-9]|[12][0-9]|3[01])$/", $date )){//This will match the input in format YYYY-MM-DD
//Date ok
}else{
//Invalid Date
}
How do I know in PHP that the date entered by the user in future than the current date.
i.e
if($current_date<$future_date)
{
//do all the success actions here
}
else
{
//show the user that they have selected a date in the past.
}
Well you first need to convert the date string using strtotime() function and then check if future date value is greater than current date value.
Here is the code snippet:
$today_date=date('Y-m-d H:i:s');
$current_date=strtotime($today_date);
$future_date=strtotime($future_date);//retrieved from user's input
Now you can call your function:
if($current_date<$future_date)
{
//do all the success actions here
}
else
{
//show the user that they have selected a date in the past.
}
I suppose you know the date format in which your users enters their date cos it will help you understand what date format you will be working with. But irrespective of whatever date format you are working with, you can always convert it to a more suitable one using:
strtotime()
Below is an example of checking a future date (working strictly with date)
$currentDate = date("Y-m-d");
$userFututeDate = "2014-05-08";
if($userFututeDate > $currentDate){
echo 'You have selected a date in the future';
}
else{
echo 'You have selected a date in the past.';
}
Below is another example of checking a future date (working with date and time)
$currentDateTime = date("Y-m-d H:i:s");
$userFututeDateTime = "2014-05-07 05:05:08";
if($userFututeDateTime > $currentDateTime){
echo 'You have selected a date in the future';
}
else{
echo 'You have selected a date in the past.';
}
Perhaps, you need to understand how to play around with strtotime(), find some sample below:
$dateVar = "25-07-2014 05:05:08";
echo date("F j Y", strtotime($dateVar));
echo '<br><br>';
echo date("Y-m-d", strtotime($dateVar));
echo '<br><br>';
echo date("F jS Y, g:i a", strtotime($dateVar));
Check out for more on strtotime()
When I retrieve a date from a my_sqli query and format it it becomes one day forward. The date is saving correctly to the server, and echoing it before the new format is correct.
$date = "SELECT date FROM blogtable WHERE id = $artID";
$dateEx = mysqli_query($con, $date);
while($dateGet = mysqli_fetch_array($dateEx))
{
//This is in YYYY-mm-dd
$dateGet['date'];//If I echo this, it is correct
}
$source = $dateGet;
$newDate = new DateTime($source);
echo $newDate->format('M-d-Y');
So for example if I tried to use it today(the 24th), it would save correctly, but after the format, display as the 25th.
Wrikken's suggestion worked, changing the statement in the while to $source=$dateGet['date']; and deleting the $source = $dateGet;.
Got stuck in a complex or maybe stupid problem. I am getting a query from mysql, and then trying to compare a date column with a PHP data which i formatted to the same format i.e "Y-m-d" it always results in no match, although i see there is a match.. and it gets the right result set too.
<?php
date_default_timezone_set('America/Los_Angeles'); // set timezone to our timezone
$constantTime = time(); // get value of time in constant
$appDate = date("Y-m-d", $constantTime); //that defines php time variable -
$queryDate = "SELECT * FROM date WHERE date='$appDate'";
$resultDate = mysql_query($queryDate) or die("Sorry Website Under Maintainence");
$recordDate = mysql_fetch_array($resulDate);
if ($appDate == date("Y-m-d", strtotime($recordDate['date']))) {
echo "MATCH ";
$dateID = $recordDate['dateID'];
} else {
mysql_query("insert into date(date) values('$appDate')")or die("Database write error1");
$resultDate = mysql_query($queryDate) or die("Sorry Website Under Maintainence");
$recordDate = mysql_fetch_array($resultDate);
echo "NO MATCH ";
$dateID = $recordDate['dateID'];
}
This is always triggering the else, i tried === instead of ==, i tried strcmp
As i assume you're comparing datetime field, you have two possibilities:
Cast field to date:
$queryDate = "SELECT * FROM your_table WHERE date(your_date_field) = date('$appDate')";
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date
or
Modify your date format to be ISO compatible:
$appDate = date("Y-m-d H:i:s", $constantTime); //it defines date in format 2015-03-14 15:00:00
$queryDate = "SELECT * FROM your_table WHERE your_date_field='$appDate'";
See also this question