将字符串连接成一个单独的字符串作为php中的变量

时间:2017-10-13 05:47:25

标签: php mysql

我有一个表单字段,并希望检查每个输入字段是否已存在于数据库中。

以下是我的PHP代码:

$sql_query = "SELECT * FROM test_table";
if($result_query = $connect->query($sql_query))
{
    $items = array("firstName", "lastName", "country", "phone");

    //$names variable contains stored values which i've declared at the beginning
    $names = array($firstName, $lastName, $country, $phone);

    foreach(array_combine($items, $names) as $item => $name)
    {
        $array_items = "";
        $check_query = "SELECT $item FROM test_table WHERE $item = '".$name."'";
        $result_check_query = $connect->query($check_query);
        if($row_query = $result_check_query->num_rows)
        {
         $array_items .= $item . ", ";
        }
        echo $array_items . "gettype()=> " . gettype($array_items);
        echo "<br>";
    }
    print_r ( "<br>" . $array_items); 
}

echo $array_items的结果如下:

Results from $array_items

问题是当我在$array_items循环外打印/回显foreach时,它只会phone

enter image description here

如何将所有单个字符串作为一个并将其分配给php中的变量?

提前感谢。

如果有重新链接到旧帖子,请提供链接。 我不知道使用术语来搜索这类问题。

1 个答案:

答案 0 :(得分:1)

请尝试此代码

$sql_query = "SELECT * FROM test_table";
if($result_query = $connect->query($sql_query))
{
    $items = array("firstName", "lastName", "country", "phone");

    //$names variable contains stored values which i've declared at the beginning
    $names = array($firstName, $lastName, $country, $phone);
    $array_items = "";
    foreach(array_combine($items, $names) as $item => $name)
    {

        $check_query = "SELECT $item FROM test_table WHERE $item = '".$name."'";
        $result_check_query = $connect->query($check_query);
        if($row_query = $result_check_query->num_rows)
        {
         $array_items .= $item . ", ";
        }
        echo $array_items . "gettype()=> " . gettype($array_items);
        echo "<br>";
    }
    print_r ( "<br>" . $array_items); 
}

您的代码的问题是在foreach循环中分配$ array_items变量。每次执行循环时都会将值设置为空白($ array_items =&#34;&#34 ;;)