doushi9856 2018-06-02 09:32
浏览 184
已采纳

我不能用PHP脚本在MongoDB上插入json

<?php
    $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    try {

        $link = mysqli_connect('localhost', 'root', '')
        or die('No se pudo conectar: ' . mysqli_error());
    mysqli_select_db($link,'classicmodels5') or die('No se pudo seleccionar la base de datos');

           $query = "select c.customerNumber,c.customerName,c.city as customerCity, c.country as customerCountry,c.salesRepEmployeeNumber from customers as c";
           $result = mysqli_query($link,$query);
                   $isFirst=0;
                   $isFirst2=0;
                   $isFirst3=0;
                   $isFirst4=0;
                   $json="";
                    while ($fila = mysqli_fetch_array($result)) {
                         $bulk = new MongoDB\Driver\BulkWrite;

                             $isFirst2=0;
                            $isFirst3=0;
                            $isFirst4=0;
                            extract($fila);

                            $json = $json."{";

                            //$json = $json.",{";
                            $json = $json.'"customerNumber":'.$fila["customerNumber"].',';
                            $json = $json.'"customerName":"'.$fila["customerName"].'",';
                            $json = $json.'"city":"'.$fila["customerCity"].'",';
                            $json = $json.'"country":"'.$fila["customerCountry"].'"';

                            //INICIO:INSERTAR PAYMENTS
                            $query2 = "select  p.checkNumber,p.amount from payments as p where p.customerNumber=".$fila["customerNumber"];
                            $result2 = mysqli_query($link,$query2);
                            if(mysqli_num_rows($result2)>0){
                                $json=$json.',"payments":[';
                            }
                            while ($fila2 = mysqli_fetch_array($result2)) {
                                extract($fila2);
                                if($isFirst2==1){
                                   $json = $json.",{";
                                }else{
                                   $json = $json."{";
                                }
                                     $json = $json.'"checkNumber":"'.$fila2["checkNumber"].'",';
                                     $json = $json.'"amount":"'.$fila2["amount"].'"}';
                                $isFirst2=1;

                            }
                            if(mysqli_num_rows($result2)>0){
                                $json=$json.']';
                            }
                            //FIN:INSERTAR PAYMENTS
                            //INICIO: INSERTAR EMPLOYEE
                            $query3 = "SELECT e.employeeNumber,e.lastName,e.extension,e.officeCode FROM employees as e where e.employeeNumber=".$fila["salesRepEmployeeNumber"];
                            $result3 = mysqli_query($link,$query3);
                                if(mysqli_num_rows($result3)>0){
                                    $json=$json.',"employees":[';
                                }
                                while ($fila3 = mysqli_fetch_array($result3)) {
                                extract($fila3);
                                if($isFirst3==1){
                                   $json = $json.",{";
                                }else{
                                   $json = $json."{";
                                }
                                   $json = $json.'"employeeNumber":"'.$fila3["employeeNumber"].'",';
                                   $json = $json.'"lastName":"'.$fila3["lastName"].'",';
                                   $json = $json.'"extension":"'.$fila3["extension"].'"';
                                   //INICIO:INSERTAR OFFICE

                                    $query4 = "SELECT o.officeCode,o.city,o.country FROM offices as o where o.officeCode=".$fila3["officeCode"];
                                    $result4 = mysqli_query($link,$query4);    
                                     if(mysqli_num_rows($result4)>0){
                                         $json=$json.',"officeCode":';
                                     }
                                     while ($fila4 = mysqli_fetch_array($result4)) {
                                     extract($fila4);
                                      if($isFirst4==1){
                                        $json = $json.",{";
                                     }else{
                                        $json = $json."{";
                                     }
                                       $json = $json.'"officeCode":"'.$fila4["officeCode"].'",';
                                       $json = $json.'"city":"'.$fila4["city"].'",';
                                       $json = $json.'"country":"'.$fila4["country"].'"}';

                                      $isFirst4=1;
                                     }

                                    //FIN:INSERTAR OFFICE

                                 $isFirst3=1;

                                }
                                if(mysqli_num_rows($result3)>0){
                                $json=$json.'}]';
                            }
                            //FIN:INSERTAR EMPLOYEE

                            $json = $json.'}';
                            echo $json."</br>";


                            //Hacer el insert 
                            $bulk->insert(json_decode($json));
                            $resultFinal = $manager->executeBulkWrite('test.prueba3', $bulk);
                            $json="";

                            $isFirst=1;
                        }
                        $json = str_replace("'", " ", $json);
                        echo $json;
                //echo $json;
       /* $bulk->insert(json_decode($json));
        $resultFinal = $manager->executeBulkWrite('test.customers', $bulk);
        var_dump($resultFinal);*/
    }catch(Exception $e) {
        echo "EXCEPTION: ".$e->getMessage(), "
";
        exit;
    }

