简体   繁体   中英

update multiple rows in table mysql

im wondering if someone could point me in the right direction as im trying to update multiple rows but for some reason everytime time i do the update, variable id_employee is set with the same value for all the rows.. that´s what i figured out when i var_dumped $_POST. The rest of fields are fine.. Here is a complete view of my code. http://pastie.org/5478920 , also this is what i get when i var_dump http://pastie.org/5478980

    $query = "update project_staff
    set
    id_employee=?
    where
    id_project=?
    and
    id_projectemployee=?
    ";

    $stmt = $this->dbh->prepare($query);

    for ($i = 0; $i < count($_POST['id_employee']); $i++){

    $employee = $_POST['id_employee'][$i];

    $stmt->bindValue(1, $employee, PDO::PARAM_INT);
    $stmt->bindValue(2, $_POST["id"], PDO::PARAM_INT);
    $stmt->bindValue(3, $_POST["idstaff"], PDO::PARAM_INT);

    $stmt->execute();

    }

    echo("Project" . " " . $_POST["nom"] . " ". "has been updated");

You are setting the bind param to an explicit data type PDO::PARAM_INT , but values FROM $_POST are always string.

You should change and validate your POST input to be INT first and change it to INT or use PDO::PARAM_STR

//UPDATE

Looking at your code you set the value of the where clause to the content of $_POST['id'] AND $_POST["idstaff"]. So in every run trough your foreach you are requesting the same value. So the $employee is update on every run, but the where clause is always the same. this would look like:

//example
//$_POST['id'] = 20;
//$_POST['idstaff'] = 40;
//$_POST['id_employee'][0] = 1;
//$_POST['id_employee'][1] = 2;
//$_POST['id_employee'][2] = 3;

//run 1
$employee = $_POST['id_employee'][0]; //1
update project_staff set id_employee=1 where id_project=20 and id_projectemployee=40

//run 1
$employee = $_POST['id_employee'][1]; //2
update project_staff set id_employee=2 where id_project=20 and id_projectemployee=40

//run 1
$employee = $_POST['id_employee'][2]; //3
update project_staff set id_employee=3 where id_project=20 and id_projectemployee=40

so you are overwriting previous changes on every run.

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