Reputation: 15
I have a form field and would like to check for each input field if it is already exist in database.
Below is my php code:
$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);
}
The results from echo $array_items
is as below:
The problem is when i print/echo out $array_items
outside foreach
loop, it only gets phone
how can i get all the individual strings as one and assigned it to a variable in php?
thanks in advance.
if there're link to old post, please provide me the link. i do not know the term use to search for this kind of problem.
Upvotes: 0
Views: 41
Reputation: 477
Please try this code
$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);
}
The problem with your code is assignment of $array_items variable in foreach loop. Each time loop execute it set the value to blank ($array_items = "";)
Upvotes: 1