Php pdo insert date

Как вставить datetime из PHP или PDO в базу данных MYSQL?

По какой-то причине формат кажется правильным, и он не будет вставлен в мою базу данных. Если у меня установлено значение Date вместо DateTime и используется только Y-m-d, это прекрасно работает для года-месяца-дня.

Столбец таблицы — дата-время:

$creation_date = date("Y-m-d H:i:s"); $sql = "INSERT INTO table SET creation_date='$creation_date'"; $stmt = $con->prepare($sql); $data = $stmt->execute(); 
INSERT INTO table SET creation_date='2016-10-22 20:42:11' 

Решение

Вы, вероятно, терпите неудачу в какой-то другой момент, трудно сказать, не видя схему таблицы. Вот полный пример, который включает в себя создание и вставку таблицы, попробуйте дублировать каждый шаг, если он все еще не выполняется, я рекомендую:

  1. Попробуйте те же запросы от клиента командной строки mysql (mysql), чтобы увидеть, если это проблема с библиотекой PHP / подключение к БД
  2. Опубликуйте схему таблицы, в идеале со всеми шагами, которые я покажу ниже.
localhost/test> CREATE TABLE datetest (id smallint(5) unsigned NOT NULL AUTO_INCREMENT, \ ctime DATETIME NOT NULL, PRIMARY KEY(id)); Query OK, 0 rows affected (0.03 sec) localhost/test> SHOW CREATE TABLE datetest; +----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | datetest | CREATE TABLE `datetest` ( `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `ctime` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 | +----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) localhost/test> INSERT INTO datetest SET ctime='2016-10-22 20:42:11'; Query OK, 1 row affected (0.00 sec) localhost/test> SELECT * FROM datetest; +----+---------------------+ | id | ctime | +----+---------------------+ | 1 | 2016-10-22 20:42:11 | +----+---------------------+ 1 row in set (0.00 sec) 

Следует также отметить, что вам следует избегать зарезервированных ключевых слов, таких как date , Не похоже, что это твоя проблема, но есть на что обратить внимание.

Другие решения

Источник

how to insert date in mysql using php?

For Insert date Into MySQL in ‘dd-mm-yyyy’ format Using PHP first of all I have to make a simple table in data base like bellow example for InsertDate current date in mysql using php.

Insert date Into MySQL Using PHP

how to InsertDate date in mysql using php?
Here i am using main three file for InsertDate data in MySQL Example:

  • database.php:firs of all you can database For connecting & testing data base
  • InsertDate.php:and then for fetching the values from the members
  • process.php:A PHP server side file that process the get data request
Читайте также:  Php как разбить переменную

CREATE TABLE : members

CREATE TABLE `members` ( `userid` int(8) NOT NULL, `member_name` varchar(55) NOT NULL, `profile_name` varchar(55) NOT NULL, `birth_date` varchar(55) NOT NULL, `email` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Alternative Code in (PDO)

setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO members (member_name,profile_name,birth_date,email,datetime) VALUES ('$member_name', '$profile_name','$birth_date','$email','$insertdate')"; $conn->exec($sql); echo "New record created successfully"; > catch(PDOException $e) < echo $sql . "
" . $e->getMessage(); > $conn = null; ?>

how to InsertDate in mysql using php form

First name:

Last name:

Borth Date:

Email Id:

Источник

PHP/PDO insert current date plus one month into MYSQL

* * *, that mean it every minute also will checking the result, so once my result had check complete , it will insert to database, but now my results are keep inserting to database, so how to everyday insert only one record in database with the cronjob run every minute or how to stop keep inserting result to database? thank you hope you guys reply me soonest Solution 1: Do the following: Add a date field to the record and make it unique. Assuming your table is and column that stores date is as This code does not check for sql errors and does not use prepared statments, but it’s simple and provides you with a good idea to start.

PHP/PDO insert current date plus one month into MYSQL

I am trying to add the current date (not time if i have the option) and also the date of one month later into my MYSQL database and I keep gettin the following error:

Parse error: syntax error, unexpected T_LNUMBER in *myfile* on line 45 

My function to insert the data is as follows:

function add_zipcode($zip, $adminID, $email) < global $db; $query = ' INSERT INTO zip_owners (zip, email, adminID, started, transferred, expires) VALUES (:zip, :email, :adminID, :started, :transferred, :expires)'; try< $statement = $db->prepare($query); $statement->bindValue(':zip', $zip); $statement->bindValue(':email', $email); $statement->bindValue(':adminID', $adminID); $statement->bindValue(':started', now()); $statement->bindValue(':transferred', now()); $statement->bindValue(':expires', DATE_ADD(now(), INTERVAL 1 MONTH)); $statement->execute(); $statement->closeCursor(); > catch (PDOexception $e) < $error_message = $e->getMessage(); echo "

Database Error: $error_message

"; exit(); > >

The problem line is this one:

$statement->bindValue(':expires', DATE_ADD(now(), INTERVAL 1 MONTH)); 

I’m not quite sure why that syntax doesn’t work.

My goal is to be able to compare the dates when selecting rows to return the rows that have the expires filed within a week of the current date.

Quote your MySQL statements, they’re strings in PHP:

$statement->bindValue(':expires', 'DATE_ADD(now(), INTERVAL 1 MONTH)'); 

Sql — MySQL’s now() +1 day, You can use: NOW () + INTERVAL 1 DAY. If you are only interested in the date, not the date and time then you can use CURDATE instead of NOW: CURDATE () + INTERVAL 1 DAY. Share. answered Oct 8, 2010 at 3:34. Mark Byers. 776k 181 1550 1440. Usage exampleNOW() + INTERVAL 1 DAYFeedback

How to insert only one record per day?

my coding had regarding crontab in linux and php, what I want to do is my cronjob datetime is * * * * *, that mean it every minute also will checking the result, so once my result had check complete , it will insert to database, but now my results are keep inserting to database, so how to everyday insert only one record in database with the cronjob run every minute or how to stop keep inserting result to database?

Читайте также:  Employee Table

thank you hope you guys reply me soonest

  1. Add a date field to the record and make it unique.
  2. Modify your job to check if there is an record — if so, don’t insert a new one.

You have to check if you have already inserted the date. Assuming your table is Table and column that stores date is date as timestamp

$sql = "select * from Tablewhere DATE(`date`) = CURRENT_DATE()"; $result = mysql_query($sql); if (mysql_num_rows($result)>0) < //you already have inserted current date, handle this as you need >else < //current date have not beed inserted, insert it as usual >

This code does not check for sql errors and does not use prepared statments, but it’s simple and provides you with a good idea to start.

Insert current date/time using now() in a field using, NOW () normally works in SQL statements and returns the date and time. Check if your database field has the correct type (datetime). Otherwise, you can always …

How to add 1 day to the date in MySQL?

We can add 1 day to the date with the help of DATE_ADD() function.

mysql> create table Add1DayDemo -> ( -> id int, -> MyDate datetime not null -> ); Query OK, 0 rows affected (1.06 sec)
mysql> insert into Add1DayDemo values(1,now()); Query OK, 1 row affected (0.08 sec) mysql> insert into Add1DayDemo values(2,date_add(now(),interval 5 day)); Query OK, 1 row affected (0.16 sec)
mysql> select *from Add1DayDemo;

The following is the output.

+------+---------------------+ | id | MyDate | +------+---------------------+ | 1 | 2018-10-30 10:51:21 | | 2 | 2018-11-04 10:51:30 | +------+---------------------+ 2 rows in set (0.00 sec)

To add 1 day in field “MyDate”, use the SELECT

mysql> SELECT DATE_ADD(`MyDate`, INTERVAL 1 DAY) from Add1DayDemo -> where > The following is the output that shows the day, which was 4th November, increments by one, since we added a day.
+------------------------------------+ | DATE_ADD(`MyDate`, INTERVAL 1 DAY) | +------------------------------------+ | 2018-11-05 10:51:30 | +------------------------------------+ 1 row in set (0.00 sec)

MySQL: How to add one day to datetime field in query, SELECT * FROM `fab_scheduler` WHERE eventdate>= (NOW () — INTERVAL 1 DAY)) AND eventdate

Источник

how to insert date in mysql using php?

For Insert date Into MySQL in ‘dd-mm-yyyy’ format Using PHP first of all I have to make a simple table in data base like bellow example for InsertDate current date in mysql using php.

Insert date Into MySQL Using PHP

how to InsertDate date in mysql using php?
Here i am using main three file for InsertDate data in MySQL Example:

  • database.php:firs of all you can database For connecting & testing data base
  • InsertDate.php:and then for fetching the values from the members
  • process.php:A PHP server side file that process the get data request
Читайте также:  All css codes pdf

CREATE TABLE : members

CREATE TABLE `members` ( `userid` int(8) NOT NULL, `member_name` varchar(55) NOT NULL, `profile_name` varchar(55) NOT NULL, `birth_date` varchar(55) NOT NULL, `email` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Alternative Code in (PDO)

setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO members (member_name,profile_name,birth_date,email,datetime) VALUES ('$member_name', '$profile_name','$birth_date','$email','$insertdate')"; $conn->exec($sql); echo "New record created successfully"; > catch(PDOException $e) < echo $sql . "
" . $e->getMessage(); > $conn = null; ?>

how to InsertDate in mysql using php form

First name:

Last name:

Borth Date:

Email Id:

Источник

Блог

Как вставить datetime из PHP или PDO в базу данных MYSQL?

#php #mysql #datetime #pdo

#php #mysql #datetime #pdo

Вопрос:

По какой-то причине формат кажется правильным, и он не будет вставлен в мою базу данных. Если я установил для него значение Date вместо DateTime и использую только Y-m-d, это отлично работает для Year-Month-Day.

Столбец таблицы — datetime:

 $creation_date = date("Y-m-d H:i:s"); $sql = "INSERT INTO table SET creation_date='$creation_date'"; $stmt = $con->prepare($sql); $data = $stmt->execute(); 
 INSERT INTO table SET creation_date='2016-10-22 20:42:11'  

Комментарии:

1. каков тип столбца creation_date в вашей таблице? попробуйте сделать это отметкой времени.

2. A. Просто:. Если вы собираетесь использовать Y-m-d H:i:s , то вам нужно изменить свой столбец на DATETIME.

3. Это просто. Голосование отражает качество вопроса.

4. Добавьте выходные данные SHOW CREATE TABLE yourtablename; к вашему вопросу.

5. ИСПОЛЬЗУЙТЕ SQL NOW(). Попробуйте Google..

Ответ №1:

Вероятно, у вас сбой в какой-то другой момент, трудно сказать, не видя вашей схемы таблицы. Вот полный пример, который включает в себя создание таблицы и вставку, попробуйте повторить каждый шаг, если это все еще не удается, я рекомендую:

  1. Попробуйте те же запросы из клиента командной строки mysql (mysql), чтобы узнать, не проблема ли это с библиотекой PHP / подключением к БД
  2. Опубликуйте свою схему таблицы, в идеале со всеми шагами, которые я показываю ниже.
 localhost/test> CREATE TABLE datetest (id smallint(5) unsigned NOT NULL AUTO_INCREMENT, ctime DATETIME NOT NULL, PRIMARY KEY(id)); Query OK, 0 rows affected (0.03 sec) localhost/test> SHOW CREATE TABLE datetest; ---------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | Table | Create Table | ---------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | datetest | CREATE TABLE `datetest` ( `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `ctime` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 | ---------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 1 row in set (0.00 sec) localhost/test> INSERT INTO datetest SET ctime='2016-10-22 20:42:11'; Query OK, 1 row affected (0.00 sec) localhost/test> SELECT * FROM datetest; ---- --------------------- | id | ctime | ---- --------------------- | 1 | 2016-10-22 20:42:11 | ---- --------------------- 1 row in set (0.00 sec) 

Еще одна вещь, на которую следует обратить внимание, это то, что вам следует держаться подальше от зарезервированных ключевых слов, таких как date . Не похоже, что это ваша проблема, но на что-то нужно обратить внимание.

Комментарии:

1. Я сделаю это в следующий раз.

Источник

Оцените статью