dongxiji0687 2012-03-17 17:44
浏览 47
已采纳

PDO对象的长度大于预期

I would like to create Javascript arrays with some data from a PDO object. Here is my code:

$req = $bdd->query('SELECT 
    id AS user_id, 
    fname AS user_fname, 
    lname AS user_lname
    FROM mand_users');

$autocomplete_users = '<script type="text/javascript"> var names_users = new Array(';
$users_ids = 'var users_ids = new Array(';

$i = -1;

while ($donnees = $req->fetch(PDO::FETCH_ASSOC)) {
    print_r($donnees);
    $i++;

    $user_full_name = $donnees['user_fname'].' '.$donnees['user_lname'];
    $user_id = $donnees['user_id'];

              if ( $i < count($donnees)-1) {

        $autocomplete_users .= $user_full_name.', ';
        $users_ids .= $user_id.', ';

           } else  {

        $autocomplete_users .= $user_full_name.');';
        $users_ids .= $user_id.');';

    }
}

echo $autocomplete_users . $users_ids .'</script>';

print_r returns

Array
(
    [user_id] => 1
    [user_fname] => Bob
    [user_lname] => Smith
)
Array
(
    [user_id] => 2
    [user_fname] => Alice
    [user_lname] => Smith
)

so the object's length would be 2. In this case, the JS code would look like this

<script type="text/javascript">
var names_users = new Array(Bob Smith, Alice Smith);
var users_ids = new Array(1, 2); 
</script>

but instead I get this

<script type="text/javascript">
var names_users = new Array(Bob Smith, Alice Smith, var users_ids = new Array(1, 2, </script>

which means that the code in the elseis not executed. So I checked the object's length with count() and it returned 3. How could you explain this ?

  • 写回答

2条回答 默认 最新

  • douwen3127 2012-03-17 18:09
    关注

    I suggest you do not write your code like that it is too much error prone. You could insert your data in 2 arrays, then you can use something like http://ca.php.net/implode to add comas..

    $user_ids = array();
    $user_names = array();
    
    while ($donnees = $req->fetch(PDO::FETCH_ASSOC)) {
        $name = $donnees['user_fname'].' '.$donnees['user_lname'];
        $id = $donnees['user_id'];
    
        $user_ids[] = $id;
        $user_names[] = $name;
    }
    
    <script>
    var names = new Array('<?php implode("', '", $user_names); ?>');
    var ids = new Array(<?php implode(", ", $user_ids); ?>);
    </script>
    
    (code not tested, just to give you a hint)
    

    But to be honest, you should not do that, you should try to check out JSON : http://ca.php.net/json_encode http://ca.php.net/json_decode

    It is the easiest way to pass objects tojavascript.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 复现论文:matlab仿真代码编写
  • ¥15 esp32驱动GC9A01循环播放视频
  • ¥15 惠普360g9的最新bios
  • ¥30 这个功能用什么软件发合适?
  • ¥60 微信小程序,取消订单,偶尔订单没有改变状态
  • ¥15 用pytorch实现PPO算法
  • ¥15 关于调制信号的星座图?
  • ¥30 前端传参时,后端接收不到参数
  • ¥15 这是有什么问题吗,我检查许可证了但是显示有呢
  • ¥15 机器学习预测遇到的目标函数问题