简体   繁体   English

转义字符串/在php脚本中插入

[英]Escape strings/ inserting in php script

I'm trying to finish a script that connects to two databases, each on a different server, and preforms an update. 我正在尝试完成一个脚本,该脚本连接到两个数据库,每个数据库位于不同的服务器上,并执行更新。 Basically, the tables being selected from and inserted to are identical: I did a dump/import the other day. 基本上,从中选择和插入的表是相同的:前几天我进行了转储/导入。 The script needs to keep my local table up to date from the remote once since there will be daily records inserted into the remote one and I need to keep it up to date locally. 该脚本需要使我的本地表在远程数据库中保持最新状态,因为将有每日记录插入到远程数据库中,因此我需要在本地将其保持最新状态。

The key here is that I'm determining the new rows on the remote server by looking at the Auto-incremented Primary key that the tables share, SESSIONID . 这里的关键是,我通过查看表共享的自动递增主键SESSIONID来确定远程服务器上的新行。 I'm trying to get my loop below to say, if the id exists in remote server and not local, then insert those records in local server. 我试图在下面让我的循环说,如果该ID存在于远程服务器中而不是本地,则将这些记录插入本地服务器中。

I run the below script in powershell by typing php 'filename', and I get both of my successful connection messages, and then I get this message: Incorrect datetime value: '' for column 'ALERTINGTIMESTAMP' at row 1 . 我通过键入php'filename'在powershell中运行以下脚本,并且得到了两条成功的连接消息,然后得到此消息: Incorrect datetime value: '' for column 'ALERTINGTIMESTAMP' at row 1 In this record it's trying to insert, the datetime value is NULL, which the table allows for, however I'm worried it's an issue with escaping characters or something. 在此记录中,它试图插入,表中允许datetime值为NULL,但是我担心这是转义字符或其他问题。

How can I modify this to escape properly, or get these records inserted. 我该如何修改它以使其正常转义或插入这些记录。

Note: Replication and large dump/import/table recreations are not an option for us in this situation. 注意:在这种情况下,复制和大型转储/导入/表重新创建不是我们的选择。 We have several similar scripts to this running and we want to keep the same process here. 我们有几个与此运行类似的脚本,我们希望在此处保持相同的过程。 I'm merely looking to resolve these errors or have someone give me a more efficient way of coding this script, perhaps using a max id or something along those lines. 我只是想解决这些错误,或者让某人给我一种更有效的编码此脚本的方法,也许使用max id或类似的方法。

