: This article describes how to connect to MySQL through PHP learning. For more information about PHP tutorials, see. Record two methods for connecting PHP to MySQL.
First mock the data, you can execute the SQL.
/* Create database */create database if not exists 'test';/* Select DATABASE */USE 'test '; /* create table */create table if not exists 'user' (name varchar (50), age int);/* INSERT test data */insert into 'user' (name, age) VALUES ('Harry ', 20), ('Tony', 23), ('Harry ', 24 );
The first is to use PHP native methods to connect to the database. The code is as follows:
The running structure is as follows:
Name: harry Age: 20 Name: tony Age: 23
The second method is to use PDO to connect to the database. the code is as follows:
Exec ("set names 'utf8'"); $ SQL = "select * from user where name =? "; $ Stmt = $ pdo-> prepare ($ SQL); $ rs = $ stmt-> execute (array ($ selectName); if ($ rs) {// PDO: FETCH_ASSOC join array form // PDO: FETCH_NUM numeric index array form while ($ row = $ stmt-> fetch (PDO: FETCH_ASSOC )) {$ name = $ row ['name']; $ age = $ row ['age']; echo "name: $ Name"; echo "age: $ Age "; echo "\ n" ;}}$ pdo = null; // close the connection
The result is the same as the first one.
The above introduces the PHP learning-two ways to connect to MySQL, including content, hope to be helpful to friends who are interested in PHP tutorials.