PHP learning-two ways to connect to MySQL: 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:
<? Php $ host = 'localhost'; $ database = 'test'; $ username = 'root'; $ password = 'root'; $ selectName = 'Harry '; // The user name to be searched, which is generally the user input $ connection = mysql_connect ($ host, $ username, $ password ); // connect to the database mysql_query ("set names 'utf8'"); // encode and convert if (! $ Connection) {die ("cocould not connect to the database. \ n ". mysql_error (); // diagnose a connection error} $ selectedDb = mysql_select_db ($ database); // select the database if (! $ SelectedDb) {die ("cocould not to the database \ n ". mysql_error ();} $ selectName = mysql_real_escape_string ($ selectName); // prevents SQL injection $ query = "select * from user where name = '$ selectName '"; // construct the query statement $ result = mysql_query ($ query); // execute the query if (! $ Result) {die ("cocould not to the database \ n ". mysql_error ();} while ($ row = mysql_fetch_row ($ result) {// retrieve the result and display $ name = $ row [0]; $ age = $ row [1]; echo "Name: $ name"; echo "Age: $ age"; echo "\ n ";}
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:
<? Php $ host = 'localhost'; $ database = 'test'; $ username = 'root'; $ password = 'root'; $ selectName = 'Harry '; // The user name to be searched, usually the user input information $ pdo = new PDO ("mysql: host = $ host; dbname = $ database", $ username, $ password ); // create a pdo object $ pdo-> 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.