Jump to content

how to insert insert array


lukep11a

Recommended Posts

I am currently going through the process of converting all mysql code to mysqli and having some trouble with inserting an array from a prepared statement. This is how it used to work:

 

$apointsAry = array();
$apointsAry[] = "($id, $aid, $at_points)";

$query = "INSERT INTO team_points (fixture_id, team_id, points)
VALUES ".implode(', ', $apointsAry);
$result = mysql_query($query) or die("Query: {$query}<br>Error: ".mysql_error());

 

And this is what I have got so far after converting it:

 

$stmt = $mysqli->prepare("INSERT INTO team_points (fixture_id, team_id, points)
VALUES (?, ?, ?)");
			
$stmt->bind_param("iii", $id, $aid, $at_points);
$stmt->execute();
$stmt->close();

 

 

Obviously the above code only enters one row. I have searched around but can't find how to incorporate an array with bind_param or is it not possible? Any help would be greatly appreciated.

Link to comment
https://forums.phpfreaks.com/topic/275176-how-to-insert-insert-array/
Share on other sites

You could run a foreach loop. (http://php.net/manual/en/mysqli-stmt.execute.php)

 

$query->bindParams("iii", $param1, $param2, $param3);
$query->execute();

foreach ($insertVals as $values) {
    $param1 = $values[0];
    $param2 = $values[1];
    $param3 = $values[2];
    $query->execute();
}

Fill in the missing pieces of your logic before an appropriate answer can be formulated. An example array would help.

Storing multiple values in one array element is not how arrays are meant to be implemented. Something like:

 

 

$arr = array();
$arr[] = array($id, $aid, $at_points);

 

would be a better solution.

Thanks to you both for your help, got it working with the code below so thanks for pointing me in the right direction:

 

$apointsAry = array();
$apointsAry[] = array($id, $aid, $at_points);

$stmt = $mysqli->prepare("INSERT INTO team_points (fixture_id, team_id, points)
VALUES (?, ?, ?)");
				
foreach ($apointsAry as $values) {
$stmt->bind_param("iii", $id, $aid, $at_points);
$id = $values[0];
$aid = $values[1];
$at_points = $values[2];
$stmt->execute();
}
$stmt->close();

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.