duandaotuo5542 2011-06-29 10:46
浏览 62
已采纳

Php while Array中的循环错误,连接到Postgresql数据库

I have a static code to update some select boxes.

The original structure code:

$result = "
      ({ 
        'options': [
          {'value': '','description': '(pick an item)'}, 
          {'value': 'test','description': 'test'}, 
          {'value': 'test_2','description': 'test_2'}
        ]
      });
    ";

I'm trying to make this dynamic and connect to my table in Postgresql Database but my code don't works.

Here is My Code:

if($value=="asus"){

    require("includes/connection.php");

    $sth = $dbh->prepare( "SELECT * FROM mapa_ferias WHERE area = 'Asus' " );
    $sth->setFetchMode(PDO::FETCH_ASSOC);
    $sth->execute();

    $result = "
    ({
      'options': [";

            while($row = $sth->fetch()) { 
            $result += "{'value': '" + $row['nome'] + "','description': '" + $row['nome'] + "'},";
    }

    $result += 
            "]
        });
    ";
  }

I hope you can help me. Thanks in advance.

  • 写回答

1条回答 默认 最新

  • duanmie9741 2011-06-29 11:02
    关注

    Please do not try to build JSON data yourself.. PHP has a function for it: json_encode()

    if ($value=="asus"){
    
        require("includes/connection.php");
    
        $sth = $dbh->prepare( "SELECT * FROM mapa_ferias WHERE area = 'Asus' " );
        $sth->setFetchMode(PDO::FETCH_ASSOC);
        $sth->execute();
    
        $options = array();
        while($row = $sth->fetch()) { 
            $options[] = array(
                'value' => $row['nome'], 
                'description' => $row['nome']
            );
        }
        $sth->closeCursor();
    
        $result = '('.json_encode(array(
            'options' => $options
        )).')';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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库的算法识别小麦病虫害