Online computer courses, code, programming tutorial and sidebar information for monitoring Canadian S&P/TSX index. Build friendship and networking. Welcome to visit my blogs often!!! I also have two other sites: YouTube Channel and Google site.
Adsense
Popular Posts
- PHPWind-- A PHP forum script applcaition in China
- How to blend adsense inside your post?
- Formatting my post
- Notepad++ - Add C++ compiler
- Install PHPMailer 5.2.4 and use smtp gmail
- Set up a child account and set screen time limit in Windows 8
- Wayback Machine - see archived versions of web pages across time
- phpexcel toggle expand and hide column in EXCEL and summary
- Install PHP ibm_db2 extension in Linux (redHat)
- PHP: add a download as pdf file button in report page
Tuesday, December 18, 2012
Using MySQL In PHP Demo
Give a brief introduction how to connect to MySQL in PHP (mysql_connect), how to use mysql_fetch_row and mysql_fetch_array.
1) Connect to MySQL dataase
config.inc.php
<?php
//Example of using MySQL in PHP
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "test";
$con=mysql_connect("$db_host","$db_username","$db_pass");
if($con)
{echo "connect to MySQL server ".$db_host."<br />";}
else die ("could not connect to mysql");
if(mysql_select_db("$db_name"))
{echo "connect to dtabase ".$db_name."<br />";}
else die("no database");
?>
2) Create guestbook table and insert three rows
CREATE TABLE `guestbook` (
`id` int(11) NOT NULL auto_increment,
`FirstName` varchar(100) NOT NULL default '',
`LastName` varchar(100) NOT NULL default '',
UNIQUE KEY `id` (`id`)
);
INSERT INTO `guestbook` (`FirstName`,`LastName`)
VALUES ('John', 'Smith'), ('Tom', 'Lu'), ('Mike','Xu');
3) Example of mysql_fetch_row
<?php
include('config.inc.php');
$query = "SELECT * from guestbook";
$result = mysql_query($query);
//Fetch each row
while($thisrow=mysql_fetch_row($result))
{
$i=0;
//Fetch each column
while ($i < mysql_num_fields($result))
{
$field_name=mysql_fetch_field($result, $i);
//Display all the fields on one line
echo $thisrow[$i] . " ";
$i++;
}
echo "<br>";
}
mysql_close($con);
?>
4) Example of mysql_fetch_array.
<?php
include('config.inc.php');
$query = "SELECT * from guestbook";
$result = mysql_query($query);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Video of this tutorial
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment