search

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 '';

更新与删除数据

数据的更新与删除相对比较简单,只需要构建好相应的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
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
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools