Inserting data into MySql database using php

In my last post, I have discussed about displaying a table from mysql database using php. Click here to read my previous post.

This program is about inserting a new record into the database using php. To insert a new rcord into the databse, the program is kind of similar to the displaying the table but one extra piece of code is needed.

For SQL, we use the "Insert" query to enter a new record into the database. If you don't know the format of the "Insert" query then here it is.

INSERT INTO table_name VALUES("col1","col2",......);

Now, here is the php code.

<?php
$connection=mysql_connect("localhost","root","")
   or die("Couldn't connect to the server");
$db=mysql_select_db("produce",$connection)
   or die ("Couldn't select database");
$result=mysql_query("INSERT INTO fruit VALUES('PINEAPPLE','04','20KG')");
$result=mysql_query("SELECT * FROM fruit"); 
echo "<table border='1'>";
echo "<tr>";
echo "<th>Name</th><th>Number</th><th>Quantity</th>";
echo "</tr>";
while($row=mysql_fetch_array($result))
{
     echo "<tr>";
     echo "<td>",$row['name'],"</td><td>",$row['number'],"  
     </td><td>",$row['quantity'],"</td>";
      echo "</tr>";
}
echo "</table>";
mysql_close($connection);
?>


Output before running the php file.
NameNumberQuantity
APPLE15KG
MANGO210KG
Orange315kg

Output after running the php file
NameNumberQuantity
APPLE15KG
MANGO210KG
Orange315kg
PINEAPPLE420KG
   


NOTE : If you keep on refreshing the page it will keep on adding the same row like this .

NameNumberQuantity
APPLE15KG
MANGO210KG
Orange315kg
PINEAPPLE420KG
PINEAPPLE420KG
PINEAPPLE420KG
PINEAPPLE420KG
PINEAPPLE420KG
                

Top