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
To insert data into our chat table, use following commandPHP Code:INSERT INTO TABLE_NAME SET field1=value, field2=value,....
day_14_mysql_insert.phpPHP Code:INSERT INTO `chat` SET `name`='Some Name Here', `message`='Some message here';
To see the data you inserted, use the script we created on Day 13 - day_13_mysql_read.phpPHP 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;
}
Try inserting multiple data into the database.
Find
Replace name and message, so we can insert more data into the table.PHP Code:$sql = 'INSERT INTO `chat` SET `name`=\'Anonymous\', `message`=\'Change this message, be creative\'';
For example
We use \' to escape single quote.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.\'';



Reply With Quote

Bookmarks