Skip to content
Amal Hashim
All posts
Snippet

PHP - MySQL Insert

A basic PHP example that connects to MySQL, inserts a row and closes the connection.

1 min read#MySQL#PHP

A minimal example of inserting a row into a MySQL table from PHP. Change the server, credentials, database, table and column to match yours.

php
$dbServer = 'localhost';
$dbUserName = 'username';
$dbPassword = 'password';
$connection = mysql_connect($dbServer, $dbUserName, $dbPassword);
if (!$connection) {
    die('Connection Failed : ' . mysql_error());
}

$insertStatement = 'INSERT INTO TableName(Column) VALUES("Value")';
mysql_select_db('databaseName');
$returnValue = mysql_query($insertStatement, $connection);
if (!$returnValue) {
    die('Insertion Failed : ' . mysql_error());
}
echo "Data Inserted.";
mysql_close($connection);

The script stops with the MySQL error message if the connection or the insert fails.