Retrieve data
from MySQL database using php
Before you start this lesson, I assume that you finished reading
the following tutorials:
- install phpmyAdmin, mysql , php
- Create Database by using phpMyAdmin
- Working with forms
- Insert Form Data into Database
In this lesson, we will learn how to retrieve data from MySQL database.We
will retrieve phone number based on name input.
Collect input Form
We build a "form" like the following
<form action="action.php" method="post">
<input type="text" name="name"><br>
<input type="submit">
</form>
Save the above code to a HTML file in your c:\inetpub\wwwroot(see Install
phpMyAdmin,MySql, PHP for detail)
PHP Retrieve data from Mysql
In the lesson Working with Forms ,
we already know how to get form input in php.
We use the following code to retrieve phone number associated with
name input.
<html>
<body>
<?php
$username="root";
$password="123456";
$database="phonebook";
//connect to database
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die("<b>Unable to specified
database</b>");
$name=$_POST['name'];
//perform query
$query = "select * from contact where name='$name'";
$result=mysql_query($query) or die('Error, insert query failed');
//get result
$phone=mysql_result($result,0,"phonenumber");
echo "Hi! $name. Your phone number is <b> $phone</b> ";
?>
</body>
</html>
Save above code to "acion.php".
In the above code, we used two new Mysql function: mysql_query and
mysql_result(). mysql_resul syntax
is
mysql_result(result resource,int row,[column name]). In
this example, result resource is $result, row is 0(the first row),
column name is "phonenumber".
Test it like the following:
Load the HTML file to your browser like http://localhost/myhtml.html,
then type name in. You should be able to retrieve its phone number.
|