2017-10-13 124 views
0

我有一个表单域,并希望检查每个输入域是否已经存在于数据库中。将字符串连接成一个单个字符串作为变量在php中

下面是我的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_itemsforeach循环,只有它获得phone

enter image description here

我怎样才能得到所有的单个字符串作为一个,并将其分配给一个变量在PHP?

在此先感谢。

如果有与旧帖子的链接,请为我提供链接。 我不知道术语用来搜索这类问题。

+0

你是否希望数组在末尾作为最终输出(在单独索引中包含组串输出)? –

+0

这也会有帮助。是的,请给我看看@AlivetoDie –

+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); 
} 

与您的代码的问题是$分配array_items在foreach循环变量。每次循环执行它将值设置为空($ array_items =“”;)

+0

哦,我的..非常感谢你。我是多么愚蠢的把初始变量放在'foreach'循环中。 –

相关问题