Delicious Bookmark this on Delicious

MySQL database entries - Creating a new entry in a MySQL database table


There you go ... now that you know how to create a MySQL database table, you (eventually) want to be able to store a new entry within your database. This is achieved with the SQL command INSERT according to the following syntax:

INSERT INTO table_name (field_i, field_j, ...)
VALUES (value_i, value_j, ...)

  • where field_i denotes the name of the field i, in which value_i will be inserted. Note that field_i must not be put between quotes, while value_i must be put between double quotes.

Computer Forums

MySQL database entries - Creating a new entry in a MySQL database table


In orde to delete an entry from a database table, you must use the SQL command DELETE FROM ... WHERE, whose SQL syntax is as follows:


DELETE FROM table_name WHERE field_name = value_i;

  • where table_name and field_name are not put between quotes.
  • where value_i, the value you are searching for, is put between double quotes.

Here is an example in PHP illustrating the creation of new table entries followed by their deletion from within your PHP script:


Learn the PHP and MySQL code:

<?php
$connection = mysql_connect('localhost', 'john', 'secret');
if (!$connection) die('An error has occured during the connection');
mysql_query('CREATE DATABASE your_database', $connection);
mysql_select_db('your_database',$connection);
mysql_query('CREATE TABLE your_table (ClientID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(ClientID), Client_Address TEXT)',$connection);
mysql_query('INSERT INTO your_table (Client_Address) VALUES ("Somewhere in Paris")',$connection);
mysql_query('INSERT INTO your_table (Client_Address) VALUES ("Somewhere in New York")',$connection);
mysql_query('DELETE FROM your_table WHERE Client_Addree = "Somewhere in New York"',$connection);
?>



Remarks:

  • The above assumes that you have already selected the appropriate database using the PHP function mysql_select_db.
  • You do not necessarily have to include the SQL command directly within mysql_query. Instead, you can store the string of the SQL command within a variable $command and then execute it with the PHP code mysql_query($commands,$connection).
  • You will notice that the field ClientID is first set to 1 for the first entry, and then is automatically incremented by 1 for each subsequent entry. This is made possible by the use of the setting AUTO_INCREMENT and is necessary because ClientID is the primary key of the table.

You have just learned how to insert or remove new intries within a database table. Ib the next turorial, you will see how to perform searches among database tables' entries and thus how to quickly make available the information that was stored during the execution of your PHP scripts.


Computer Forums

Next tutorial: SQL SELECT (MySQL database search)
Previous tutorial: Creating or deleting a MySQL database

Back to computer forums