我目前正在用phpMyAdmin制作一个系统,遇到了一个常见的错误。我尝试键入一个自动递增系统,该系统按递增顺序为属性提供唯一的id。
<?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);
}
?>
但我收到错误信息
Warning: Trying to access array offset on value of type null in C:xampphtdocspertandingan_inovasipenilaian_insert.php
我猜这与属性"idpenilaian"是主键有关,并且不是null。
这是输出图像错误阵列偏移
有人能帮我做这个吗?谢谢
您需要检查$row
变量是否为空或是否有数据,还需要验证idpenilaian
是否存在于$row
中,如果不存在,则如果存在则处理该情况,然后运行下一个代码。
通过适当的验证,您的代码将如下所示:
$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.
}