Here's the script: 这是脚本:

      ini_set('memory_limit', '256M');

      // Create connection
      $conn = new mysqli($servername, $username, $password);
      $conn2 = new mysqli($servername2, $username2, $password2);

      // Check connection
      if ($conn->connect_error) {
          die("Connection failed: " . $conn->connect_error);
      }
      echo "Connected successfully";

      // Check connection2
      if ($conn2->connect_error) {
          die("Connection failed: " . $conn2->connect_error);
      }
      echo "Connected successfully";


    $latest_result = $conn2->query("SELECT MAX(`SESSIONID`) FROM `ambition`.`session`");
    $latest_row = $latest_result->fetch_row();
    $latest_session_id = $latest_row[0];

    //Select All rows from the source phone database
    $source_data = mysqli_query($conn, "SELECT * FROM `cdrdb`.`session` WHERE `SESSIONID` > $latest_session_id");

      // Loop on the results
      while($source_item = $source_data->fetch_assoc()) {

          // Check if row exists in destination phone database
          $row_exists = $conn2->query("SELECT SESSIONID FROM ambition.session WHERE SESSIONID = '".$source_item['SESSIONID']."' ") or die(mysqli_error($conn2));

              //if query returns false, rows don't exist with that new ID.
             if ($row_exists->num_rows == 0){

                    //Insert new rows into ambition.session
                    $conn2->query("INSERT INTO ambition.session (SESSIONID,SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO,DIALPLANNAME,TERMINATIONREASONCODE,ISCLEARINGLEGORIGINATING,CREATIONTIMESTAMP,ALERTINGTIMESTAMP,CONNECTTIMESTAMP,DISCONNECTTIMESTAMP,HOLDTIMESECS,LEGTYPE1,LEGTYPE2,INTERNALPARTYTYPE1,INTERNALPARTYTYPE2,SERVICETYPEID1,SERVICETYPEID2,EXTENSIONID1,EXTENSIONID2,LOCATION1,LOCATION2,TRUNKGROUPNAME1,TRUNKGROUPNAME2,SESSIONIDTRANSFEREDFROM,SESSIONIDTRANSFEREDTO,ISTRANSFERINITIATEDBYLEG1,SERVICEEXTENSION1,SERVICEEXTENSION2,SERVICENAME1,SERVICENAME2,MISSEDUSERID2,ISEMERGENCYCALL,NOTABLECALLID,RESPONSIBLEUSEREXTENSIONID,ORIGINALLYCALLEDPARTYNO,ACCOUNTCODE,ACCOUNTCLIENT,ORIGINATINGLEGID,SYSTEMRESTARTNO,PATTERN,HOLDCOUNT,AUXSESSIONTYPE,DEVICEID1,DEVICEID2,ISLEG1ORIGINATING,ISLEG2ORIGINATING,GLOBALCALLID,CADTEMPLATEID,CADTEMPLATEID2,ts,INITIATOR,ACCOUNTNAME,APPNAME,CALLID,CHRTYPE,CALLERNAME,serviceid1,serviceid2)
                    VALUES ('".$source['SESSIONID']."' ,
                            '".$source['SESSIONTYPE']."' ,
                            '".$source['CALLINGPARTYNO']."' ,
                            '".$source['FINALLYCALLEDPARTYNO']."',
                            '".$source['DIALPLANNAME']."',
                            '".$source['TERMINATIONREASONCODE']."',
                            '".$source['ISCLEARINGLEGORIGINATING']."',
                            '".$source['CREATIONTIMESTAMP']."',
                            '".$source['ALERTINGTIMESTAMP']."',
                            '".$source['CONNECTTIMESTAMP']."',
                            '".$source['DISCONNECTTIMESTAMP']."',
                            '".$source['HOLDTIMESECS']."',
                            '".$source['LEGTYPE1']."',
                            '".$source['LEGTYPE2']."',
                            '".$source['INTERNALPARTYTYPE1']."',
                            '".$source['INTERNALPARTYTYPE2']."',
                            '".$source['SERVICETYPEID1']."',
                            '".$source['SERVICETYPEID2']."',
                            '".$source['EXTENSIONID1']."',
                            '".$source['EXTENSIONID2']."',
                            '".$source['LOCATION1']."',
                            '".$source['LOCATION2']."',
                            '".$source['TRUNKGROUPNAME1']."',
                            '".$source['TRUNKGROUPNAME2']."',
                            '".$source['SESSIONIDTRANSFEREDFROM']."',
                            '".$source['SESSIONIDTRANSFEREDTO']."',
                            '".$source['ISTRANSFERINITIATEDBYLEG1']."',
                            '".$source['SERVICEEXTENSION1']."',
                            '".$source['SERVICEEXTENSION2']."',
                            '".$source['SERVICENAME1']."',
                            '".$source['SERVICENAME2']."',
                            '".$source['MISSEDUSERID2']."',
                            '".$source['ISEMERGENCYCALL']."',
                            '".$source['NOTABLECALLID']."',
                            '".$source['RESPONSIBLEUSEREXTENSIONID']."',
                            '".$source['ORIGINALLYCALLEDPARTYNO']."',
                            '".$source['ACCOUNTCODE']."',
                            '".$source['ACCOUNTCLIENT']."',
                            '".$source['ORIGINATINGLEGID']."',
                            '".$source['SYSTEMRESTARTNO']."',
                            '".$source['PATTERN']."',
                            '".$source['HOLDCOUNT']."',
                            '".$source['AUXSESSIONTYPE']."',
                            '".$source['DEVICEID1']."',
                            '".$source['DEVICEID2']."',
                            '".$source['ISLEG1ORIGINATING']."',
                            '".$source['ISLEG2ORIGINATING']."',
                            '".$source['GLOBALCALLID']."',
                            '".$source['CADTEMPLATEID']."',
                            '".$source['CADTEMPLATEID2']."',
                            '".$source['ts']."',
                            '".$source['INITIATOR']."',
                            '".$source['ACCOUNTNAME']."',
                            '".$source['APPNAME']."',
                            '".$source['CALLID']."',
                            '".$source['CHRTYPE']."',
                            '".$source['CALLERNAME']."',
                            '".$source['serviceid1']."',
                            '".$source['serviceid2']."')");
                  }
      }

Like Pankaj said, try something like this: 就像Pankaj所说的那样,尝试这样的事情:

//Insert new rows into ambition.session
$statement = $conn2->prepare('INSERT INTO ambition.session (SESSIONID,SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO,DIALPLANNAME,TERMINATIONREASONCODE,ISCLEARINGLEGORIGINATING,CREATIONTIMESTAMP,ALERTINGTIMESTAMP,CONNECTTIMESTAMP,DISCONNECTTIMESTAMP,HOLDTIMESECS,LEGTYPE1,LEGTYPE2,INTERNALPARTYTYPE1,INTERNALPARTYTYPE2,SERVICETYPEID1,SERVICETYPEID2,EXTENSIONID1,EXTENSIONID2,LOCATION1,LOCATION2,TRUNKGROUPNAME1,TRUNKGROUPNAME2,SESSIONIDTRANSFEREDFROM,SESSIONIDTRANSFEREDTO,ISTRANSFERINITIATEDBYLEG1,SERVICEEXTENSION1,SERVICEEXTENSION2,SERVICENAME1,SERVICENAME2,MISSEDUSERID2,ISEMERGENCYCALL,NOTABLECALLID,RESPONSIBLEUSEREXTENSIONID,ORIGINALLYCALLEDPARTYNO,ACCOUNTCODE,ACCOUNTCLIENT,ORIGINATINGLEGID,SYSTEMRESTARTNO,PATTERN,HOLDCOUNT,AUXSESSIONTYPE,DEVICEID1,DEVICEID2,ISLEG1ORIGINATING,ISLEG2ORIGINATING,GLOBALCALLID,CADTEMPLATEID,CADTEMPLATEID2,ts,INITIATOR,ACCOUNTNAME,APPNAME,CALLID,CHRTYPE,CALLERNAME,serviceid1,serviceid2)
VALUES (?, ?, ?, ...);');
$statement->bindParam(1, $source['SESSIONID']);
$statement->bindParam(2, $source['SESSIONTYPE']);
$statement->bindParam(3, $source['CALLINGPARTYNO']);
//...
$statement->execute();

You have to use prepare() function to use parameterized query. 您必须使用prepare()函数来使用参数化查询。 Here I have taken example of your query with few parameters you can add yourself with other variables. 在这里,我以带有少量参数的查询为例,您可以添加其他变量。

$stmt = $conn2->prepare("INSERT INTO ambition.session (SESSIONID,SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO) VALUES (:SESSIONID ,:SESSIONTYPE ,:CALLINGPARTYNO ,:FINALLYCALLEDPARTYNO)");

$stmt->bindParam(':SESSIONID', $source['SESSIONID']);
$stmt->bindParam(':SESSIONTYPE', $source['SESSIONTYPE']);
$stmt->bindParam(':CALLINGPARTYNO', $source['CALLINGPARTYNO']);
$stmt->bindParam(':FINALLYCALLEDPARTYNO', $source['FINALLYCALLEDPARTYNO']);
$stmt->execute();

You can checkout this link for more understanding. 您可以签出此链接以了解更多信息。 http://php.net/manual/en/mysqli.prepare.php http://php.net/manual/en/mysqli.prepare.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM