PHP learning-two ways to connect to MySQL: mysql. PHP learning-two ways to connect to MySQL, two ways to record the two ways PHP connects to mysql. First mock the data, you can execute the SQL. * Create a database * creat php learning-two ways to connect to MySQL and two ways to connect to mysql
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.
Record two methods for connecting PHP to MySQL. First mock the data, you can execute the SQL. /* Create a database */CREAT...