2017-10-13 29 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'循環中。 –

相關問題