php - 一种在 php 中将值连接到字符串的简单方法

标签 php

<分区>

我有这个和平的代码:

$result = mysql_query("SELECT * FROM T_utilisateur WHERE cin = '" . $_POST['cin'] . "', AND pwd = '" . $_POST['pwd'] . "'");

我的问题是:有什么方法可以简单地在 mysql_query() 函数中写入字符串,因为有时我有很多变量,我必须将它们与字符串连接起来。

例如,在 C# 中,我使用如下所示的 String.Format:String.Format("SELECT * FROM T_utilisateur WHERE cin = '{0}', AND pwd = '{1}'", cin , pwd); 这是一种简单的方法,因为如果我将 concat 与 一起使用,我有时会忘记 char '

最佳答案

使用 准备好的语句。它们是为此目的而设计的。此外,您应该注意,以您实际执行的方式构建 SQL 查询容易受到 SQL 注入(inject)的攻击。或者换句话说,这是易受攻击代码的最佳示例。如果黑客发布 SQL 语句怎么办?准备好的语句将防止这种情况发生,因为它将查询数据与查询语法分开。

在 PHP 中你可以使用 PDO用于准备好的语句(以及其他扩展)。这是一个简短的例子:

$pdo = new PDO('...');

$stmt = $pdo->prepare('SELECT FROM table WHERE id=:id AND title=:title ...');
$stmt->execute(array('id' => 1, 'title' => 'test'));

更新:

在评论中你说你必须使用 mysql_* 扩展。如果这样做,您应该知道,您必须转义每个值以防止 SQL 注入(inject)。像这样:

 // first(!!!) connect to mysql. this is important because
 // mysql_real_escape_string() will need information about
 // the current connection's encoding to work properly
 if(!mysql_connect(...) && mysql_select_db(...)) {
     die('mysql connection error');
 }

 // escape values
 $id    = mysql_real_escape_string($_POST['id']);
 $title = mysql_real_escape_string($_POST['title']);
 ...

 // now you could just use double quotes `"` to insert vars into the query string:
 mysql_query("SELECT * FROM `table` WHERE id = $id AND title = '$title'");

如果您需要此附加信息:

注意:有一个语法叫做 curly syntax使用可用于访问双引号 " 字符串中的数组的 {}。我没有在示例中使用它,因为它不推荐 将 post vars 放在查询中而不先转义它们。但是这里有一个语法示例:

$array = array('foo' => 'bar');
$string = "Hello {$array['foo']}";

关于php - 一种在 php 中将值连接到字符串的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16133304/

相关文章:

javascript - 在 Laravel 中包含 .php 文件

php - AJAX 使用链接而不是按钮加载内容?

javascript - 输入键以提交 Ajax 表单

php - GAE ftp_nlist() 不起作用

php - 如何防止 PHP 中的 SQL 注入(inject)?

php - 带有子类别的面包屑导航

php - 选择在 CodeIgniter 中显示 MySQL DB 值的位置

PHP 目录循环 - 样式

JavaScript:如何在 HTML5 localStorage 中保存 html 文本

php - mod_rewrite 与永久重定向