Home Backend Development PHP Tutorial PHP database operations

PHP database operations

Aug 08, 2016 am 09:20 AM
mysql query quot user

Which databases does PHP support?

PHP implements database operations by installing corresponding extensions. The design of modern applications is inseparable from the application of databases. The current mainstream databases include MsSQL, MySQL, Sybase, Db2, Oracle, PostgreSQL, Access, etc., these databases PHP can install extensions to support it. Generally speaking, the LAMP architecture refers to: Linux, Apache, Mysql, PHP, so the Mysql database is widely used in PHP. We will discuss this in this chapter. Learn how to operate Mysql in a simple way.

Database extensions

A database in PHP may have one or more extensions, including official ones and those provided by third parties. Commonly used extensions for Mysql include the native mysql library, you can also use the enhanced version of mysqli extension, and you can also use PDO for connection and operation.

Different extensions provide basically similar operation methods. The difference is that they may have some new features and the operation performance may be different.

mysql extension method for database connection:

<span>$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password');</span><p><span>mysqli extension: </span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><span>$link = mysqli_connect('mysql_host', 'mysql_user', 'mysql_password');</span><p><span>PDO extension</span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><p><span>$dsn = 'mysql:dbname=testdb;host=127.0.0.1';</span></p><span></span><p><span>$user = 'dbuser';</span></p><p><span>$password = 'dbpass';</span></p><p><span>$dbh = new PDO($dsn, $user, $password);</span></p><divmicrosoft yahei sans gb neue font-size:14px line-height:21px><p><span>Connect to MySQL database</span></p> <divmicrosoft yahei sans gb neue font-size:14px line-height:21px margin:0px padding:0px word-break:break-all><p></p> <p><span>PHP needs to perform operations on the database Operation, the first thing to do is to establish a connection with the database. Usually we use the mysql_connect function to connect to the database. This function needs to specify the address, user name and password of the database. </span></p> <preubuntu mono line-height:1.6em font-size:13px word-break:break-word><p><span>$host = 'localhost';</span></p><span></span><p><span>$user = 'code1';</span></p><p><span>$link = mysql_connect($host, $user, $pass);</span></p><p><span>$pass = '';</span></p><p><span>The way PHP connects to the database is similar to connecting directly under the command line, similar to: <codeubuntu mono>mysql -hlocalhost -ucode1 -p, when the connection is successful, we need to select a database for operation and select the database through the mysql_select_db function. </codeubuntu></span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><span>mysql_select_db('code1');</span><p><span>Usually we will first set the character encoding used for the current connection. Generally, we will use utf8 encoding. </span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><span>mysql_query("set names 'utf8'");</span><p><span>Through the above steps, we have established a connection with the database and can perform data operations. </span></p><p><span>Execute MySQL query</span></p><divmicrosoft yahei sans gb neue font-size:13px line-height:1.6 margin:0px padding:0px word-break:break-all><divmicrosoft yahei sans gb neue font-size:14px><p><span>You can query after the database connection is established, and use the form of mysql_query plus sql statement to send query instructions to the database. </span></p> <preubuntu mono line-height:1.6em font-size:13px word-break:break-word><span>$res = mysql_query('select * from user limit 1');</span><p><span>For query class statements, a resource handle (resource) will be returned, and the data in the query result set can be obtained through this resource. </span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><p><span>$row = mysql_fetch_array($res);</span></p><span></span><p><span>var_dump($row);</span></p><p><span>By default, PHP uses the nearest database connection to execute the query, but if there are multiple connections, you can query from that connection through the parameter command. </span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><p><span>$link1 = mysql_connect('127.0.0.1', 'code1', '');</span></p><span></span><p><span>$link2 = mysql_connect('127.0.0.1', 'code1', '', true); //开启一个新的连接</span></p><p><span>$res = mysql_query('select * from user limit 1', $link1); //从第一个连接中查询数据</span></p><divmicrosoft yahei sans gb neue font-size:14px line-height:21px><p><span>Insert new data into MySQL</span></p> <divmicrosoft yahei sans gb neue font-size:14px line-height:21px><p></p> <p><span>After we understand how to use mysql_query for data query, then similarly, inserting data is actually achieved by executing a sql statement, for example: </span> </p> <preubuntu mono line-height:1.6em font-size:13px word-break:break-word><p><span>$sql = "insert into user(name, age, class) values('李四', 18, '高三一班')";</span></p><span></span><p><span>mysql_query($sql); //执行插入语句</span></p><p><span>Usually data is stored in variables or arrays, so the sql statement needs to be string spliced ​​first. </span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><p><span>$name = '李四';</span></p><span></span><p><span>$age = 18;</span></p><p><span>$class = '高三一班';</span></p><p><span>$sql = "insert into user(name, age, class) values('$name', '$age', '$class')";</span></p><p><span>mysql_query($sql); //执行插入语句</span></p><p><span>In mysql, after executing the insert statement, you can get the auto-incremented primary key id, which can be obtained through PHP's mysql_insert_id function. </span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><span>$uid = mysql_insert_id();</span><p><span>This ID is very useful. It can usually be used to determine whether the insertion is successful, or as an associated ID for other data operations. </span></p><p><span>Getting data query results</span></p><p><divmicrosoft yahei sans gb neue font-size:14px><p><span>Through the previous chapters, we found that operating the database in PHP is very similar to the operation on the MySql client. First connect, then execute the sql statement, and then get the results we want. set. </span></p> <p><span>PHP有多个函数可以获取数据集中的一行数据,最常用的是mysql_fetch_array,可以通过设定参数来更改行数据的下标,默认的会包含数字索引的下标以及字段名的关联索引下标。</span></p> <preubuntu mono line-height:1.6em font-size:13px word-break:break-word><p><span>$sql = "select * from user limit 1";</span></p><span></span><p><span>$result = mysql_query($sql);</span></p><p><span>$row = mysql_fetch_array($result);</span></p><p><span>可以通过设定参数MYSQL_NUM只获取数字索引数组,等同于mysql_fetch_row函数,如果设定参数为MYSQL_ASSOC则只获取关联索引数组,等同于mysql_fetch_assoc函数。</span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><p><span>$row = mysql_fetch_row($result);</span></p><span></span><p><span>$row = mysql_fetch_array($result, MYSQL_NUM); //这两个方法获取的数据是一样的</span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><p><span>$row = mysql_fetch_assoc($result);</span></p><span></span><p><span>$row = mysql_fetch_array($result, MYSQL_ASSOC);</span></p><p><span>如果要获取数据集中的所有数据,我们通过循环来遍历整个结果集。</span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><p><span>$data = array();</span></p><span></span><p><span>while ($row = mysql_fetch_array($result)) {</span></p><p><span> $data[] = $row;</span></p><p><span>}</span></p></preubuntu></preubuntu></preubuntu></preubuntu></divmicrosoft></p><divmicrosoft yahei sans gb neue font-size:14px line-height:21px><p>查询分页数据</p> <divmicrosoft yahei sans gb neue font-size:14px line-height:21px><p></p> <p>上一节中,我们了解到通过循环可以获取一个查询的所有数据,在实际应用中,我们并不希望一次性获取数据表中的所有数据,那样性能会非常的低,因此会使用翻页功能,每页仅显示10条或者20条数据。</p> <p>通过mysql的limit可以很容易的实现分页,limit m,n表示从m行后取n行数据,在PHP中我们需要构造m与n来实现获取某一页的所有数据。</p> <p>假定当前页为$page,每页显示$n条数据,那么m为当前页前面所有的数据,既$m = ($page-1) * $n,在知道了翻页原理以后,那么我们很容易通过构造SQL语句在PHP中实现数据翻页。</p> <preubuntu mono line-height:1.6em font-size:13px word-break:break-word background:rgb><p><span>$page = 2;</span></p><p><span>$n = 2;</span></p><p><span>$m = ($page - 1) * $n;</span></p><p><span>$sql = "select * from user limit $m, $n";</span></p><p><span>$result = mysql_query($sql);</span></p><p><span>//循环获取当前页的数据</span></p><p><span>while ($row = mysql_fetch_assoc($result)) {</span></p><p><span>$data = array();</span></p><p><span> $data[] = $row;</span></p><p><span>}</span></p><p>在上面的例子中,我们使用了$m与$n变量来表示偏移量与每页数据条数,但我们推荐使用更有意义的变量名来表示,比如$pagesize, $start, $offset等,这样更容易理解,有助于团队协作开发。</p><p></p><pre name="code"><?php //连接数据库 mysql_connect(&#39;127.0.0.1&#39;, &#39;code1&#39;, &#39;&#39;); mysql_select_db(&#39;code1&#39;); mysql_query("set names &#39;utf8&#39;"); //预设翻页参数 $page = 2; $pagesize = 2; //在这里构建分页查询 $count = ($page - 1) * $pagesize; $sql = "select * from user limit $count, $pagesize"; //获取翻页数据 $result = mysql_query($sql); $data = array(); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $data[] = $row; } echo &#39;<pre class="brush:php;toolbar:false">'; print_r($data); echo '';
Copy after login

