duannian7116 2014-08-27 16:49
浏览 43
已采纳

Jquery自动完成在一行中显示来自mysql的两行

I have a mysql table with multiple rows

ID, country, city, region

I have a search working with jquery-ui autocomplete, which currently autocompletes city searches like so:

if (isset($_GET['term'])){
    $return_arr = array();

    try {
        $conn = new PDO("mysql:host=".DB_SERVER.";port=8889;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $conn->prepare('SELECT city,country FROM location WHERE city LIKE :term LIMIT 10');
        $stmt->execute(array('term' => '%'.$_GET['term'].'%'));

        while($row = $stmt->fetch()) {
            $return_arr[] =  $row['city'];

        }

    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }



    echo json_encode($return_arr);
}

I would like to display the country next to the city, so Los Angeles would become Los Angeles, US

  • 写回答

1条回答 默认 最新

  • duanhe1976 2014-08-27 16:58
    关注

    In php you can append a string by using a '.' For example:

    $mystring = 'part one' . 'part two';
    
    echo $mystring; //-> will product: part onepart wo
    

    You can also let php interpret a string to delimiting with '"' (double quotes)

    $myvar = "boat";
    $mystring = "One day I'll buy a {$myvar}";
    
    echo $mystring; //-> will produce: One day I'll buy a boat
    

    The below should work ok. Good luck!

    if (isset($_GET['term'])){
        $return_arr = array();
    
        try {
            $conn = new PDO("mysql:host=".DB_SERVER.";port=8889;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
            $stmt = $conn->prepare('SELECT city,country FROM location WHERE city LIKE :term LIMIT 10');
            $stmt->execute(array('term' => '%'.$_GET['term'].'%'));
    
            while($row = $stmt->fetch()) {
                $return_arr[] =  $row['city'] . ', ' . $row['country'];
    
            }
    
        } catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }
    
    
    
        echo json_encode($return_arr);
    }
    

    Another alternative way to solve this would be to append the string in your SQL

    SELECT CONCAT(city, ', ', country) AS location FROM location WHERE city LIKE :term LIMIT 10
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害