不好:[php] foreach?

时间:2019-04-25 07:43:31

标签: php mysql json

无法将数据插入表

这是一个必须插入到我的数据库中的文件的示例。将文件以简单的形式上传到服务器。

{
    “FileName”: “XXXX",
    “Code”: “11112233",
    “Contacts”: [
        {
        “rowId” => '',
        “TicketId” => "xxxxxxxxxxxx",
        “otherId” => "YYYYYYYYYYYYYYYYYYYYYYY",
        “ClientId” => "wwwwwwwwwwwwwwwwwwwwwwwwwww",
        “Name” => "MARCELLO",
        “LName” => "MARCELLO",
        “Phone” => "4315415151434",
        “ADDRESS” => "hhhhhvofvofvvv",
        “Mail” => "dfwfwf@fwes.fd"
        },
        {
        “rowId” => '',
        “TicketId” => "xxxxxxxxxxxx",
        “otherId” => "YYYYYYYYYYYYYYYYYYYYYYY",
        “ClientId” => "wwwwwwwwwwwwwwwwwwwwwwwwwww",
        “Name” => "MARCELLO",
        “LName” => "MARCELLO",
        “Phone” => "4315415151434",
        “ADDRESS” => "hhhhhvofvofvvv",
        “Mail” => "dfwfwf@fwes.fd"
        }
    ]
}

在主页中,我包括用于连接数据库的脚本 我确定它可以正常工作,通常用于我网络工作的所有其他页面。

