简体   繁体   中英

foreach loop multiple array value update using pdo

<?php
$roll  = $_POST['roll'];
$score = $_POST['a'];
$test  = $_SESSION['test'];
$class = $_SESSION['class'];
print_r($roll);
print_r($score);
global $pdo;
require('connect.php');
$stmt=$pdo->prepare("update atten set $test=? where roll=?");
foreach( $roll as $rollno)
{
    $stmt->bindparam(2,$rollno);
    foreach( $score as $key)
    {
        $stmt->bindparam(1,$score);
        $stmt->execute();
    }
}
if($stmt==false)
{
    die("error".print_r($stmt->errorinfo()));
}
?>

Here $roll is a array value and $score is also array value. here last value update for all roll no as example $roll=1,2,3,4 and $score(10,20,30) I don't know but here 30 value update for all roll no. please help me.. thank you..

At the moment you are saving every single score against all your rolls, so the last score will always be set to your roll.

The mistake is that you are using two foreach loops, but you only need one, you just need to match the rolls and scores to one another.

Iff you are absolutely certain the arrays are the same length and are indexed the same way (have the same keys - you can use the array_values PHP function to make sure) you can use a for loop instead

for($i = 0; $i < count($roll); $i++){
    $stmt->bindparam(1, $roll[$i]);
    $stmt->bindparam(2, $score[$i]);
    $stmt->execute();
}

The PHP function array_combine might be useful here too as you can just do something like:

array_combine($roll, $score);

And then use a foreach loop as usual.

Edit: As requested, an array_combine example:

<?php
$roll  = $_POST['roll'];
$score = $_POST['a'];
$test  = $_SESSION['test'];
$class = $_SESSION['class'];
print_r($roll);
print_r($score);
global $pdo;
require('connect.php');
$stmt=$pdo->prepare("update atten set $test=? where roll=?");

if(count($roll) !== count($score))
    die('Arrays are not the same length!');

$rollsToScores = array_combine($roll, $score);

foreach($rollsToScores as $roll => $score){
    $result = $stmt->execute(array($score, $roll));
    if($result === false){
        die("error".print_r($stmt->errorinfo()));
        break;
    }
}

?>

You are passing $array in inner loop bind param $stmt->bindparam(1,$score); .

I think

$stmt->bindparam(1,$score);

Should be :-

$stmt->bindparam(1,$key);

Modified Block of Code :-

foreach( $roll as $rollno)
{
    $stmt->bindparam(2,$rollno);
    foreach( $score as $key)
    {
    $stmt->bindparam(1,$key);
    $stmt->execute();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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