Table of Contents
Basic tutorial on PHP connection and operation of MySQL database, basic tutorial on mysql
Steps for PHP to operate mysql database
How to connect php to Mysql database problem
Home Backend Development PHP Tutorial PHP connection and operation MySQL database basic tutorial, mysql basic tutorial_PHP tutorial

PHP connection and operation MySQL database basic tutorial, mysql basic tutorial_PHP tutorial

Jul 13, 2016 am 10:17 AM
mysql mysql database php operate database connect

Basic tutorial on PHP connection and operation of MySQL database, basic tutorial on mysql

Start here

My blog, what is the backend database? That's right, it's MySQL, the script used on the server side is PHP, and the entire framework uses WordPress. PHP and MySQL are like a couple, always working together. Now here, we will gather PHP and summarize the actual use of MySQL, which can also be regarded as an introduction to MySQL development. Regarding the cooperation between PHP and MySQL, there are no more than the following three methods:

1.mysql extension; but its use is no longer recommended;

2.mysqli extension; provides both object-oriented style and process-oriented style; requires MySQL version 4.1 and above;

3. The PDO extension defines a lightweight consistent interface for PHP to access the database; PDO_MYSQL is its specific implementation. We are only concerned with development for now. Since the mysql extension is no longer recommended, I will keep pace with the times and will not make a summary. Mysqli and PDO methods are used more often, so this article will summarize how to use the mysqli extension to connect to the database server, how to query and obtain data, and how to perform other important tasks. The next blog post will summarize the relevant content of PDO.

Use mysqli extension

First look at the test data in the following test database db_test:

Copy code The code is as follows:

mysql> select * from tb_test;
+----+-----------+----------+----------------+-------- ----+
| id | firstname | lastname | email | phone |
+----+-----------+----------+----------------+-------- ----+
| 1 | Young | Jelly | 123@qq.com | 1384532120 |
| 3 | Fang | Jone | 456@qq.com | 1385138913 |
| 4 | Yuan | Su | 789@qq.com | 1385138913 |
+----+-----------+----------+----------------+-------- ----+
3 rows in set (0.00 sec)

1. Establishing and disconnecting

When interacting with a MySQL database, the connection must be established first and disconnected last; this includes connecting to the server and selecting a database, and finally closing the connection and releasing resources. Choosing to use the object-oriented interface to interact with the MySQL server, you first need to instantiate the mysqli class through its constructor.

Copy code The code is as follows:

// Instantiate mysqli class
$mysqliConn = new mysqli();
// Connect to the server and select a database
$mysqliConn->connect('127.0.0.1', 'root', 'root', 'db_test');
Printf("MySQL error number:%d", $mysqliConn->errno);
// or
// $mysqliConn->connect("http://127.0.0.1", 'root', 'root');
// $mysqliConn->select_db('db_test');
 
//Interact with database
 
//Close connection
$mysqliConn->close();
?>

Once the database is successfully selected, you can then perform database queries against this database. Once the script has finished executing, all open database connections are automatically closed and resources are released. However, it is possible that a page requires multiple database connections during execution, and each connection should be closed appropriately. Even if only one connection is used, it is a good practice to close it at the end of the script. In any case, close() is responsible for closing the connection.

2. Handling connection errors

Of course, if you cannot connect to the MySQL database, it is unlikely that you can continue to complete the expected work on this page. Therefore, be sure to monitor connection errors and react accordingly. The mysqli extension package contains many features that can be used to capture error messages. You can also use exceptions to do this. For example, you can use the mysqli_connect_errno() and mysqli_connect_error() methods to diagnose and display information about a MySQL connection error.

Detailed information about mysqli can be viewed here: http://php.net/manual/zh/book.mysqli.php

Interacting with the database

The vast majority of queries are related to create, get, update, and delete tasks, which are collectively called CRUD. Here we begin to summarize CRUD-related content.

1. Send query to database

The method query() is responsible for sending the query to the database. It is defined as follows:

