Building Chinese Web Sites using PHP - Version 2.14, by Dr. Herong Yang
INSERT INTO - Inserting New Records
This section describes how to insert a new record into a table.
The first database transaction I want to try is to insert a new record to the Comment table. Inserting a new record can be done by sending a SQL INSERT INTO statement to the MySQL server for execution with the mysql_query() function. After that you can call the mysql_insert_id() function to obtain the auto-incremented primary key value of the inserted record.
Here is sample PHP script to insert a new record into the Comment table:
<?php #- MySQL-Insert-Into.php #- Copyright (c) 2015, HerongYang.com, All Rights Reserved. # $con = mysql_connect("localhost", "Herong", "TopSecret"); $ok = mysql_select_db("HerongDB", $con); $name = 'Bob'; $comment = <<<END_OF_MESSAGE The first database transaction I want to try is to insert a new record to the Comment table. Inserting a new record can be done by sending a SQL INSERT INTO statement to the MySQL server for execution with the mysql_query() function. After that you can call the mysql_insert_id() function to obtain the auto-incremented primary key value of the inserted record. END_OF_MESSAGE; $sql = "INSERT INTO Comment (Name, Comment)" . " VALUES ('$name', '$comment')"; if (mysql_query($sql, $con)) { print("Number of rows inserted: ".mysql_affected_rows()."\n"); print("Last row ID inserted: ".mysql_insert_id()."\n"); } else { print("SQL statement failed.\n"); print(mysql_errno($con).": ".mysql_error($con)."\n"); } mysql_close($con); ?>
The output confirms that the new was inserted correctly:
Number of rows inserted: 1 Last row ID inserted: 2
Note that mysql_query() returns TRUE/FALSE on INSERT INTO statements.
Last update: 2015.
Table of Contents
PHP Installation on Windows Systems
Integrating PHP with Apache Web Server
charset="*" - Encodings on Chinese Web Pages
Chinese Characters in PHP String Literals
Multibyte String Functions in UTF-8 Encoding
Input Text Data from Web Forms
Input Chinese Text Data from Web Forms
MySQL - Installation on Windows
►MySQL - Connecting PHP to Database
php_mysql.dll - Configuring PHP to Use MySQL Module
mysql_connect() - Creating MySQL Connections
►INSERT INTO - Inserting New Records
SELECT - Running Database Queries
UPDATE - Modifying Database Records
MySQL - Character Set and Encoding
MySQL - Sending Non-ASCII Text to MySQL
Retrieving Chinese Text from Database to Web Pages