In the website background, you often have to deal with databases. This article describes how to use XAMPP to manage MySql Databases and How to Use PHP to access MySql databases.
1. Use XAMPP to manage MySql Databases
Use XAMPP to open the MySql Management page. Follow these steps: Start XAMPP and click Admin to go to the home page of XAMPP for Windows. Click phpMyAdmin on the home page.
On the phpMyAdmin page, create a database test and create a t_student table in the database. The table contains three fields: id, name, and age.
Then you can start to use PHP to access the MySql database. Since PHP has encapsulated the MySql database, it is very easy to access MySql with PHP.
Ii. PHP accessing MySql database
The following PHP program accesses the t_student table in the test database, reads data, and outputs data in the form of tables. The Code is as follows:
// By MoreWindows (http://blog.csdn.net/MoreWindows)
// Define a constant
Define (DB_HOST, 'localhost ');
Define (DB_USER, 'root ');
Define (DB_PASS, '123 ');
Define (DB_DATABASENAME, 'test ');
Define (DB_TABLENAME, 't_ student ');
// Name of the database table column
$ Dbcolarray = array ('id', 'name', 'age ');
// Mysql_connect
$ Conn = mysql_connect (DB_HOST, DB_USER, DB_PASS) or die ("connect failed". mysql_error ());
Mysql_select_db (DB_DATABASENAME, $ conn );
// Read the number of records in the table
$ SQL = sprintf ("select count (*) from % s", DB_TABLENAME );
$ Result = mysql_query ($ SQL, $ conn );
If ($ result)
{
$ Count = mysql_fetch_row ($ result );
}
Else
{
Die ("query failed ");
}
Echo "the table has $ count [0] records <br/> ";
$ SQL = sprintf ("select % s from % s", implode (",", $ dbcolarray), DB_TABLENAME );
$ Result = mysql_query ($ SQL, $ conn );
// Table
Echo '<table id = "Table" border = 1 cellpadding = 10 cellspacing = 2 bordercolor = # ffaaoo> ';
// Header
$ Thstr = "<th>". implode ("</th> <th>", $ dbcolarray). "</th> ";
Echo $ thstr;
// Table content
While ($ row = mysql_fetch_array ($ result, MYSQL_ASSOC) // equivalent to $ row = mysql_fetch_assoc ($ result)
{
Echo "<tr> ";
$ Tdstr = "";
Foreach ($ dbcolarray as $ td)
$ Tdstr. = "<td> $ row [$ td] </td> ";
Echo $ tdstr;
Echo "</tr> ";
}
Echo "</table> ";
Mysql_free_result ($ result );
Mysql_close ($ conn );
The running result is as follows:
This HTML element is completely output by PHP, in the next article, we will introduce how to use smarty to read databases and add the function of setting the color of table parity in "add, delete, modify, and set the color of parity rows in jquery table.
From MoreWindows