PHP learning-two ways to connect to MySQL

Source: Internet
Author: User
: 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.