submitting PHP - HTML DATE to MySQL DATE - php

i would like to help with my code how to edit HTML input date into MySQL TIMESTEMP format cause my SQL code is invalid and data are not added to my database, Thanks for help
also i asking to check this code on bottom cause 2nd SQL deppends on 1st SQL, thanks
if (isset($_POST['pridaj_anime_submit'])) {
$sql_vloz_anime = "INSERT INTO anime (a_name, a_year, a_translated_min, a_translated_max, a_rate_min, a_rate_max, a_edit, a_condition)
VALUES ('$_POST[nazov]', '$_POST[rok]', '0', '$_POST[pocet]', '8', '10', '$_POST[preklad]', '$_POST[stav]')";
mysqli_query($connect_to_db , $sql_vloz_anime);
$sql_ziskaj_a_id_pridaneho_anime = "SELECT * FROM anime WHERE a_name = '$_POST[nazov]'";
$run_sql_ziskaj_a_id_pridaneho_anime = mysqli_query($sql_ziskaj_a_id_pridaneho_anime);
$a_id_ziskane = "";
while ($db_data = mysqli_fetch_assoc($run_sql_ziskaj_a_id_pridaneho_anime)) {
$a_id_ziskane = $db_data['a_id'];
}
$sql_vloz_anime_info = "INSERT INTO anime_info (a_id, a_img, a_start, a_stop, a_time_ep, a_akihabara)
VALUES ('$a_id_ziskane' , '$_POST[obrazok]', '$_POST[zaciatok]', '$_POST[koniec]', '$_POST[cas]', '$_POST[akihabara]')";
mysqli_query($connect_to_db , $sql_vloz_anime_info);
}

$input_date=$_POST['date'];
$date=date("Y-m-d H:i:s",strtotime($input_date));
This will convert input date into MySQL Timestamp compliant format.
Please DO NOT put POST values directly in your queries. Your website or web application will be hacked in no time through SQL Injections.

MySql datetime considered yyyy-mm-dd h:i:s format.
Your input date is like dd-mm-yyyy h:i:s and so on.
Then use convert date to yyyy-mm-dd h:i:s. Read strtotime manual.
For e.g.
$inputDate = '06-06-2017 05:21:34';
$mysqlDate = date("Y-m-d H:i:s",strtotime($inputDate));
// MySql Query.
INSERT INTO table_name SET `your_field`='$mysqlDate'

Related

mysql timestamp output as formatted Date not working

