doushi1900 2017-10-13 05:47
浏览 40
已采纳

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

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:

Results from $array_items

The problem is when i print/echo out $array_items outside foreach loop, it only gets phone

enter image description here

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.

  • 写回答

1条回答 默认 最新

  • dongzhuo3059 2017-10-13 05:54
    关注

    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 = "";)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题