For PHP entry-level users, we only need to master the basic database write, read, edit, delete and other basic operations. Even if we get started, we can also write simple programs, such as message book, news article system and so on. In the whole process, MySQL database connection is also more important, you can use a variety of methods to connect, for novices, we do not want to analyze which way for the optimization of system resources, we can first connect on the line.
Here, we sorts out several commonly used methods of PHP connecting to MySQL database. We can refer to them. I also make a record by the way.
First, common methods
$mysql_ server=”localhost”;
$mysql_ User name = database user name; < br > user name$mysql_ Password = database password; < br > password$mysql_ Database = < br > database name//Establish database links < br > and$conn = mysql_ connect($mysql_ server,$mysql_ username,$mysql_ Password) or die (“database link error”); < br > the//Select a databasemysql_ select_ db($mysql_ database,$conn);
mysql_ query(“set names ‘utf8′”);
//Execute MySQL < br > statements$result=mysql_ Query (“select id, name from database table”); < br > query//Extract data < br > from the database$row=mysql_ fetch_ row($result);
When extracting data, we use mysql_ fetch_ Row, you can also use mysql_ fetch_ Assoc and MySQL_ fetch_ Array, please refer to the manual for details.
Second, object-oriented method
$db=new mysqli($dbhost,$username,$userpass,$dbdatabase);
if(mysqli_ connect_ error()){
echo ‘Could not connect to database.’;
exit;
}$result=$db->query(“SELECT id,name FROM user”);
$row=$result->fetch_ row();
Third, PDO method
$dsn=’ mysql:host= ‘.$dbhost.’;dbname=’.$dbdatabase.’;’
$dbh=new PDO($dsn,$username,$userpass);$stmt=$dbh->query(‘SELECT id,name FROM user’);
$row=$stmt->fetch();
The above are three commonly used methods for PHP to connect to MySQL database. We can try to use them. Generally, we use the first method more.