?>

When I do the inserted, for every time I finish the first loop, I get the following error, I do not understand if it is because the JSON is wrong or should be inserted in another way

    Warning: MongoDB\Driver\BulkWrite::insert() expects parameter 1 to be array, null given in C:\xampp2\htdocs\prac\index.php on line 111

EXCEPTION: Cannot do an empty bulk write

I need every time I finish the first loop insert the JSON document for in the next lap add another, I get that error but when validating my json in JSONLint, I get that is valid. is a migration from MySQL to MongoDB.

This is the JSON that gives error, which I think is correctly written, where do you think this error? Thank you

{"customerNumber":144,"customerName":"Volvo Model Replicas, Co","city":"Lule�","country":"Sweden","payments":[{"checkNumber":"IR846303","amount":"36005.71"},{"checkNumber":"LA685678","amount":"7674.94"}],"employees":[{"employeeNumber":"1504","lastName":"Jones","extension":"x102","officeCode":{"officeCode":"7","city":"London","country":"UK"}}]}
  • 写回答

1条回答 默认 最新

  • dongqie8661 2018-06-03 10:07
    关注

    I simplified your code to this:

    <?php
    $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    try {
    
        $json='{"customerNumber":144,"customerName":"Volvo Model Replicas, Co","city":"Lule�","country":"Sweden","payments":[{"checkNumber":"IR846303","amount":"36005.71"},{"checkNumber":"LA685678","amount":"7674.94"}],"employees":[{"employeeNumber":"1504","lastName":"Jones","extension":"x102","officeCode":{"officeCode":"7","city":"London","country":"UK"}}]}';
            $bulk = new MongoDB\Driver\BulkWrite;
    
    
            echo $json."</br>";
    
    
            //Hacer el insert
            $bulk->insert(json_decode($json));
            $resultFinal = $manager->executeBulkWrite('test.prueba3', $bulk);
            $json="";
    
            $isFirst=1;
    
    }catch(Exception $e) {
        echo "EXCEPTION: ".$e->getMessage(), "
    ";
        exit;
    }
    

    And is printed JSON and saved data do mongodb

    > db.prueba3.find().pretty()
    {
        "_id" : ObjectId("5b13bbda65b9bb1f3e6b9922"),
        "customerNumber" : 144,
        "customerName" : "Volvo Model Replicas, Co",
        "city" : "Lule�",
        "country" : "Sweden",
        "payments" : [
            {
                "checkNumber" : "IR846303",
                "amount" : "36005.71"
            },
            {
                "checkNumber" : "LA685678",
                "amount" : "7674.94"
            }
        ],
        "employees" : [
            {
                "employeeNumber" : "1504",
                "lastName" : "Jones",
                "extension" : "x102",
                "officeCode" : {
                    "officeCode" : "7",
                    "city" : "London",
                    "country" : "UK"
                }
            }
        ]
    }
    

    Please confirm that this example works in your case. If not you can compare $json that is defined in this example and your $json before comment //Hacer el insert.

    Any way if is it possible please isolate your problem. Including such huge amount of code is not so useful as smaller. To help other to response you can use exemplary data instead of pasting code with selects from database.

    Concatenating JSON from string is very bad practice. Imagine that one of your string contains character like this: "{". Did you escaped it?

    Potentially problem can be connected with encoding Lule�. You are using Windows, maybe your text of your code or SQL database has encoding different than UTF-8.

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

报告相同问题?

悬赏问题

  • ¥15 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败