$host = "localhost";
$db_user = "xxxx";
$db_pw = "xxxxx";
$db_name = "xxxxx";
// connessione
try {
  // stringa di connessione al DBMS
  $connessione = new PDO("mysql:host=$host;dbname=$db_name", $db_user, $db_pw);
  // impostazione dell'attributo per il report degli errori
  $connessione->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

catch(PDOException $e)
{
  // notifica in caso di errore nel tentativo di connessione
  echo "Errore:" .$e->getMessage();
  die();
}   

这是我上传页面代码的一部分,对我没有帮助:

$file = file_get_contents($filejson);
if(!function_exists('json_decode')) die('Il server non ha tale funzione');
$result = json_decode($file, true);
                foreach ($result as $row){
                        $sql = "INSERT INTO ibl_Anag (TicketId,otherId,ClientId,Name,LName,MobPhone,Phone,address,mail)
                        VALUES ('".$row["TicketId"]."'
                                ,'".$row["otherId"]."'
                                ,'".$row["ClientId"]."'
                                ,'".$row["Name"]."'
                                ,'".$row["LName"]."'
                                ,'".$row["Phone"]."'
                                ,'".$row["MainPhone"]."'
                                ,'".$row["address"]."'
                                ,'".$row["mail"]."' )";
                        $stmt=$connessione->prepare($sql);
                        $stmt->execute();
                        if(!$stmt){Echo "la insert non ha funzionato";}


    }

我没有从代码中得到错误,但是数据没有插入到mysql表中。可能我在脚本的逻辑上做错了,但不知道在哪里。谁能帮帮我吗。谢谢。

2 个答案:

答案 0 :(得分:2)

您需要考虑以下因素:

  • 使用参数化的准备好的语句。这将帮助您prevent possible SQL injection和错误的用户输入错误。在您的语句中分配占位符(?,准备一次该语句,将值绑定到参数并多次执行该语句。
  • 您的JSON无效(如问题中所述)。使用有效的JSON并从此"Contacts"中读取JSON数组以执行语句。另外,您的"MainPhone"中没有JSON,而"address""ADDRESS"

您可以尝试以下代码:

<?php
# Connection
$host    = "localhost";
$db_user = "xxxx";
$db_pw   = "xxxxx";
$db_name = "xxxxx";
try {
    $connessione = new PDO("mysql:host=$host;dbname=$db_name", $db_user, $db_pw);
    $connessione->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo "Errore:" .$e->getMessage();
    die();
}  

# Data
$file = file_get_contents($filejson);
if (!function_exists('json_decode')) {
    die('Il server non ha tale funzione');
}   
$result = json_decode($file, true);

# Prepare and execute statement
try {
    $sql = 
        "INSERT INTO ibl_Anag (TicketId,otherId,ClientId,Name,LName,MobPhone,Phone,address,mail)
        VALUES (?,?,?,?,?,?,?,?,?)";
    $stmt = $connessione->prepare($sql);
    foreach ($result["Contacts"] as $row) {
        $ticketId = $row["TicketId"];
        $otherId  = $row["otherId"];
        $clientId = $row["ClientId"];
        $name     = $row["Name"];
        $lname    = $row["LName"];
        $mobPhone = $row["Phone"];
        $phone    = $row["Phone"];
        $address  = $row["ADDRESS"];
        $mail     = $row["mail"];
        $stmt->BindParam(1, $ticketId);
        $stmt->BindParam(2, $otherId); 
        $stmt->BindParam(3, $clientId);
        $stmt->BindParam(4, $name);    
        $stmt->BindParam(5, $lname);   
        $stmt->BindParam(6, $mobPhone);
        $stmt->BindParam(7, $phone);   
        $stmt->BindParam(8, $address);
        $stmt->BindParam(9, $mail);    
        if (!$stmt->execute()) {
            echo "la insert non ha funzionato";
        }
    }                       
} catch(PDOException $e) {
    echo "Errore:" .$e->getMessage();
    die();
}  
?>

示例的有效JSON:

{
    "FileName": "XXXX",
    "Code": "11112233",
    "Contacts": [
        {
        "rowId": "",
        "TicketId": "xxxxxxxxxxxx",
        "otherId": "YYYYYYYYYYYYYYYYYYYYYYY",
        "ClientId": "wwwwwwwwwwwwwwwwwwwwwwwwwww",
        "Name": "MARCELLO",
        "LName": "MARCELLO",
        "Phone": "4315415151434",
        "ADDRESS": "hhhhhvofvofvvv",
        "Mail": "dfwfwf@fwes.fd"
        },
        {
        "rowId": "",
        "TicketId": "xxxxxxxxxxxx",
        "otherId": "YYYYYYYYYYYYYYYYYYYYYYY",
        "ClientId": "wwwwwwwwwwwwwwwwwwwwwwwwwww",
        "Name": "MARCELLO",
        "LName": "MARCELLO",
        "Phone": "4315415151434",
        "ADDRESS": "hhhhhvofvofvvv",
        "Mail": "dfwfwf@fwes.fd"
        }
    ]
}

答案 1 :(得分:2)

要正确使用准备好的语句,需要在执行语句之前在绑定变量的SQL语句中分配占位符。这样做的好处是,您只需在循环外创建一次prepared statement,然后只需更改命名变量的赋值即可在循环中执行多次。以下代码未经测试,但应将您引向最终目标。

下面的代码正在使用mySQLi-如果使用PDO,则可以使用类似的方法,除了在将变量分配给bindParam等之前,变量应该存在,即使是空变量也是如此

$sql='insert into ibl_anag
    ( `ticketid`,`otherid`,`clientid`,`name`,`lname`,`mobphone`,`phone`,`address`,`mail` )
        values
    (?,?,?,?,?,?,?,?,?)';

$stmt=$connessione->prepare( $sql );


if( $stmt ){
    /*
        assumed that fields named as ID are integers, 
        other firlds are strings
    */
    $stmt->bind_params( 'iiissssss', $tid,$oid,$cid,$name,$lname,$mob,$phone,$addr,$email );


    $json = json_decode( file_get_contents( $filejson ) );
    foreach( $json as $obj ){
        $tid=$obj->TicketId;
        $oid=$obj->otherId;
        $cid=$obj->ClientId;
        $name=$obj->Name;
        $lname=$obj->LName;
        $mob=$obj->Phone;
        $phone=$obj->MainPhone;
        $addr=$obj->address;
        $email=$obj->mail;

        $stmt->execute();
    }
    $stmt->close();
}

对于PDO,您可以尝试以下操作:

$sql='insert into ibl_anag
    ( `ticketid`,`otherid`,`clientid`,`name`,`lname`,`mobphone`,`phone`,`address`,`mail` )
        values
    (:tid,:oid,:cid,:name,:lname,:mob,:phone,:addr,:email)';

$stmt=$connessione->prepare( $sql );

if( $stmt ){

    $json = json_decode( file_get_contents( $filejson ) );
    foreach( $json as $obj ){
        $stmt->execute(array(
            ':tid'  =>  $obj->TicketId,
            ':oid'  =>  $obj->otherId,
            ':cid'  =>  $obj->ClientId,
            ':name' =>  $obj->Name,
            ':lname'=>  $obj->LName,
            ':mob'  =>  $obj->Phone,
            ':phone'=>  $obj->MainPhone,
            ':addr' =>  $obj->address,
            ':email'=>  $obj->mail
        ));
    }
}