Home > Software engineering >  Warning: Illegal string offset when try to insert data
Warning: Illegal string offset when try to insert data

Time:08-01

I've an error when i'am trying to insert data in PHP, it says

Warning: Illegal string offset 'last_id' in C:\xampp\htdocs\learn\tambah_proses.php on line 13

my add data process looked like this,

<?php
include "koneksi.php";

if(isset($_POST['tambah']))
{  
  $nama             = $_POST['nama'];
  $namakegiatan     = $_POST['namakegiatan'];

  $query            = "INSERT INTO tbl_user (nama) VALUES ('$nama')";

  
  $sqlid            = "SELECT MAX(id) as last_id from tbl_user limit 1";
  $lastId           = $sqlid['last_id'];

  $query           .= "INSERT INTO tbl_kegiatan (namakegiatan) VALUES ('$lastId','{$_POST['namakegiatan']}');";

  var_dump($query);
  
  mysqli_multi_query($koneksi, $query);
    do 
        {
    /* store the result set in PHP */
        if ($result = mysqli_store_result($koneksi)) 
    {
            while ($row = mysqli_fetch_row($result)) 
        {
            printf("%s\n", $row[0]);
        }
    }
    /* print divider */
        if (mysqli_more_results($koneksi)) 
    {
        printf("-----------------\n");
    }
        }   while (mysqli_next_result($koneksi));
}

?>

i just learning to add data and insert to 2 different tables. first table name is tbl_user which have id (int), nama(varchar) second table name is tbl_kegiatan which have *id (int), iduser(int) that have foreign key that connected to 'id' in tbl_user, i so when i want to add data in form, the iduser in tbl_kegiatan will auto fill as the same as id in tbl_user. Form

CodePudding user response:

You're never executing the $sqlid query.

$sqlid  = "SELECT MAX(id) as last_id from tbl_user";
$result = mysqli_query($koneksi, $sqlid);
$row = mysqli_fetch_assoc($result);
$lastId = $row['last_id'];

If you're trying to get the auto-increment ID that was just assign, you don't need this query. You can use mysqli_insert_id($koneksi).

You can't do both INSERT queries in a single mysqli_multi_query() call, since you need to get the ID that was created when inserting into tbl_user before you can create the query that inserts into tbl_kegiatan.

You can also use the MySQL function LAST_INSERT_ID() in the next query instead of a PHP variable.

Also, please read How can I prevent SQL injection in PHP? to learn how to use prepared statements instead of substituting variables directly into queries. You should never substitute a $_POST variable into the query.

  • Related