MySQL数据库操作中参数绑定的使用

主要是总结一下进行常用数据库查询(操作)时常常用到的包括PDOmysqli中应该注意的参数绑定,以降低被sql注入的风险。

mysqli连接数据库时,使用函数bind_param()

使用范例:

<?php
mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}stmt = mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");stmt->bind_param('sssd', code,language, official,percent);

code = 'DEU';language = 'Bavarian';
official = "F";percent = 11.2;

/* execute prepared statement */
stmt->execute();

printf("%d Row inserted.\n",stmt->affected_rows);

/* close statement and connection */
stmt->close();

/* Clean up table CountryLanguage */mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", mysqli->affected_rows);

/* close connection */mysqli->close();
?>

这里要注意的是他的第一个参数,表示的是参数数量以及对应参数的type(数据类型)。参数数量必须与prepare()中的相对应,数据类型有以下这些:

i - integer 整型
s - string 字符串
d - double 双精度浮点型
b - blob 布尔型

PDO中,使用bindParam()

使用范例:

$db_host = 'localhost';
$db_name = 'student';
$db_user = 'root';
$db_pwd = '';
$dsn = "mysql:host=$db_host;dbname=$db_name";
$pdo = new PDO($dsn,$db_user,$db_pwd);
$pdo->query('set names utf8');
$query = "insert into tb_chengji set xuesheng=:xuesheng,yuwen=:yuwen";
$result = $pdo->prepare($query);

$xuesheng = '赵明明';
$yuwen = 98;
$result->bindParam(':xuesheng',$xuesheng);
$result->bindParam(':yuwen',$yuwen);
$result->execute();

$xuesheng = '王大大';
$yuwen = 120;
$result->bindParam(':xuesheng',$xuesheng);
$result->bindParam(':yuwen',$yuwen);
$result->execute();

这是使用类似:something作为占位符,如果使用?作为占位符,上面的代码应该这样写:

$query = "insert into tb_chengji set xuesheng=?,yuwen=?";
$result = $pdo->prepare($query);

$xuesheng = '赵明明';
$yuwen = 98;
$result->bindParam(1, $xuesheng);
$result->bindParam(2, $yuwen);
$result->execute();

$xuesheng = '王大大';
$yuwen = 120;
$result->bindParam(1, $xuesheng);
$result->bindParam(2, $yuwen);
$result->execute();

注意一下,如果这里使用的查询中要绑定的参数为like关键词查询语句后面的条件应该这样写:

$sth = $dbh->prepare('SELECT * FROM `users` WHERE `firstname` LIKE :keyword');
$keyword = "%".$keyword."%";
$sth->bindParam(':keyword', $keyword, PDO::PARAM_STR);

不能把%放到语句中区,而应该拼接到变量中。

参考文章:
1. 文档mysqli_stmt::bind_param
2. 文档PDOStatement::bindParam
3. PHP PDO prepare()、execute()和bindParam()方法详解

MySQL数据库操作中参数绑定的使用

原文链接:https://beltxman.com/2173.html,若无特殊说明本站内容为 行星带 原创,未经同意禁止转载。

MySQL数据库操作中参数绑定的使用”上有 4 条评论;

    1. 简单理解,mysqli是mysql的增强版,更安全,更节省资源,更详细的区别百度上有。

评论已关闭。

Scroll to top