在PHP中拆分字符串

时间:2014-02-12 15:36:06

标签: php mysql string

我需要将一个字符串分成多个部分。该字符串是一组唯一的用户名,但我检索三个名称以及之间的空格。我需要将一些'放在一端到另一端的开头之间,以便我可以将它们用于MySQL查询目的。

我已经使用了数组,但这次是不同的,因为这个字段填充了数据库中的数据。

如果添加/删除用户,它将使用该数组,但如果没有,它将使用我想要格式化的字符串。

我现在有这个代码:

$Pessoas2=  implode(" ", $_POST['Pessoas']);
 $Pessoas2 = str_replace(';', ' ' , $Pessoas2);

(...)

$to = mysqli_query($con,"SELECT Email FROM utilizadores WHERE Nome IN ( $Pessoas2)");

while ($row = mysqli_fetch_assoc($to)){ 
    echo $row['Email'];
    echo ";";

 foreach ($row as $destino);

 echo $destino;

4 个答案:

答案 0 :(得分:1)

使用以下代码:

$Pessoas2 =  implode("','", $_POST['Pessoas']);
$Pessoas2 =  "'".$Pessoas2."'";

而不是

$Pessoas2=  implode(" ", $_POST['Pessoas']);
$Pessoas2 = str_replace(';', ' ' , $Pessoas2);

答案 1 :(得分:0)

从您的问题中不确定$_POST['Pessoas']是否是一个字符串,其中用户名由空格分隔,或者是否为数组。

如果是由空格分隔的字符串,请尝试:

$Pessoas2 = "'" . preg_replace('/ /', "','", $_POST['Pessoas'])) . "'";

如果是数组,请尝试:

$Pessoas2 = "'" . implode("','", $_POST['Pessoas'])) . "'";

然后在查询中使用$Pessoas2,就像编写它一样。

答案 2 :(得分:0)

在代码中要解决一些问题。我会回答你的问题,但也指出了一些问题。

//always escape values before db insertion - see real_escape_string here
$Pessoas2= mysqli_real_escape_string(implode("", $_POST['Pessoas']));
//using substr here to get rid of the trailing ','
//this is assuming the last name in the array has a trailing semicolon, don't use it otherwise.
$Pessoas2 = substr(str_replace(';', "','", $Pessoas2), 0, -3);

$to = mysqli_query($con,"SELECT Email 
                         FROM utilizadores 
                        WHERE Nome IN ('". $Pessoas2 ."')");

while ($row = mysqli_fetch_assoc($to)){ 
    echo $row['Email'];
    echo ";";
   //the semicolon does not belong after the foreach here.
   foreach ($row as $destino)
        echo $destino;
}

那应该做你想要的,并帮助防止SQL注入。

答案 3 :(得分:-1)

有机会使用功能方法!哈哈

$Pessoas2 = array_map( function($val) {
    return "'{$val}'";
}, explode(' ', $_POST['Pessoas']));

$sql = "SELECT Email FROM utilizadores WHERE Nome IN (".implode(',', $Pessoas2).")";
相关问题