找不到id栏。在php

时间:2018-06-22 05:04:31

标签: php json on-duplicate-key

我使用JSON文件记录通过PHP脚本插入到MySQL数据库。以下是JSON文件,其中包含表名,字段名和具有25个以上表的值。

[
  {
    "tableName": "cashdrawer_open_time",
    "rows": []
  },
  {
    "tableName": "counters",
    "rows": [
      {
        "id": "2",
        "name": "B",
        "description": "SAKTHY",
        "added_on": "2018-06-21T12:49:30",
        "last_updated": "2018-02-18T12:49:40",
        "department": "1"
      },
      {
        "id": "5",
        "name": "E",
        "description": "SAKTHY2",
        "added_on": "2018-06-21T12:50:21",
        "last_updated": "2018-06-21T14:52:18",
        "department": "1"
      }
    ]
  }
]

以下PHP脚本(谢谢@Sloan Thrasher)用于将JSON文件记录插入在线表格中。但是,当我执行此脚本时,在浏览器中得到了以下错误回显。

<?php
try
{
    $connect = mysqli_connect("localhost", "fmart", "password", "fmart_dbsync"); 
    $query = '';
    $table_data = '';
    $filename = "sample.json";

    $data = file_get_contents($filename);
    $array = json_decode($data, true); 

    foreach($array as $set) 
    {
        $tblName = $set['tableName'];
        if(sizeof($set['rows']) > 0) 
        {
            $query = '';
            $colList = array();
            $valList = array();
            //  Get list of column names
            foreach($set['rows'][0] as $colName => $dataval) 
            {
                $colList[] = "`".$colName."`";
            }
            $query .= "INSERT INTO `".$tblName."` \n";
            $query .= "(".implode(",",$colList).")\nVALUES\n";
            //  Go through the rows for this table.
            foreach($set['rows'] as $idx => $row) 
            {
                $colDataA = array();
                //  Get the data values for this row.
                foreach($row as $colName => $colData) 
                {
                    $colDataA[] = "'".$colData."'";
                }
                $valList[] = "(".implode(",",$colDataA).")";
            }
            //  Add values to the query.
            $query .= implode(",\n",$valList)."\n";
            //  If id column present, add ON DUPLICATE KEY UPDATE clause
            if(in_array("id", $colList)) 
            {
                $query .= "ON DUPLICATE KEY UPDATE\n\t SET ";
                $tmp = array();
                foreach($colList as $idx => $colName) 
                {
                    //$tmp[] = $colName." = new.".$colName." ";
                    $tmp[] = $colName." = VALUE(".$colName.") ";    //  Changed this line to get value from current insert row data

                }
                $query .= implode(",",$tmp)."\n";
            } 
            else 
            {
                echo "<p><b>`id`</b> column not found. <i>ON DUPLICATE KEY UPDATE</i> clause <b>NOT</b> added.</p>\n";
                echo "<p>Columns Found:<pre>".print_r($colList, true)."</pre></p>\n";
            }
            echo "<p>Insert query:<pre>$query</pre></p>";
            $r = mysqli_query($connect, $query);  
            echo "<h1>".mysqli_affected_rows($connect). " Rows appended in .$tblName.</h1>";
        } 
        else 
        {
            echo "<p>No rows to insert for .$tblName.</p>";
        }
    }
} 

catch(Exception $e)
{   
    echo $e->getMessage();  
}

?>

以下是执行PHP脚本时在浏览器上显示的错误回显:

No rows to insert for .bank_accounts.

No rows to insert for .bank_transactions.

No rows to insert for .cashdrawer_open_time.

`id` column not found. ON DUPLICATE KEY UPDATE clause NOT added.

Columns Found:

Array
(
    [0] => `id`
    [1] => `name`
    [2] => `description`
    [3] => `added_on`
    [4] => `last_updated`
    [5] => `department`
)
Insert query:

.INSERT INTO `counters` 
(`id`,`name`,`description`,`added_on`,`last_updated`,`department`)
VALUES
('2','B','SAKTHY','2018-06-21T12:49:30','2018-02-18T12:49:40','1'),
('5','E','SAKTHY2','2018-06-21T12:50:21','2018-06-21T14:52:18','1')
.

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /home/fmart/public_html/newSync/webScript.php on line 60
Rows appended in .counters.

No rows to insert for .customer_transactions.

No rows to insert for .customers.

No rows to insert for .department_stock_transfers.

and so on...

1 个答案:

答案 0 :(得分:1)

需要一些修改。您应该使用mysqli_affected_rows而不是mysqli_num_rows。由于mysqli_affected_rows返回受插入,更新,删除查询影响的行。试试修改后的代码:

echo "<p>Insert query:<pre>.$query.</pre></p>";
if (mysqli_query($connect, $query)) {
    echo "<h1>" . mysqli_affected_rows($connect) . " Rows appended in .$tblName.</h1>";
} else {
    echo "<h1>Query Failed</h1>";
}

还更新以下行:

$query .= "ON DUPLICATE KEY UPDATE\n\t id = id + 1 ";

注意:我仅更新了所需的部分代码,其余部分保持不变。