更新与删除数据

数据的更新与删除相对比较简单,只需要构建好相应的sql语句,然后调用mysql_query执行就能完成相应的更新与删除操作。

$sql = "update user set name = '曹操' where id=2 limit 1"; if (mysql_query($sql)) { echo '更新成功'; }

同样的删除可以使用类似以下的代码:

$sql = "delete from user where id=2 limit 1"; if (mysql_query($sql)) { echo '删除成功'; }

对于删除与更新操作,可以通过mysql_affected_rows函数来获取更新过的数据行数,如果数据没有变化,则结果为0。

$sql = "update user set name = '曹操' where id=2 limit 1"; if (mysql_query($sql)) { echo mysql_affected_rows(); }

关闭MySQL连接

当数据库操作完成以后,可以使用mysql_close关闭数据库连接,默认的,当PHP执行完毕以后,会自动的关闭数据库连接。

mysql_close();

虽然PHP会自动关闭数据库连接,一般情况下已经满足需求,但是在对性能要求比较高的情况下,可以在进行完数据库操作之后尽快关闭数据库连接,以节省资源,提高性能。

在存在多个数据库连接的情况下,可以设定连接资源参数来关闭指定的数据库连接。

$link = mysql_connect($host, $user, $pass); mysql_close($link);



版权声明:本文为博主原创文章,未经博主允许不得转载。

以上就介绍了PHP数据库操作,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

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)

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

Centos install mysql Centos install mysql Apr 14, 2025 pm 08:09 PM

Installing MySQL on CentOS involves the following steps: Adding the appropriate MySQL yum source. Execute the yum install mysql-server command to install the MySQL server. Use the mysql_secure_installation command to make security settings, such as setting the root user password. Customize the MySQL configuration file as needed. Tune MySQL parameters and optimize databases for performance.

See all articles