Table of Contents
 返回结果:
Home Backend Development PHP Tutorial PHP的MySQLi函数库的使用 以及 表单的字符编码配置

PHP的MySQLi函数库的使用 以及 表单的字符编码配置

Jun 23, 2016 pm 01:30 PM

1.什么是mysqli

PHP-MySQL 函数库是 PHP 操作 MySQL 资料库最原始的扩展库,PHP-MySQLi 的 i 代表 Improvement ,相当于前者的改进增强版,也包含了相对进阶的功能,另外本身也增加了安全性,比如可以大幅度减少 SQL 注入等问题的发生。


2. mysql与mysqli的概念相关

(1)mysql与mysqli都是php方面的函数集,与mysql数据库关联不大。

(2)在php5版本之前,一般是用php的mysql函数去驱动mysql数据库的,比如mysql_query()的函数,属于面向过程

(3)在php5版本以后,增加了mysqli的函数功能,某种意义上讲,它是mysql系统函数的增强版,更稳定更高效更安全,与mysql_query()对应的有mysqli_query(),属于面向对象,用对象的方式操作驱动mysql数据库


3. mysql与mysqli的主要区别

(1)mysql是非持继连接函数,mysql每次链接都会打开一个连接的进程,所以mysqli耗费资源少一些。

(2)mysqli是永远连接函数,mysqli多次运行mysqli将使用同一连接进程,从而减少了服务器的开销。mysqli封装了诸如事务等一些高级操作,同时封装了DB操作过程中的很多可用的方法。

(3)mysqli支持面向对象编程方式和面向过程编程方式,而mysql则只可以面向过程。


例如如下代码分别是mysqli的面向对象编程方式和面向过程方式

面向对象方式

<?php$mysqli = new mysqli("localhost","db_user","db_passwd","database");# check connectionif (mysqli_connect_errno()) {    printf ("Connect failed: %s\n",mysql_connect_error());    exit;}printf ("Host infomation: %s\n",$mysqli->host_info);# close connection$mysqli->close();?>
Copy after login


面向过程的方式

<?php$link = mysqli_connect("localhost","db_user","db_passwd","database");# check connectionif (!$link) {    printf("Connect failed: %s\n",mysqli_connect_error());    exit;}printf("Host infomation: %s\n",mysqli_get_host_info($link));#close connectionmysqli_close($link);?>
Copy after login

(4)mysqli 可以通过预处理语句来减少开销和SQL注入的风险,而mysql则做不到。


综上所述,如果大家用的是PHP5,而且mysql版本在5.0以上,希望大家以后能用mysqli的就尽量使用mqsqli,不仅高效,而且更安全,而且推荐大家使用面向对象编程方式。


在这里,我们也只介绍面向对象编程方式。


面向对象方式函数使用

1,连接数据库并获取相关信息

<?php    $mysqli = new mysqli("localhost","root","","mysql");        #如果连接失败    if (mysql_connect_errno()){        echo "数据库连接失败:".mysql_connect_error();        $mysqli = null;        exit();    }    #获取当前字符集    echo $mysqli->character_set_name()."<br>";        #获取客户端信息    echo $mysqli->get_client_info()."<br>";        #获取mysql主机信息    echo $mysqli->host_info."<br>";        #获取服务器信息    echo $mysqli->server_info."<br>";        #获取服务器版本    echo $mysqli->server_version."<br>";        #关闭数据库连接,严格来说,这并不是必要的,因为脚本执行完毕的时候他们将被自动关闭    $mysqli->close();?>
Copy after login

以上代码如果连接成功则运行结果

latin1mysqlnd 5.0.10 ? 20111026 ? $Id: e707c415db32080b3752b232487a435ee0372157 $localhost via TCP/IP5.6.12-log50612
Copy after login

如果连接失败则结果可能为

连接数据库失败:Access denied for user ‘root’@’localhost’ (using password: YES)连接数据库失败:Unknown database ‘hello’
Copy after login


2.查询数据

<?php    $mysqli = new mysqli("localhost","root","","test");    #如果连接失败    if (mysql_connect_errno()){        echo "数据库连接失败:".mysql_connect_error();        $mysqli = null;        exit();    }        #构造SQL语句    $query = "SELECT * FROM test ORDER BY id LIMIT 3";    #执行SQL语句    $result = $mysqli->query($query);        #遍历结果    while ($row = $result->fetch_array(MYSQLI_BOTH)){        echo "id".$row["id"]."<br>";    }    #释放结果集    $result=free();    #关闭连接    $mysqli->close();?>
Copy after login

运行结果

id10062id10063id10064
Copy after login


在这里需要注意的是

fetch_array(MYSQLI_BOTH)
Copy after login

这个方法,参数有三个,分别是MYSQLI_BOTH,MYSQLI_NUM,MYSQLI_ASSOC。

如果传入了MYSQLI_BOTH,返回数据的索引既包括数字和名称

array(size=26)    0=>string '10062'(length=5)    'id' => string '10062' (length=5)      1 => string '??' (length=2)      'name' => string '??' (length=2)      2 => string '10169103@qq.com' (length=17)      'email' => string '10169103@qq.com' (length=17)      3 => string '18366119732' (length=11)      'phone' => string '18366119732' (length=11)
Copy after login

其实还有等价的方法fetch_row(),fetch_assoc()

它们之间的关系如下

$result->fetch_row() =  mysql_fetch_row() = $result->fetch_array(MYSQLI_NUM) = mysql_fetch_array(MYSQLI_NUM)  返回索引数组$result->fetch_assoc() =  mysql_fetch_assoc() = $result->fetch_array(MYSQLI_ASSOC) = mysql_fetch_array(MYSQLI_ASSOC)  返回索引列名
Copy after login

