简体   繁体   中英

how to insert and update sql database in different table in the same one button call

I tried to insert the data and also update the data in 2 different table. so I tried this code

    $query = "INSERT INTO mitra (id_user, puas_1, puas_2)
  values (?,?,?);
  UPDATE user
  SET fill = 1
  WHERE id = '".$id_session."';";
  $stmt = $connection->prepare($query);
  $stmt->bind_param("idd", $id_session, $puas1, $puas2);
  $stmt->execute();
  if ($stmt->affected_rows) {
    echo "Uploaded " . $stmt->affected_rows . " rows";
    // header("Location: umum.php");
  } else {
    echo "No rows matched the criteria.";

  }
  $stmt->close();

but it says that Uncaught mysqli_sql_exception: You have an error in your SQL syntax; near update etc. is there anything to make it work please?

Were you perhaps intending to use mysqli_multi_query ? That does allow for multiple queries that are separated using a semi-colon.. but that cannot be used with the prepared statement and would potentially open the code to sql injection. To use two prepared statements you could do like this:

$rows = false;
$sql='insert into `mitra` (`id_user`, `puas_1`, `puas_2`) values ( ?, ?, ? )';
$stmt=$connection->prepare( $sql );
if( $stmt ){

    $stmt->bind_param('idd', $id_session, $puas1, $puas2 );
    $res=$stmt->execute();
    $stmt->close();

    if( $res ){

        $sql='update `users` set `fill`=1 where `id`=?';
        $stmt=$connection->prepare( $sql );

        if( $stmt ){
            $stmt->bind_param('i',$id_session );
            $res=$stmt->execute();
            $rows = $stmt->affected_rows;
            $stmt->close();
        }
    }
    if( $res && $rows )exit( header('Location: umum.php') );
}

You can create a procedure and call it in php.

Procedure

DELIMITER $$

DROP PROCEDURE IF EXISTS `proc_insert_and_update` $$
CREATE PROCEDURE `proc_insert_and_update`(
    IN x_user_id int(11),
    IN x_puas_1 VARCHAR(20),
    IN x_puas_2 varchar(20)
    )
BEGIN

    #inserting data
    insert into mitra (id_user, puas_1, puas_2) 
    values ( x_user_id, x_puas_1, x_puas_2 );

    #update data
    update users set fill=1 where id=x_user_id;


END$$
DELIMITER ;

PHP

$stmt = $connection->prepare('CALL proc_insert_and_update(?, ?, ?)');
$stmt->bind_param('iss', $id_session, $puas1, $puas2);

clarify parameter types (i->integer, s->varchar).

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