PDO inserting recrod to MySQL tableWe will learn how to insert or add record to a MySQL table by using PDO in PHP. Here we will only work on the database query and record insert part.
To keep the script simple and easy to understand we have omitted the data validation part. The table structure has unique constraints of userid so duplicate userid is not accepted. If you try to add same userid ( already exist) then you will get error message.
In your downloaded script there is a file pdo-insert.php . This file displays the form and after submission of the form data is posted to pdo-insert2.php file for storing in MySQL table.
Before using this page you must create the tables by using sql_dump file. The detail of singup page with data validation is shown here. php_signup.php.
LastInsertIDThis gives you the value of the auto increment Id field. The value is created once a new record is added to the table. You can read more on this at mysql_insert_id() . WE assume that the PHP Pdo connection is already available. WE will directly go to query part.
Printing the error message.The above code there is a if else condition checking, in case of failure of insert query it will display a message saying 'Not able to add data please contact Admin' however it does not tell about the error or mistake in the syntax. So to get more meaning full information from the database we have to use errorinfo() function. We will modify the part of the above code like this.
Storing error message in a string and passing to front end
Adding current DateIn the above code you can add current date like this ( only changes )
Changing date format to store in MySQL table
Here $dt is the variable storing date field value.
To add null to a date fieldIf the date field is set to accept null data then here is the query to add
If you are receving date field as blank from a form then use this PHP script.
This article is written by plus2net.com team.