|
Main (PHP)
3rd Party Streams
Resources
Code Snippets
Affiliates
|
|
|
| |
Simple MySql Example |
| By admin (2009-02-10. 8231 views.) |
Quick overview of using PHP to connect to a MySql database, retrieve the rows of information and close out. |
|
Let's jump right in with a code sample:
<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');
// Performing SQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// Printing results in HTML
echo "<table>";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>";
foreach ($line as $col_value) {
echo "<td>$col_value</td>";
}
echo "</tr>";
}
echo "</table>";
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>
First we connect to the mysql database server using the mysql_connect function. The function returns a 'handle' to be used for subsequent access to the database. It is assumed that you have determined the host machine that the database server is running on, and have the credentials for accessing the database. Note, we have only connected to the server, not to to a specific database. Credentials in mysql are used at all levels of the server, including deciding which databases you can access.
Then we select the specific database we want to access on the connected server using the mysql_select_db function. Note, this does not return a value.
Then we formulate the SQL query string we want to use against the database. In this case we are getting all rows and all columns, *, from the my_table table in the my_database databae.
We perform the query using the mysql_query function. This function returns a 'result set'. The result set represents the entire result of your query.
We get the next row of data out of the result set using the mysql_fetch_array function. This function returns an array of values where every element of the array corresponds to a column in the current row of the table.
We release the result set using the mysql_free_result function. This is an important, but often overlooked step. In larger scale systems you must programmatically release any resources a specific use has gathered.
Lastly, we disconnect from the database using the mysql_close function. This function frees up a connection to the database represented by your handle. |
| |
|
| |
|
|
|
|
|
|
|
|
Top Sponsor
Sponsors
Sponsors
Advertisting
Affiliates
|
|