Submitted by:David Villa

Date added:09 May, 2011


This is a general code to use when inserting an item from a MySQL database. This code isn't considered definitive and can be written in many varied ways.

An extention of this code would be to make sure the entry you are adding to the database doesn't already exist (to save dupicate entries).

Note: This code requires you to connect to the MySQL database to work. Also, all field and table names need to be set up to match.

This MYSQL Code using in PHP

Tags: insert statement , insert data in mysql db

Code Snippet:

//This example shows how to insert a variable in a databse (this example assumes the 'id' field is set to 'auto_increment').

$id = 1;
$my_variable1 = "insert me";
$my_variable2 = "insert me too!";

//MySQL string:
$sql = "INSERT INTO table_name (id, my_variable1, myvariable2) VALUES
('', '$my_variable1', '$my_variable2')";

$result = mysql_query($sql);

//Output a result
echo "Variables added to database!";
} else {
$message = "Failed to insert! This is the MySQL Error output:<br>" + mysql_error();