如果fetch_array()方法什么也不传,则默认传入的是MYSQLI_BOTH


3,插入数据

<?php    $mysqli = new mysqli("localhost","root","","test");    #如果连接失败    if (mysql_connect_errno()){        echo "数据库连接失败:".mysql_connect_error();        $mysqli = null;        exit();    }        #插入数据    $sql = "INSERT INTO test(name,phone) values ("hello","10086")";    #执行插入语句    $result = $mysqli->query($sql);        #如果执行错误    if (!$result){        echo "SQL语句有误<br>";        echo "ERROR:".$mysqli->errno."|".$mysqli->error;        exit();    }    #如果插入成功,则返回影响的行数    echo $mysqli->affected_rows;    #关闭数据库连接    $mysqli->close();?>
Copy after login

如果插入成功,那么结果则会是1 ,如果失败,则会报错。


4,修改内容

<?php    $mysqli = new mysqli("localhost","root","","test");    #如果连接失败    if (mysql_connect_errno()){        echo "数据库连接失败:".mysql_connect_error();        $mysqli = null;        exit();    }    #执行语句    $sql = "update test set name = 'hello' where id = 10062";    #执行修改语句    $result = $mysqli->query($sql);    #如果执行错误    if (!$result){        echo "SQL语句有误<br>";        echo "ERROR:".$mysqli->errno."|".$mysqli->error;        exit();    }    #如果修改成功,则返回影响的行数    echo $mysqli->affected_rows;    #关闭数据库连接    $mysqli->close();?>
Copy after login

如果修改成功,同样返回被修改的行数。


5,预处理语句

<?php    $mysqli = new mysqli("localhost","root","","test");    #如果连接失败    if (mysql_connect_errno()){        echo "数据库连接失败:".mysql_connect_error();        $mysqli = null;        exit();    }    #准备好一条语句放到服务器中,比如插入语句    $sql = "INSERT INTO test(name,email) values (?,?)";        #生成预处理语句    $stmt = $mysqli->prepare($sql);        #给站位符号每个 ? 号传值(绑定参数)i d s b,没一个参数为格式化字符,ss代表两个字符串,d代表数字    $stmt = bind_param("ss",$name,$email);        #执行    $stmt->excute();        #为变量赋值    $name = "Mike";    $email = "mike@live.cn";        #执行    $stmt->execute();    #执行输出    echo "最后ID".$stmt->insert_id."<br>";    echo "影响了".$stmt->affected_rows."行<br>";        #关闭数据库连接    $mysqli->close();?>
Copy after login

通过以上的预处理语句,我们也可以实现数据的插入。


那么预处理有什么特点呢?

  • 效率上高,就是如果执行多次相同的语句,只有语句数据不同,因为将一条语句在服务器端准备好,然后将不同的值传给服务器,再让这条语句执行。相当于编译一次,使用多次。

  • 安全上:可以防止SQL注入 (?占位)这样就可以防止非正常的变量注入。



所以,推荐大家使用mysqli 的预处理语句方式,不仅效率高,而且更安全。




-------------------------------------------------------------------

关于html表单提交字符到MySQL中字符编码的问题


首先我们来看看html文件里面的代码

<html><body><form action="tt.php" method="post"><head>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">        <meta http-equiv="pragma" content="no-cache">Test input values to MySQL<br></head><br><input type="text" name="isbn" maxlength="13" size="13">  <input type="submit" value="提交"></body></html>
Copy after login

这里定义了一个表单,名称是isbn ,允许的数据类型为text

使用post方法传递到后端 tt.php 脚本页面中。


tt.php文件代码

<html><head>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">        <meta http-equiv="pragma" content="no-cache"></head><title>         Input to MySQL page!</title><h1 id="nbsp-返回结果"> 返回结果:</h1><?php//create short variable names$v = $_POST['isbn'];      //获取表单传递过来的值#判断如果值为空,那么打印错误信息,并退出。if (!$v) {        echo "you must input some values <br> Please go back and try again.";        exit;}#检查是否经过php的魔术字符转换if (!get_magic_quotes_gpc()){        $isbn = addslashes($v);}#定义一个数据库连接对象@ $db = new mysqli('211.162.188.60','test','123.com','test');#设置字符if ( $db->set_charset("utf8") ){    //注意这里是utf8  并不是utf-8        printf("Current charset is: %s <br>",$db->character_set_name());} else {        echo "Error: Could not set this charset !";}#检查是否连接数据库错误if (mysqli_connect_errno()) {        echo "Error: Could not connect to database. Please try again later.";        exit;}#插入数据$insert = "insert into ttt set S22 = '".$isbn."'";#执行插入操作$result = $db->query($insert);#检测是否执行成功if ($result) {        echo $db->affected_rows." values inserted into database."; //打印影响行数} else {        echo "An error has occurred. The item was not added.";}#关闭连接$db->close();?>
Copy after login

执行结果:

返回结果:Current charset is: utf8 .1 values inserted into database.
Copy after login

查看数据库

+----+------+--------------+| s1 | tax  | s22          |+----+------+--------------+|  0 | 1.00 | 测试数据     ||  0 | 1.00 | 测试数据     ||  0 | 1.00 | 测试数据     ||  0 | 1.00 | 测试数据     ||  0 | 1.00 | 测试数据     |+----+------+--------------+5 rows in set (0.02 sec)
Copy after login


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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
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 and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

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.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles