search
HomeBackend DevelopmentPHP TutorialI suddenly found myself a little busy this week. . Playing-PHP advanced, a little busy-php_PHP tutorial

I suddenly found myself a little busy this week. . Just playing - PHP advanced, a little busy - php

 hi

It’s only Tuesday, but I suddenly realized that this week is a bit busy, and I’m still looking forward to it – I’ll go to the city this afternoon, come back to watch a movie in the evening, have a dinner party for hot pot tomorrow night, shoot a short film in the afternoon the day after tomorrow, and maybe in the evening To play, Friday, well, it’s Friday. Although I don’t even know how to write a (bian) weekly report if this continues, it’s still a good idea to do this.

1. PHP Advanced Completion

11. Database Operation

11.1 What 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 Extensions can be installed to support it. Generally speaking, the LAMP architecture refers to: Linux, Apache, Mysql, and PHP. Therefore, Mysql database is widely used in PHP. We will briefly understand the operation method of Mysql in this chapter.

11.2 Database Extension

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 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:

$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password');

mysqli extension:

$link = mysqli_connect('mysql_host', 'mysql_user', 'mysql_password');

PDO extension

$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);

$link = mysql_connect('127.0.0.1', 'code1', '') or die('Database connection failed');
mysql_select_db('code1');
mysql_query("set names 'utf8'");
$result = mysql_query('select * from user limit 1');
$row = mysql_fetch_assoc($result);
print_r($row) ;

11.3 Connecting to MySQL database

To operate the database in PHP, 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 requires specifying the address, username and password of the database.

$host = 'localhost';
$user = 'code1';
$pass = '';
$link = mysql_connect($host, $user, $pass);

The way PHP connects to the database is similar to connecting directly under the command line, similar to: 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.

mysql_select_db('code1');

Usually we will first set the character encoding used for the current connection. Generally, we will use utf8 encoding.

mysql_query("set names 'utf8'");

Through the above steps, we have established a connection with the database and can perform data operations.

$host = '127.0.0.1';
$user = 'code1';
$pass = '';
//Write the database connection code here
mysql_connect($host,$user,$pass);
mysql_select_db('code1');
mysql_query("set names 'utf8'");

11.4 Execute MySQL query

After establishing a connection to the database, you can query, using the form of mysql_query plus sql statement to send query instructions to the database.

$res = mysql_query('select * from user limit 1');

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.

$row = mysql_fetch_array($res);
var_dump($row);

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.

$link1 = mysql_connect('127.0.0.1', 'code1', '');
$link2 = mysql_connect('127.0.0.1', 'code1', '', true); //开启一个新的连接
$res = mysql_query('select * from user limit 1', $link1); //从第一个连接中查询数据

//Connect to the database
mysql_connect('127.0.0.1', 'code1', '');
mysql_select_db('code1');
mysql_query("set names 'utf8'");
//Perform data query here
$arr=mysql_query("select * from user limit 1");
$row=mysql_fetch_row($arr);
print_r($row);
echo $row[0];

11.5 Insert new data into MySQL

After we understand how to use mysql_query for data query, similarly, inserting data is actually achieved by executing a sql statement, for example:

$sql = "insert into user(name, age, class) values('李四', 18, '高三一班')";
mysql_query($sql); //执行插入语句

Usually data is stored in variables or arrays, so the sql statement needs to be string spliced ​​first.

$name = '李四';
$age = 18;
$class = '高三一班';
$sql = "insert into user(name, age, class) values('$name', '$age', '$class')";
mysql_query($sql); //执行插入语句

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.

$uid = mysql_insert_id();

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.

11.6 Get data query results

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 obtain the result set we want.

PHP has multiple functions that can obtain a row of data in the data set. The most commonly used is mysql_fetch_array. You can change the subscript of the row data by setting parameters. The default will include the subscript of the numeric index and the associated index of the field name. subscript.

$sql = "select * from user limit 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);

可以通过设定参数MYSQL_NUM只获取数字索引数组,等同于mysql_fetch_row函数,如果设定参数为MYSQL_ASSOC则只获取关联索引数组,等同于mysql_fetch_assoc函数。

$row = mysql_fetch_row($result);
$row = mysql_fetch_array($result, MYSQL_NUM); //这两个方法获取的数据是一样的
$row = mysql_fetch_assoc($result);
$row = mysql_fetch_array($result, MYSQL_ASSOC);

如果要获取数据集中的所有数据,我们通过循环来遍历整个结果集。

$data = array();
while ($row = mysql_fetch_array($result)) {
    $data[] = $row;
}

//连接数据库
mysql_connect('127.0.0.1', 'code1', '');
mysql_select_db('code1');
mysql_query("set names 'utf8'");
//数据预处理 防止查询不到数据
mysql_query("insert into user(name, age, class) values('王二', 19, '高三五班')");
//进行数据查询
$sql = "select * from user limit 1";
$result = mysql_query($sql);

//在这里获取一行数据
$row=mysql_fetch_assoc($result);

echo '

';<br>print_r($row);<br>echo '
';

11.7 查询分页数据

上一节中,我们了解到通过循环可以获取一个查询的所有数据,在实际应用中,我们并不希望一次性获取数据表中的所有数据,那样性能会非常的低,因此会使用翻页功能,每页仅显示10条或者20条数据。

通过mysql的limit可以很容易的实现分页,limit m,n表示从m行后取n行数据,在PHP中我们需要构造m与n来实现获取某一页的所有数据。

假定当前页为$page,每页显示$n条数据,那么m为当前页前面所有的数据,既$m = ($page-1) * $n,在知道了翻页原理以后,那么我们很容易通过构造SQL语句在PHP中实现数据翻页。

$page = 2;
$n = 2;
$m = ($page - 1) * $n;
$sql = "select * from user limit $m, $n";
$result = mysql_query($sql);
//循环获取当前页的数据
$data = array();
while ($row = mysql_fetch_assoc($result)) {
    $data[] = $row;
}

在上面的例子中,我们使用了$m与$n变量来表示偏移量与每页数据条数,但我们推荐使用更有意义的变量名来表示,比如$pagesize, $start, $offset等,这样更容易理解,有助于团队协作开发。

//连接数据库
mysql_connect('127.0.0.1', 'code1', '');
mysql_select_db('code1');
mysql_query("set names 'utf8'");
//预设翻页参数
$page = 2;
$pagesize = 2;
//在这里构建分页查询
$start=($page-1)*$pagesize;

$sql="SELECT * FROM user LIMIT $start,$pagesize";

//获取翻页数据
$result = mysql_query($sql);
$data = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$data[] = $row;
}
echo '

';<br>print_r($data);<br>echo '
';

11.8 更新与删除数据

数据的更新与删除相对比较简单,只需要构建好相应的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_connect('127.0.0.1', 'code1', '');
mysql_select_db('code1');
mysql_query("set names 'utf8'");
//预设数据以便进行更新操作
mysql_query("insert into user(name, age, class) values('王二', 19, '高三五班')");
$id = mysql_insert_id();
//在这里更新id为$id的行的名字为李白
$sql="update user set name='李白' where id=$id limit 1";
mysql_query($sql);
//输出更新数据条数
echo '数据更新行数:'.mysql_affected_rows();
mysql_query("delete from user where id='$id'");

11.9 关闭MySQL连接

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

mysql_close();

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

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

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

//连接数据库
$con=mysql_connect('127.0.0.1', 'code1', '');
mysql_select_db('code1');
mysql_query("set names 'utf8'");
//在这里关闭数据库连接

mysql_close($con);

 

 

 

 

 

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1077136.htmlTechArticleI suddenly found myself a little busy this week. . Playing - PHP advanced, a little busy - php hi It’s only Tuesday, but I suddenly realized that I am a little busy playing this week. I am still looking forward to going to the city this afternoon, late...
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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

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 Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.