How to Fix Trying to Access Array Offset on Value of Type Null Error

Message: Trying to access array offset on value of type null

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

How to fix Trying to access array offset on value of type null error

When you receive this error after fetching data from the database then it means that the database didn't found any matching rows. Most database fetching functions return either null or an empty array when there are no matching records or when the result set has been exhausted.

To solve the problem you need to check for the truthiness of the value or for the existence of the key that you want to access.

$monday_lectures = "SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday'";
$result_11to1 = mysqli_query($con, $monday_lectures);
$m11to1 = mysqli_fetch_array($result_11to1);
if ($m11to1 && $m11to1["lecture_day"] == !'') {
echo "<td>".$m11to1["lecture_name"]."</td>";
} else {
echo "<td> no class</td>";
}

If what you are after is a single value from the result array then you can specify a default in case the result is not present.

$monday_lectures = "SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday'";
$result_11to1 = mysqli_query($con, $monday_lectures);
$m11to1 = mysqli_fetch_array($result_11to1);
$lecture = $m11to1["lecture_day"] ?? null;

The same applies to PDO.

$monday_lectures = $pdo->prepare("SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday'");
$monday_lectures->execute();
$m11to1 = $monday_lectures->fetch();
$lecture = $m11to1["lecture_day"] ?? null;

Trying to access array offset on value of type null for array populated from MySQLi result set

mysqli_fetch_row will return null at some point (as it always does when it runs out of rows to retrieve, as per the documentation). But you're not checking that before trying to read its 0th index, hence the error.

Many people retrieve rows using this kind of style:

while ($row = mysqli_fetch_row($result)) { 
$resultArray[] = $row[0];
}

which will avoid this sort of problem. That's the way you'll often see it done in examples and documentation, too.

How to solve Trying to access array offset on value of type null in Codeigniter 4

Since you don't have a " firstOrFail " function, you should add a try catch around your code at

$dataMember = $M_admin->where("unm",
$member_username)->first();

You probably don't want to do the full check process if an user doesn't exist, you can also add a simple " if(!empty($dataMember))" but adding too much logic in your controller is probably not the best way, at least you should create a private function who do the full checking logic and return " true " or " err = "your_error_message"

I hope my answer can help you. :)

Received Error: PHP Warning: Trying to access array offset on value of type null , but correct value returned

This code will issue that warning if the query finds nothing because $row is empty and you're explicitly trying to extract a value from it regardless, and after that, you're checking if it was set:

$device = $row["txt_partnum"];
if (isset($device)) {
return $device;
} else {
return false;
}

You want to call isset() on the thing that might not be set, not the thing that you just explicitly created:

if (isset($row["txt_partnum"])) {
return $row["txt_partnum"];
} else {
return false;
}

Alternatively, just:

return $row["txt_partnum"] ?? false;

Trying to access array offset on value of type null when using mysqli_fetch_array() in PHP

The error is likely to be thrown when no rows are returned from the DB, since the code only handles the condition where number of rows returned is equal to 1.

When 0 rows are returned, $row is null.
And when you are try to access array offsets $row["user_name"] and $row["password"], it throws the error Trying to access array offset on value of type null since $row["user_name"] and $row["password"] don't exist.

To fix this, you must either handle the case where mysqli_num_rows($result) === 0, or you must check isset($row["user_name"]) and isset($row["password"]) beforehand.

Note 1: Depending on your table design, the code will fail if more than 1 row is returned. I suggest appending your SQL query with LIMIT 1 to avoid this.

Note 2: It also seems like you're saving the passwords in the DB as plaintext. This is bad practice. Please look up password hashing. This article is a good starting point.

Note 3: You may want to consider implementing a generic error message in your else block instead. Returning something like "Your username/password is incorrect"

Note 4: You are open to SQL injection attacks. Please take a look at the answers in the provided link and implement parameterized prepared statements.

Trying to access array offset on value of type null but database is not

as far as i know sqlserver driver for php is case sensitive and you selecting Status field from database as status in php

    if (!isset($_GET['id'])) {
die('no id provided');
}

if ($conCore2 === false) {
echo "Could not connect to Core2 Server.\n";
trigger_error(print_r(sqlsrv_errors(), true), E_USER_ERROR);
}

// pay attention to field's name case Status
$statusField = 'Status';
$locationField = 'FileLocation';
$docId = $_GET['id'];
//get details status and file location of document using docno


$sql = "SELECT [$statusField] ,[$locationField] FROM [dbo].[tbl_Documents] where DocNo = ?";
// as mentioned in comments, don't you ever, EVER pass unprepared
// params to sql query
$params = [$docId];
$resultset = sqlsrv_query($conCore2, $sql, $params);

if ($resultset === false) {
trigger_error(print_r(sqlsrv_errors(), true), E_USER_ERROR);
}

$row = sqlsrv_fetch_array($resultset, SQLSRV_FETCH_ASSOC);

if (!$row) {
die('no row of empty column list');
}

echo "inside";
echo $row[$locationField];
echo $row[$statusField];

Error: Trying to access array offset on value of type null in my PHP code

Problem

This line:

$screens = json_decode( str_replace( '`', '"', $code ), true );

will make the json invalid before you're trying to decode it.

Imagine you have a string like this:

$json = '{"foo": "lorem `bar` ipsum"}';

If you run your current str_replace() on it before trying to decode the string, it will become:

$json = '{"foo": "lorem "bar" ipsum"}';

See the issues with the quotes? If you try to decode that using json_decode(), it will fail and return null, which means that $screens['kc-css'] will throw the error message you're getting.

Solution

You need to escape the double quote with a backslash: \" if you want to use a literal double quote inside a double quoted string.

Change it to:

$screens = json_decode( str_replace( '`', '\"', $code ), true );

and it should work.

Here's a demo

Trying to access array offset on value of type null in

You need to check the existance of the keys you have in the array before comparing as it can not find it anyway.

use this instead

if (isset($ops["#pthelp"]['count']) && $ops["#pthelp"]['count']> 0)

also for this will be good to avoid any further problems

if (isset($voices["#pthelp"]['count']) &&  $voices["#pthelp"]['count'] > 0)


Related Topics



Leave a reply



Submit