1

I'm currently making a system with with phpMyAdmin and I'm coming across a common error. I tried to type in an auto increment system which provides a unique id to an attribute in increasing order.

<?php $query = "select * from penilaian order by idpenilaian desc limit 1";
$result = mysqli_query($sambungan, $query);
$row = mysqli_fetch_array($result);
$lastid = $row['idpenilaian'];
if($lastid == ' '){
$idpenilaian = "N10";
}
else{
$idpenilaian = substr($lastid,1);
$idpenilaian = intval($idpenilaian);
$idpenilaian = "N" . ($idpenilaian + 1);
}
?>

But I'm getting the error message

Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\pertandingan_inovasi\penilaian_insert.php

I'm guessing it's something related to the attribute 'idpenilaian' being a primary key and is not null.

Here's the output image error_array-offset

Can someone please help me with this? Thanks!

  • Does the `penilaian` table have a `idpenilaian` column? Does the table contain any records? Is the query syntactically correct? – kmoser Sep 17 '22 at 05:32

1 Answers1

-1

You need to check if your $row variable is empty or has data and also validate if idpenilaian exists in a $row or not, if not then handle the case if exists then run your next code.

With proper validation your code will be like this:

$query  = 'select * from penilaian order by idpenilaian desc limit 1';
$result = mysqli_query( $sambungan, $query );
$row    = mysqli_fetch_array( $result );

// !empty($row) - Check if row is not empty.
// isset($row['idpenilaian']) - check if idpenilaian exists in $row
// !empty($row['idpenilaian']) - check if $row['idpenilaian'] is not empty.
if ( ! empty( $row ) && isset( $row['idpenilaian'] ) && ! empty( $row['idpenilaian'] ) ) {
    $lastid = $row['idpenilaian'];
    if ( $lastid == ' ' ) {
        $idpenilaian = 'N10';
    } else {
        $idpenilaian = substr( $lastid, 1 );
        $idpenilaian = intval( $idpenilaian );
        $idpenilaian = 'N' . ( $idpenilaian + 1 );
    }
} else {
    // Handle your case here.
}
Vijay Hardaha
  • 2,411
  • 1
  • 7
  • 16