Creating a connection between PHP and MySQL is fairly simple. PHP provides all of the functions you need to connect and extract data.
Before we begin have a database setup in MySQL and know the username, password and name of the database.
Create a table and add some default values into it. Remember the name of this table.
1) To connect to MySQL you really only need a few variables. To start, open notepad and add these lines:
These are the values that we will use to connect to MySQL from PHP. Replace all of these values with your MySQL values. $mysql_server = "localhost" can generally be as is.Code:<?php
// mysql config
$mysql_username = "yourname";
$mysql_password = "password";
$mysql_database = "db";
$mysql_server = "localhost";
2) Now we will connect to MySQL using the variables above:
As simple as that you have a connection to MySQL.Code:$link = mysql_connect($mysql_server, $mysql_username, $mysql_password);
mysql_select_db($mysql_database, $link);
3) Lets pull some data out of our DB. You should have the table name as stated above and I named mine tbl_tutorial so replace this with your table name. We now need to build a query
4) Execute the queryCode:$query = "SELECT * FROM tbl_tutorial";
This will actually make the query on the MySQL database. Once this has been done all we need to do is fetch the results and manipulate them.Code:$results = mysql_query($query, $link);
5) Display our results
The $row array will contain all of the fields in your table starting with 0 and ending with the number of rows - 1.Code:// Fetch results
while ($row = mysql_fetch_row($results)) {
// Data will be displayed in an array $row[0]
print "$row[0]<br>";
}
6) Close our connection
Thats it. I've attached the PHP file from this tutorial if you need to reference it.Code:// Close our connection
mysql_close($link);
?>


LinkBack URL
About LinkBacks









Reply With Quote




Bookmarks
Algorithms and Data Structures
Java tutorials
Algorithms Forum