I' trying to insert a DATE into MySQL database. Date has been set as new DateTime() and formatted to "Y:m:d". A variable carries the new DateTime but when inserting it to a DATE field in MYSQL only ceros are inserted. The DATE field is not getting NULL results but just CEROS 000-00-00.
This is my code.
$bigin=date("Y-m-d");
$datetime_bigining = new DateTime($bigin);
$datetime_bigining->modify('-60 day');
$datetime_bigining->format('Y:m:d');
$insert_days= mysql_query("INSERT INTO $tocreate (date_full) VALUES".$datetime_bigining->format('Y-m-d').");") or die(mysql_error());
Your code can be simplified tremendously (and fixed):
$datetime_beginning = new DateTime('60 days ago');
$insert_days= mysql_query("INSERT INTO $tocreate (date_full)
VALUES ('".$datetime_beginning->format('Y-m-d')."');") or die(mysql_error());
You can combine your first three lines of code
Your fourth line is unnecessary and useless
You have a couple of SQL syntax errors (missing parenthesis, missing quotes)
Try $datetime_bigining->format('Y-m-d'); This is the format that MySQL expects.
Related
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'
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;
Hey guys it may have been asked before but I am still stuck with a peculiar issue.
I am trying to Pass a dateTime object to my mysql insert statement but it always tells me there is an error namely:
Object of class DateTime could not be converted to string
$dateToPass = new DateTime('now');
//$dateToPass = $dateToPass->format('d/m/Y H:i:s');
//inserting values
$SQLstring="Insert into Request(cust_num,request_date,item_description,item_weight,pickup_address,pickup_suburb,
pickup_date,pickup_time,receiver_name,delivery_address,delivery_suburb,delivery_state)
values(27,$dateToPass,'$desc',$weight,'$address','$suburb','$date', '$time','$rname','$raddress','$rsuburb','$rstate');";
$queryResult = #mysqli_query($DBConnect, $SQLstring)
Or die ("<p>Unable to query the Customer table.</p>"."<p>Error code ". mysqli_errno($DBConnect). ": ".mysqli_error($DBConnect)). "</p>";
Where $dateToPass is a datetime field in my database.
Hope you guys can help.
you cannot send DateTime object as string. Try converting it to string as MySQL expects.
$dateToPass = new DateTime('now');
$dateToPass = $dateToPass->format('Y-m-d H:i:s');
Alternatively if you are always going to store current datetime you can use the MySQL NOW() like
$SQLstring="Insert into Request(cust_num,request_date,item_description,item_weight,pickup_address,pickup_suburb,
pickup_date,pickup_time, receiver_name,delivery_address,
delivery_suburb,delivery_state)
values(27,NOW(),'$desc',$weight,'$address','$suburb','$date', '$time','$rname','$raddress','$rsuburb','$rstate');";
I receive a GET variable named $temp in my php code, after connecting to the server and selecting the correct database, and I am able to pass it into the table using:
mysql_query("INSERT INTO Temperature (Temperature) VALUES ($temp)");
However if I save a time variable using:
$time = date('G:i', time());
and try and pas it in with:
mysql_query("INSERT INTO Temperature (Temperature) VALUES ($temp)");
or even:
mysql_query("INSERT INTO Temperature (Time,Temperature) VALUES ($time,$temp)");
I am unable to get it to be passed into my table.
I am echoing both variables so I know they are being saved correctly into the variables. Also, in my table there are two columns named "Time" and "Temperature". The name of the table is "Temperature". Why won't the $time variable get passed in if it is the exact same line of code as $temperature variable except for changing the column name? Also both columns are set to recieve varchar (20) could this be the issue?
You're very close to having it right in your example. In this line you need quotes in your query around your values.
mysql_query("INSERT INTO Temperature (Time,Temperature) VALUES ($time,$temp)");
So it would look like this:
mysql_query("INSERT INTO Temperature (Time,Temperature) VALUES ('$time', '$temp')");
But this way of creating a query is soon to be deprecated for the easier to use and more modern method of using PDO. Using PDO would looking something like this:
$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);
// prepare sql and bind parameters
$stmt = $conn->prepare('INSERT INTO Temparature (`time`, `temperature`)
VALUES (:time, :temperature)');
$stmt->bindParam(':time', $time);
$stmt->bindParam(':temperature', $temp);
// insert a row
$temp = "34";
$time = date('G:i', time());
$stmt->execute();
A time column in MySQL expects a string in the format 'hh:mm:ss'.
To do this, you could do:
$timestamp = time();
$time = date('G:i', $timestamp); // assuming you need $time somewhere else
mysql_query("INSERT INTO Temperature (Time,Temperature) VALUES ( ".date('H:i:s', $timestamp).", $temp)");
If you do not need $time for any other purpose than inserting it in the database, you could use:
mysql_query("INSERT INTO Temperature (Time,Temperature) VALUES (NOW(), $temp)");
And let MySQL do the time creation for you.
To only select the hours and minutes do:
SELECT TIME_FORMAT(Time, '%H:%i') FROM Temperature;
See the MySQL Documentation for more info on formatting date and time as strings.
I'm trying to filter out repeated values entering into a MySQL table, by comparing the input PHP variable with the timestamp of an entry already present in the table and only if they don't match, the input PHP variable is entered into the table.
$user1_date = mysql_real_escape_string($user1_date); // the date variable
$user1_temp1 = mysql_real_escape_string($user1_temp1);
$user1_temp2 = mysql_real_escape_string($user1_temp2);
$user1_temp3 = mysql_real_escape_string($user1_temp3);
$user1_date = date("Y-m-d H:i:s", strtotime($user1_date)); //Typecasting PHP variable into timestamp
$sql_check = "SELECT * FROM user_details WHERE temp_date ='$user1_date'";
$result_check = mysql_query($sql_check);
$num_rows_check = mysql_num_rows($result_check);
if ($num_rows_check == 0) // To check if there is no entry in the table with the same date and time as input PHP variable
{
$sql_insert = "INSERT INTO data_hour (user_id, temp1, temp_date, temp2, temp3)
VALUES (1,'$user1_temp1', '$user1_date', '$user1_temp2', '$user1_temp3')";
$result_insert = mysql_query($sql_insert);
}
temp_date is a column in the table of type timestamp. Even when the $user1_date is the same as the temp_date(timestamp) column for one of the entries in the table, it considers it as not equal and is inserting it into the table and hence I'm getting repeated values. I'm guessing the WHERE temp_date = '$user1_date'is not working properly. Some troubleshooting that I have done included
Changing '$user1_date' to just $user1_date in the WHERE
statement
Changing the WHERE clause as follows WHERE temp_date = (date)'$user1_date'
It will be great if somebody can help me out with this!
A nice easy solution would be giving temp_date a UNIQUE INDEX in your Mysql Table, as that would not allow the same value to be inserted twice. This would also make your operations more efficient, as you wouldn't have to do SELECT * every time you want to insert something.
However, for what you're doing, I think I see your problem; there are some quirks in your logic so I'll try to dispel them here. (Hopefully?) this will make your program cleaner and you'll be able to pinpoint the error, if not eliminate it altogether.
Examining this piece of code:
// $user1_date doesn't have a value here! //
$user1_date = mysql_real_escape_string($user1_date);
...
$user1_date = date("Y-m-d H:i:s", strtotime($user1_date));
Error 1 - You escape the string before ever setting a value.
What you are doing is that you are using mysql_real_escape_string() before $user1_date is ever defined.
Correction:
// Getting better, but not done. //
$user1_date = date("Y-m-d H:i:s", strtotime($user1_date));
...
$user1_date = mysql_real_escape_string($user1_date);
Error 2 - You do not give the date() function appropriate parameters
The date() function in PHP expects a timestamp, which is just an int. You can easily get the time with time(), so that should rectify your problem
Correction:
// You use strtotime($user1_date), but you should use time() //
$user1_date = date("Y-m-d H:i:s", time());
...
$user1_date = mysql_real_escape_string($user1_date);
These are small mistakes, but they can be deadly. Like I said, you should assign temp_date to a UNIQUE INDEX in your MySQL table, but make sure to correct these errors listed as well.
Let me know how it goes!