I have a crazy phenomenon in my php script. I have defined a column as a timestamp in a mysql table. I fill it with the function:
date("Y-m-d H:i:s");
The data in the table then look like this: 2017-04-19 17:08:45
When I query this column with mysqli as a unix timestamp again:
SELECT UNIX_TIMESTAMP (timestamp) as timestampUnix FROM posts
Then binding the result using bind_result to the variable $timestampUnix.
I can echo the variable with
echo $timestampUnix;
and it outputs a correct timestamp like this: 1492614559
however if i do the following:
$timestampUnix2 = $timestampUnix;
echo $timestampUnix2;
there is simply no echo output... What is the reason?
I tried this because I actually want echo only the date in an other format with:
date('d.m.Y', $timestampUnix)
and it gave me 01.01.1970 and i wondered why the timestamp must be 0 but it isnt since when i directly echo it it gives me a correct one.
however when i do
Date('d.m.Y', 1492614559)
it gives me the correct date.. no clue what is going on there!
i know there are many other questions about mysql php Date output, but no one have this issue as i think i cannot do something with the variable i got from the query.
thanks in advance!
edit: i attach the complete code in question:
---the query that inputs the data in the db----
$timestamp = date("Y-m-d H:i:s");
mysqli_query($mysqli,"INSERT INTO posts (timestamp)
VALUES ('$timestamp')");
---the query that fetches the data----
$results = $mysqli->prepare("SELECT UNIX_TIMESTAMP(timestamp) as timestampUnix FROM posts");
$results->execute(); //Execute prepared Query
$results->bind_result($timestampUnix); //bind variables to prepared statement
$postdate = date('d.m.Y',$timestampUnix)
echo $postdate;

Trying to make a stored Datetime value shorter with SQL Convert function

I'm new to using the convert function. I'm trying to make a datetime value from my table shorter. Currently my datetime values look something like this, 2016-10-14 16:51:41, but I'd like to make it look something like mm/dd/yy.
I don't know if this is the right approach (must not be since it doesn't work), but I've generated a query using the convert function and then fetching the data with a mysqli_fetch_array.
Here's the code I'm using:
$sql = "SELECT id, time, CONVERT(VARCHAR(11), time) as something FROM tableName";
$query = mysqli_query($db, $sql);
$statusnumrows = mysqli_num_rows($query);
// Gather data about parent pm's
if($statusnumrows > 0){
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$time= $row["time"];
}
}
Time is the name of the column which has the datetime type.
Thanks in advance, for suggestions/advice.
You should store datetime in your DB in proper data types like datetime etc.
As I can see you are using PHP, if you need to OUTPUT this datetime in some interface (f.e. HTML page), you should use PHP functions to convert date in format you need. That is the good practice
DB should STORE the data but formatting is front-end problem.
Simple example of strtotime() and date():
$Date = "2016-10-15";
$newDate = date("m/d/Y", strtotime($Date));
You can read docs on the PHP site: strtotime and date
If 2012+ you could use format (not very efficient but does offer some other possibilities)
Declare #Date DateTime = GetDate()
Select UsingFormat = Format(#Date,'MM/dd/yy')
,UsingConvert1 = convert(varchar(10),#Date,1)
,UsingConvert101 = convert(varchar(10),#Date,101)
Returns
UsingFormat UsingConvert1 UsingConvert101
10/15/16 10/15/16 10/15/2016
Use style 1 in Convert function for mm/dd/yy format
select CONVERT(VARCHAR(20), [time],1)
From yourtable
If you want mm/dd/yyyy format then use 101 style
select CONVERT(VARCHAR(20), [time],101)
From yourtable
MSDN link for Convert function with various style : CONVERT

Get date and time retrieved from database into a datetime input

I'm trying to retrieve a Datetime value from my database and place it in an html input with a date type but it doesn't show anything.
$resQuery = mysql_query("SELECT * FROM reserveringen WHERE id = $ID");
while ($resInfo = mysql_fetch_array($resQuery))
{
$dateTime = $resInfo[3];
}
<?php echo "<input name='dateTime' type='datetime-local' value='$dateTime'"?>
Also when I F12 I get this error: The specified value "2525-0505-16161616 0606:0505" does not conform to the required format. The format is "yyyy-MM-ddThh:mm" followed by optional ":ss" or ":ss.SSS".
This fixed it for me guys!
I changed my query to:
SELECT *, DATE_FORMAT(Datum, '%Y-%m-%dT%H:%i') AS Datum_conv FROM reserveringen WHERE id = $ID
The problem is that when you was writing data into database you used wrong date format. Look carefully at datetime value:
2525-0505-16161616 0606:0505
It must be
25-05-16 06:05
What you did when saving data is using these date format:
date('dd-mm-yyyy HH:ii')
instead of this
date('d-m-Y H:i');

Empty DATETIME value stored as 0000-00-00 00:00:00 instead of NULL in MySQL [duplicate]

This question already has answers here:
How to store NULL values in datetime fields in MySQL?
(9 answers)
Closed 7 years ago.
I have optional date and time form fields which are combined to form a DATETIME-friendly string, which is then sent to the MySQL database. The relevant MySQL column data type is DATETIME, with a default value of NULL. It saves correctly when the date and time fields are completed; however when these optional form fields are empty, the datetime is stored as 0000-00-00 00:00:00 instead of NULL. It needs to be stored as NULL and I have no idea why it isn't. Here's my code:
$Date_Query_Received1 = mysqli_real_escape_string($conn, $_POST['Date_Query_Received']);
$Date_Query_Received2 = implode("-", array_reverse(explode("/", $Date_Query_Received1)));
$Time_Query_Received1 = mysqli_real_escape_string($conn, $_POST['Time_Query_Received']);
$Time_Query_Received2 = $Time_Query_Received1.':00';
if (empty($_POST['Date_Query_Received']) || empty($_POST['Time_Query_Received'])) {
$Date_Query_Received = NULL;
$Time_Query_Received = NULL;
} else {
$Date_Query_Received = $Date_Query_Received2;
$Time_Query_Received = $Time_Query_Received2
}
$Date_Time_Query_Received = $Date_Query_Received.' '.$Time_Query_Received;
mysqli_query($conn, "INSERT INTO log (Date_Time_Query_Received) VALUES ('$Date_Time_Query_Received')";
The form dates are in DD/MM/YYYY format, hence implode(...array_reverse(...)) to convert to MySQL-friendly DATETIME YYYY-MM-DD format. The same applies with appending ':00' to the time value, as the form field jQuery timepicker is set up for hh:mm only - seconds are not required.
Perhaps it has something to do with the quotes around $Date_Time_Query_Received in the SQL statement; however the query fails without them.
So if you look at your query, you were trying to set the date column to the string ' ' which obviously isn't going to make MySQL happy. It's a very forgiving database though, and defaults to its fallback for a DATETIME column, which is 0000-00-00 00:00:00.
So, how do you pass a null value to the database from PHP? Try using prepared statements like so:
if (empty($_POST['Date_Query_Received']) || empty($_POST['Time_Query_Received'])) {
$Date_Time_Query_Received = NULL;
} else {
$Date_Query_Received2 = implode("-", array_reverse(explode("/", $_POST['Date_Query_Received'])));
$Time_Query_Received2 = "$_POST[Time_Query_Received]:00";
$Date_Time_Query_Received = "$Date_Query_Received2 $Time_Query_Received2";
}
$stmt = $conn->prepare("INSERT INTO log (Date_Time_Query_Received) VALUES (?)");
$stmt->bind_param("s", $Date_Time_Query_Received);
$stmt->execute();
In addition to making it easier to pass the null value, you're also protecting yourself from SQL injection attacks more effectively than with mysqli_real_escape_string().

php insert prepared stmt

My code looks like:
$sql_ = $this->db->prepare("SELECT * FROM user");
$sql_->execute();
$user = $sql_->fetchAll();
$sql_insert_blog = $this->db->prepare("INSERT INTO
blog
(blog_title,blog_author,blog_content,blog_tags,blog_create,blog_update)
VALUES
(:1,:2,:3,:4,:5,:6)");
$sql_insert_blog->execute(array(
":1"=>$title,
":2"=>$author,
":3"=>$content,
":4"=>$tags,
":5"=>$date_create,
":6"=>$date_update
));
So the first sql statement is to proof if the database coneccion is active. It works when i use
print_r($user)
Th second one is the statement thats not been executed.
I have a controller that calls this function on a model, and gives all the info from the form to this function like
function newBlogEntry()
{
$title = $_POST["input_blog_title"];
$author = $_POST["input_blog_author"];
$content = $_POST["input_blog_content"];
$tags = $_POST["input_blog_tags"];
$date_create = date('m/d/Y h:i:s a', time());
$date_update = $date_create;
$this->model->newBlogEntry($title,$author,$content,$tags,$date_create,$date_update);
}
and the function on this model is actually called. i can select all users from db.
i allready checked all the parameters, and also every parameter can be null so, even if the form is emtpy it should be a insert in the database(This is just for testing).
But there is no entry in the database...
So my question is: what am i doing wrong here?
It would appear that MySQL doesn't like your date values. The default format for dates-as-strings in MySQL is YYYY-MM-DD HH:MM:SS, according to the docs; a string that looks like this will automatically be parsed as a date.
use (?,?,?,?,?,?) instead of (:1,:2,:3,:4,:5,:6)
and
$sql_insert_blog->execute(array($title, $author, $content, $tags, $date_create, $date_update));
and
dates should be strings with Y-m-d H:i:s php date() format

Categories