Search code examples
phpmysqlzend-framework2

Php mysql insert array key values for the same table id


I have an array like below.

enter image description here

Where i need to insert all the values of ActionKey and ActionValue corresponding to each index for the same AdId

ie)
0th index - sms - 213123 and

1st index call - 12313

I am trying something like, but not working out.

$sDate = date("Y-m-d H:i:s");
$values = array();
$d_actionKey = $this->params()->fromPost('d_ActionKey');
$d_actionValue = $this->params()->fromPost('d_ActionValue');

$sql = "INSERT INTO `AdActions` (`CreatedDate`,`ActionKey`,`ActionValue`) VALUES";

foreach($values as $value) {
    $values[] = "($sDate, $d_actionKey, $d_actionValue)";
}

My table data should look like.

UPDATED CODE:

I need to get the AdId from another table's last inserted value. Then take that last inserted AdId and insert into AdActions

$adActionsInsert = $this->getAdLibraryTable()->saveAdd($dataArray);

$query='INSERT INTO `AdActions` (`AdId`,`CreatedDate`,`ActionKey`,`ActionValue`) VALUES ';
        for($i=0; $i < count($adActionsArray['ActionKey']); $i++)
        {
            if($i!=0)
                $query .= ', ';

            $query .= sprintf("(%d,'%s', '%s', '%d')",
            $adActionsInsert,
            $adActionsArray['CreatedDate'],
            $adActionsArray['ActionKey'][$i],
            $adActionsArray['ActionValue'][$i]);
        }

I am able to get the last insert value like below (from the model file)

$this->tableGateway->lastInsertValue;

enter image description here


Solution

  • If you want to insert the $data array into the table AdActions. You can build your query like this.

    $data = [
        'CreatedDate' => '2018-12-12 08:04:32',
        'ActionKey' => [
            0=>'sms',
            1=>'call'
        ],
        'ActionValue' => [
            0 => 213123,
            1 => 12313
        ]
    ];
    $query='INSERT INTO `AdActions` (`CreatedDate`,`ActionKey`,`ActionValue`) VALUES ';
    for($i=0; $i < count($data['ActionKey']); $i++)
    {
        if($i!=0)
            $query .= ', ';
        $query .= sprintf("('%s', '%s', '%d')",
            $data['CreatedDate'],
            $data['ActionKey'][$i],
            $data['ActionValue'][$i]);
    }
    echo $query;
    

    This should give you a query like this

    INSERT INTO `AdActions` (`CreatedDate`,`ActionKey`,`ActionValue`) VALUES ('2018-12-12 08:04:32', 'sms', '213123'), ('2018-12-12 08:04:32', 'call', '12313')