May 16, 2021 MariaDB
In this chapter, we'll learn how to insert data into a table.
An INSERT command is required to insert data into a table. T he general syntax of this command is INSERT, followed by the table name, fields, and values.
Check out the general syntax given below -
INSERT INTO tablename (field,field2,...) VALUES (value, value2,...);
The statement needs to use single or double quotes for string values. O ther options for the statement include "INSERT ... S ET" statement, "INSERT ... S ELECT" statement and several other options.
Note - The VALUES() function that appears in the statement applies only to INSERT statements and returns NULL if used elsewhere.
There are two options for doing this: use the command line or use PHP scripts.
When prompted, there are many ways to make a selection. T he standard statement is given below -
belowmysql> INSERT INTO products_tbl (ID_number, Nomenclature) VALUES (12345, “Orbitron 4000”); mysql> SHOW COLUMNS FROM products_tbl; +-------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------+------+-----+---------+-------+ | ID_number | int(5) | | | | | | Nomenclature| char(13) | | | | | +-------------+-------------+------+-----+---------+-------+
You can insert multiple lines -
INSERT INTO products VALUES (1, “first row”), (2, “second row”);
You can also use the SET clause -
INSERT INTO products SELECT * FROM inventory WHERE status = 'available';
Use the same "INSERT INTO ..." statement in the PHP function to perform the action. Y ou will use the mysql_query() function again.
See the example given below -
<?php if(isset($_POST['add'])) { $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } if(! get_magic_quotes_gpc() ) { $product_name = addslashes ($_POST['product_name']); $product_manufacturer = addslashes ($_POST['product_name']); } else { $product_name = $_POST['product_name']; $product_manufacturer = $_POST['product_manufacturer']; } $ship_date = $_POST['ship_date']; $sql = "INSERT INTO products_tbl ". "(product_name,product_manufacturer, ship_date) ". "VALUES"."('$product_name','$product_manufacturer','$ship_date')"; mysql_select_db('PRODUCTS'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); } echo "Entered data successfully "; mysql_close($conn); } ?>
After successfully inserting the data, you will see the following output -
mysql> Entered data successfully
You will also use insert statements to work together to validate statements, such as checking to ensure correct data entry. M ariaDB includes many options, some of which are automatic.