![]() |
|
MySQL INSERT Statement. Free online PHP and MySQL Web Database Programming Tutorial... |
| Lessons | MySQL INSERT Statement |
|
|
The first form of INSERT INTO statement doesn't specify the column names where the data is to be inserted, it only specifies their values: INSERT INTO table_name VALUES (value1, value2, value3,...) The second form of INSERT INTO specifies both; the column names and the values to be inserted, as follows: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) We have to use PHP mysql_query() function to execute the above statements. Here is an example: Example The following code inserts two new records in the "Students" table: <?php $con = mysql_connect("localhost", "adam" ,"ada"); if (!$con) { die('Error connecting database'); } mysql_select_db("my_db", $con); mysql_query("INSERT INTO Students (Name, Age, Address) VALUES ('Jacob', '20', 'Jacob Address')"); mysql_query("INSERT INTO Students VALUES ('Ibrahim', '22', 'Ibrahim Address')"); mysql_close($con); ?> How to Insert Data From a HTML Form Into a Database? It is not as difficult as it sounds. It, really, is very simple. The following example creates an HTML form that is then used to insert new record into our "Students" table: HTML Form (code): <html> <body> <form action="insertData.php" method="post"> Name:<input type="text" name="name" /><br> Age: <input type="text" name="age" /><br> Address: <input type="text" name="address" /><br> <input type="submit" /> </form> </body> </html> This is how the above HTML would look like in an internet browser: When a user clicks the submit button, the form data is sent to "insertData.php". The "insertData.php" file then retrieves the values from the form using the PHP $_POST array, connects to the database and inserts into the database the retrieved values. Here is the code for the "insertData.php" page: <?php $con = mysql_connect("localhost", "adam", "ada"); if (!$con) { die('Error connecting database'); } mysql_select_db("my_db", $con); $sql="INSERT INTO Students (Name, Age, Address) VALUES ('$_POST[name]', '$_POST[age]', '$_POST[address]')"; if (!mysql_query($sql, $con)) { die('Error inserting record'); } echo "Record added successfully "; mysql_close($con) ?>
Next: PHP MySQL Select
|