国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

PHP Tutorial
1502
276
Object-Relational Mapping (ORM) Performance Tuning in PHP Object-Relational Mapping (ORM) Performance Tuning in PHP Jul 29, 2025 am 05:00 AM

Avoid N 1 query problems, reduce the number of database queries by loading associated data in advance; 2. Select only the required fields to avoid loading complete entities to save memory and bandwidth; 3. Use cache strategies reasonably, such as Doctrine's secondary cache or Redis cache high-frequency query results; 4. Optimize the entity life cycle and call clear() regularly to free up memory to prevent memory overflow; 5. Ensure that the database index exists and analyze the generated SQL statements to avoid inefficient queries; 6. Disable automatic change tracking in scenarios where changes are not required, and use arrays or lightweight modes to improve performance. Correct use of ORM requires combining SQL monitoring, caching, batch processing and appropriate optimization to ensure application performance while maintaining development efficiency.

VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

A Deep Dive into PHP's Internal Garbage Collection Mechanism A Deep Dive into PHP's Internal Garbage Collection Mechanism Jul 28, 2025 am 04:44 AM

PHP's garbage collection mechanism is based on reference counting, but circular references need to be processed by a periodic circular garbage collector; 1. Reference count releases memory immediately when there is no reference to the variable; 2. Reference reference causes memory to be unable to be automatically released, and it depends on GC to detect and clean it; 3. GC is triggered when the "possible root" zval reaches the threshold or manually calls gc_collect_cycles(); 4. Long-term running PHP applications should monitor gc_status() and call gc_collect_cycles() in time to avoid memory leakage; 5. Best practices include avoiding circular references, using gc_disable() to optimize performance key areas, and dereference objects through the ORM's clear() method.

The Serverless Revolution: Deploying Scalable PHP Applications with Bref The Serverless Revolution: Deploying Scalable PHP Applications with Bref Jul 28, 2025 am 04:39 AM

Bref enables PHP developers to build scalable, cost-effective applications without managing servers. 1.Bref brings PHP to AWSLambda by providing an optimized PHP runtime layer, supports PHP8.3 and other versions, and seamlessly integrates with frameworks such as Laravel and Symfony; 2. The deployment steps include: installing Bref using Composer, configuring serverless.yml to define functions and events, such as HTTP endpoints and Artisan commands; 3. Execute serverlessdeploy command to complete the deployment, automatically configure APIGateway and generate access URLs; 4. For Lambda restrictions, Bref provides solutions.

Building Immutable Objects in PHP with Readonly Properties Building Immutable Objects in PHP with Readonly Properties Jul 30, 2025 am 05:40 AM

ReadonlypropertiesinPHP8.2canonlybeassignedonceintheconstructororatdeclarationandcannotbemodifiedafterward,enforcingimmutabilityatthelanguagelevel.2.Toachievedeepimmutability,wrapmutabletypeslikearraysinArrayObjectorusecustomimmutablecollectionssucha

Integrating PHP with Machine Learning Models Integrating PHP with Machine Learning Models Jul 28, 2025 am 04:37 AM

UseaRESTAPItobridgePHPandMLmodelsbyrunningthemodelinPythonviaFlaskorFastAPIandcallingitfromPHPusingcURLorGuzzle.2.RunPythonscriptsdirectlyfromPHPusingexec()orshell_exec()forsimple,low-trafficusecases,thoughthisapproachhassecurityandperformancelimitat

css dark mode toggle example css dark mode toggle example Jul 30, 2025 am 05:28 AM

First, use JavaScript to obtain the user system preferences and locally stored theme settings, and initialize the page theme; 1. The HTML structure contains a button to trigger topic switching; 2. CSS uses: root to define bright theme variables, .dark-mode class defines dark theme variables, and applies these variables through var(); 3. JavaScript detects prefers-color-scheme and reads localStorage to determine the initial theme; 4. Switch the dark-mode class on the html element when clicking the button, and saves the current state to localStorage; 5. All color changes are accompanied by 0.3 seconds transition animation to enhance the user

How to seed a database in Laravel? How to seed a database in Laravel? Jul 28, 2025 am 04:23 AM

Create a seeder file: Use phpartisanmake:seederUserSeeder to generate the seeder class, and insert data through the model factory or database query in the run method; 2. Call other seeder in DatabaseSeeder: register UserSeeder, PostSeeder, etc. in order through $this->call() to ensure the dependency is correct; 3. Run seeder: execute phpartisandb:seed to run all registered seeders, or use phpartisanmigrate:fresh--seed to reset and refill the data; 4

See all articles