本文介绍了MySQL的凡阵列串/用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

code:

$friendsArray = array("zac1987", "peter", "micellelimmeizheng1152013142");
$friendsArray2 = join(', ',$friendsArray);
$query120 = "SELECT picturemedium FROM users WHERE username IN ('$friendsArray2')";
echo $query120;

这是输出:

SELECT picturemedium FROM users WHERE username IN ('zac1987, peter, micellelimmeizheng1152013142')

它失败,因为用户名没有被像zac1987','彼得',单引号包裹老鼠......。如何使用单引号包装每个用户名?

It fail because usernames are not wrapped by single quote like 'zac1987', 'peter', 'mice...'. How to wrap each username with single quote?

推荐答案

让我们遍历每个名​​字一个接一个,每个转义

Let's loop through each name one by one, escaping each.

我要推荐你使用MySQL的实际脱出功能,而不是仅仅回绕报价,以确保数据实际上进入查询正确。 (否则,如果我进入像的名称是我!,单引号会搞乱了查询)。我要在这里假设你使用 PDO (你应该!),但是,如果没有,请更换为 PDO ::报价与 mysql_real_escape_string

I'm going to recommend that you use an actual MySQL escaping function rather than just wrapping quotes around, to ensure that the data actually goes into the query correctly. (Otherwise, if I entered a name like It's me!, the single quote would mess up the query.) I'm going to assume here that you're using PDO (which you should!), but, if not, replace references to PDO::quote with mysql_real_escape_string.

foreach($friendsArray as $key => $friend) {
  $friendsArray[$key] = PDO::quote($friend);
}

$friendsArray2 = join(', ', $friendsArray);

这篇关于MySQL的凡阵列串/用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 15:54