Copy code The code is as follows:

mixed mysqli::query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

The optional parameter resultmode can be used to modify the behavior of this method. It accepts two possible values. This article summarizes the differences between the two. http://www.bkjia.com/article/55792.htm; The following is a simple usage example:

Copy code The code is as follows:

// Instantiate mysqli class
$mysqliConn = new mysqli();

// Connect to the server and select a database
// Wrong password
$mysqliConn->connect('127.0.0.1', 'root', 'root', 'db_test');
If ($mysqliConn->connect_error)
{
              printf("Unable to connect to the database:%s", $mysqliConn->connect_error);
exit();
}
 
//Interact with database
$query = 'select firstname, lastname, email from tb_test;';

//Send query to MySQL
$result = $mysqliConn->query($query);

// Iterative processing result set
While (list($firstname, $lastname, $email) = $result->fetch_row())
{
                 printf("%s %s's email:%s
", $firstname, $lastname, $email);
}
 
//Close connection
$mysqliConn->close();
?>

2. Insert, update and delete data

Insert, update and delete are completed using insert, update and delete queries, which are actually the same as select queries. The sample code is as follows:

Copy code The code is as follows:

// Instantiate mysqli class
$mysqliConn = new mysqli();

// Connect to the server and select a database
// Wrong password
$mysqliConn->connect('127.0.0.1', 'root', 'root', 'db_test');
If ($mysqliConn->connect_error)
{
             printf("Unable to connect to the database:%s", $mysqliConn->connect_error);
exit();
}
 
//Interact with database
$query = 'select firstname, lastname, email from tb_test;';
//Send query to MySQL
$result = $mysqliConn->query($query);

// Iterative processing result set
While (list($firstname, $lastname, $email) = $result->fetch_row())
{
                 printf("%s %s's email:%s
", $firstname, $lastname, $email);
}
 
$query = "delete from tb_test where firstname = 'Yuan';";
$result = $mysqliConn->query($query);

// Tell the user how many rows were affected
Printf("%d row(s) have been deleted.
", $mysqliConn->affected_rows);
// Re-query the result set
$query = 'select firstname, lastname, email from tb_test;';

//Send query to MySQL
$result = $mysqliConn->query($query);

// Iterative processing result set
While (list($firstname, $lastname, $email) = $result->fetch_row())
{
                 printf("%s %s's email:%s
", $firstname, $lastname, $email);
}
//Close connection
$mysqliConn->close();
?>

3. Release query memory

Sometimes a particularly large result set may be obtained, and once processing is completed, it is necessary to release the memory requested by the result set. The free() method can complete this task for us. For example:

Copy code The code is as follows:

//Interact with the database
$query = 'select firstname, lastname, email from tb_test;';

// Send query to MySQL
$result = $mysqliConn->query($query);

// Iteratively process the result set
while (list($firstname, $lastname, $email) = $result->fetch_row())
{
Printf("%s %s's email:%s
", $firstname, $lastname, $email);
}
$result->free();

4. Parse query results

Once the query has been executed and the result set has been prepared, it is time to parse the resulting rows. You can use multiple methods to get the fields in each row. Which method you choose mainly comes down to personal preference, because only the method of referencing the fields differs.

(1) Put the result into the object

Use the fetch_object() method to complete. The fetch_object() method is usually called in a loop. Each call causes the next row in the returned result set to be filled in with an object. This object can then be accessed according to PHP's typical object access syntax. For example:

Copy code The code is as follows:

//Interact with the database
$query = 'select firstname, lastname, email from tb_test;';

// Send query to MySQL
$result = $mysqliConn->query($query);

// Iteratively process the result set
while ($row = $result->fetch_object())
{
$firstname = $row->firstname;
$lastname = $row->lastname;
$email = $row->email;
}
$result->free();

(2) Use index array and associative array to obtain results

The mysqli extension package also allows the use of associative arrays and index arrays to manage result sets through the fetch_array() method and the fetch_row() method respectively. The fetch_array() method can actually obtain each row of the result set as an associative array, a numeric index array, or both. It can be said that fetch_row() is a subset of fetch_array. By default, fetch_array() will obtain both associative arrays and index arrays. You can pass parameters in fetch_array to modify this default behavior.

MYSQLI_ASSOC, returns rows as an associative array, with keys represented by field names and values ​​represented by field contents;
MYSQLI_NUM, returns the row as a numeric index array, the order of its elements is determined by the order of the field names specified in the query;
MYSQLI_BOTH is the default option.

Identify selected rows and affected rows

It is often desirable to be able to determine the number of rows returned by a select query, or the number of rows affected by insert, update, or delete.

(1) Determine the number of rows returned

The num_rows attribute is useful if you want to know how many rows the select query statement returned. For example:

Copy code The code is as follows:

//Interact with the database
$query = 'select firstname, lastname, email from tb_test;';

// Send query to MySQL
$result = $mysqliConn->query($query);

// Get the number of rows
$result->num_rows;

Remember, num_rows is only useful when determining the number of rows obtained by a select query. If you want to obtain the number of rows affected by insert, update, or delete, you must use the affected_rows attribute summarized below.

(2) Determine the number of affected rows

The affected_rows attribute is used to get the number of rows affected by insert, update or delete. See the code above for a code example.

Execute database transaction

There are 3 new methods that enhance PHP’s ability to execute MySQL transactions, namely:

1.autocommit function, enable automatic submission mode;

The autocommit() function controls the behavior of MySQL auto-commit mode. The parameters passed in determine whether to enable or disable auto-commit; pass in TRUE to enable auto-commit, and pass in false to disable auto-commit. Whether enabled or disabled, TRUE will be returned on success and FALSE on failure.

2.commit function, commits the transaction; submits the current transaction to the database, returns TRUE if successful, otherwise returns FALSE.

3.rollback function, rolls back the current transaction, returns TRUE if successful, otherwise returns FALSE.

Regarding transactions, I will continue to summarize them later. Here is a brief summary of these three APIs.

It won’t end

This is just the beginning of learning MySQL and it will not end. Keep up the good work.

Steps for PHP to operate mysql database

$conn=mysql_pconnect("localhost","root","123456");//Open the connection
mysql_select_db("database name",$conn);//Connect to the specified database
mysql_query ("set names utf8");//Set character encoding
$sql="";
$R=mysql_query($sql);//Execute SQL statements to return the result set
while($v= mysql_fetch_array($R)){
echo "field name".$v['title'];
}

How to connect php to Mysql database problem

$hostname = "localhost";//Host address, generally no need to change
$database = "zx_title";//Database table name
$username = "root" ;//User name, the default is generally root
$password = "123";//Password for mysql database
$conn= mysql_pconnect($hostname, $username, $password) or trigger_error(mysql_error() ,E_USER_ERROR);
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/887352.htmlTechArticleBasic tutorial on PHP connection and operation of MySQL database, basic mysql tutorial starts here on my blog, what is the background database? That's right, it's MySQL, and the script used on the server side is P...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1254
29
C# Tutorial
1228
24
MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Oracle's Role in the Business World Oracle's Role in the Business World Apr 23, 2025 am 12:01 AM

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

How to safely store JavaScript objects containing functions and regular expressions to a database and restore? How to safely store JavaScript objects containing functions and regular expressions to a database and restore? Apr 19, 2025 pm 11:09 PM

Safely handle functions and regular expressions in JSON In front-end development, JavaScript is often required...

Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

SQL vs. MySQL: Clarifying the Relationship Between the Two SQL vs. MySQL: Clarifying the Relationship Between the Two Apr 24, 2025 am 12:02 AM

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

Compare and contrast MySQL and MariaDB. Compare and contrast MySQL and MariaDB. Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

Redis: Understanding Its Architecture and Purpose Redis: Understanding Its Architecture and Purpose Apr 26, 2025 am 12:11 AM

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

See all articles