Storing Data in MySQL
Today we will see how to store data into MySQL database. This is done with SQL command INSERT.
The SYNTAX for SQL INSERT command is
PHP Code:
INSERT INTO TABLE_NAME SET field1=value, field2=value,....
To insert data into our chat table, use following command
PHP Code:
INSERT INTO `chat` SET `name`='Some Name Here', `message`='Some message here';
day_14_mysql_insert.php
PHP Code:
<?php
$db_server = '127.0.0.1';
$db_user = 'fwhphp_user';
$db_password = 'k5BJRaX6SFbs';
$db_name = 'fwhphp_db';
$mysqli = new mysqli($db_server, $db_user, $db_password, $db_name);
if ($mysqli->connect_errno) {
echo 'Connect failed: ' . $mysqli->connect_error;
exit();
}
$sql = 'INSERT INTO `chat` SET `name`=\'Anonymous\', `message`=\'Change this message, be creative\'';
if ($mysqli->query($sql) === TRUE) {
echo '<h1>Data saved into MYSQL</h1>';
} else {
echo '<h1>Failed to Insert Data to Database</h1>';
echo $mysqli->error;
}
To see the data you inserted, use the script we created on Day 13 - day_13_mysql_read.php
Try inserting multiple data into the database.
Find
PHP Code:
$sql = 'INSERT INTO `chat` SET `name`=\'Anonymous\', `message`=\'Change this message, be creative\'';
Replace name and message, so we can insert more data into the table.
For example
PHP Code:
$sql = 'INSERT INTO `chat` SET `name`=\'Raju\', `message`=\'I asked you to change this text and storing more data into table, so you learn MySQL INSERT.\'';
We use \' to escape single quote.
Bookmarks