Home > other >  PHP MYSQL, Update data with multiple select option, failed update with multiple option, success with
PHP MYSQL, Update data with multiple select option, failed update with multiple option, success with

Time:04-03

I have database

like this

`
$tgl_pinjam    = $_POST['tgl_pinjam'];
$barang        = $_POST['barang'];
$id_petugas    = $_POST['id_petugas'];
$peminjam      = $_POST['peminjam'];
$stat          = '1';
$kd_pinjam     = '1';
$barang        = implode(', ', $_POST['barang']);

{

$test1="UPDATE tb_barang SET stat='$stat' WHERE id_barang='$barang'";
$isi="INSERT INTO tb_pinjam_barang VALUES ('$no','$kd_pinjam','$tgl_pinjam','$barang','$id_petugas','$peminjam','$stat')";

$result=mysql_query($isi);
$update = mysql_query($test1);
        
    }
    if($result && $update)
    {`

if i choose 1 option, it will be success, stat change into '1' but if i choose more than 1 option, update not success, stat still '0'. what should i do.. thanks before..

.

CodePudding user response:

I guess you submit $_POST['barang'] as an array (therefore the implode). The resulting SQL-statement in $test1 will be

UPDATE tb_barang SET stat='1' WHERE id_barang='NX100-01, NX100-02'

which is a valid SQL-statment but it will not match any of the shown tupels.

To update multiple tuples the correct SQL-statement would be in this case

UPDATE tb_barang SET stat='1' WHERE id_barang IN ('NX100-01', 'NX100-02')

Another important thing: please sanitize your input to avoid SQL-injection-attacks.

Example: If I post the value ', ''); DELETE FROM tb_pinjam_barang; -- as $_POST['peminjam'] this would result in

INSERT INTO tb_pinjam_barang VALUES ('$no','$kd_pinjam','$tgl_pinjam','$barang','$id_petugas','`', ''); DELETE FROM tb_pinjam_barang; --','$stat')

and wipe your entire table. You can use already existing function mysql_escape_string(...) for this purpose. But as mysql_...-functions are deprecated in PHP 7 I guess it would be a good idea to switch to MySQLi or PDO_MySQL

  • Related