Insert & Displaying Data
Insert data into Mysql Table |
The following example incert the data into
table named "Biodata", with three columns. The column names will be
"FirstName", "LastName" and "Age": <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_database", $con); mysql_query("INSERT INTO biodata (FirstName, LastName, Age) VALUES ('Scarlett', 'Clooney',25)"); mysql_query("INSERT INTO biodata (FirstName, LastName, Age) VALUES ('Kate', 'Eva',34)"); mysql_close($con); ?> |
Insert Data From a HTML Form Into a MySql Table |
The following example shows you the html form used to enter data
|
Codes for above form is as follows
<html> <body> <form action="insert.php" method="post"> Firstname: <input type="text" name="firstname" /> Lastname: <input type="text" name="lastname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> |
The Following php file send data into MySql table
<?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_database", $con); $sql="INSERT INTO biodata (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con); ?> |
Displaying Data
The following examples selects the data from the above MySql table and displays the data in HTML tables.Example-01 <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_database", $con); $result = mysql_query("SELECT * FROM biodata"); echo "<table border='1'> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['FirstName'] . "</td>"; echo "<td>" . $row['LastName'] . "</td>"; echo "<td>" . $row['Age'] . "</td>"; echo "</tr>"; } echo "</table>"; mysql_close($con); ?> |
Example-02 <?php $dbHost = 'localhost'; $dbUser = 'root'; $dbPass = ''; $dbName = 'my_database'; $dbConn = mysql_connect ($dbHost,$dbUser, $dbPass) or die ('MySQL connect failed. ' . mysql_error()); mysql_select_db($dbName) or die('Cannot select database. ' . mysql_error()); ?> <html> <head> <title>Display</title> </head> <table align="center" border=1> <tr> <th> First Name</th> <th>Last Name </th> <th> Age </th> </tr> <?php $query = "SELECT * FROM biodata"; $result = mysql_query($query); while ($row = mysql_fetch_assoc($result)){ ?> <tr><td><?php echo $row["FirstName"];?></td> <td><?php echo $row["LastName"];?></td> <td><?php echo $row["Age"];?></td> </tr> <?php }?> </table> </body> </html> |
No comments:
Post a Comment