0

I am trying to get a query to run where it returns the SQL row's id of a user using a collar number through PHP.

For some reason, it is not working and providing an error: trying to access array offset on value of type null. Full Error Message - https://gyazo.com/38367bee5066d16f419a43aab93cbc89

I am not exactly sure how to fix this, I've tried a lot of things. I want the function to return the id so I can then use it where ever needed. I am using PHP's include functions.

UpdatePassword.php

session_start();

include("functions.php");

$id = findUserID(array_key_exists("collar", $_POST));
echo($id);

Functions.php

function findUserID($collar){
    $id = "";

    include("../connection.php");

    $query = "SELECT `id` FROM `users` WHERE collar = '".mysqli_real_escape_string($link, $collar)."'";

    if ($result = mysqli_query($link, $query)){
        //echo "Query was Successful";
    
        $row = mysqli_fetch_array($result);
        return($row['id']);
    }
}
Welshy
  • 57
  • 8
  • 2
    [`array_key_exists()`](https://www.php.net/manual/en/function.array-key-exists.php) returns true or false. You're passing true or false to your function but your function is expecting a string. – bloodyKnuckles Sep 14 '22 at 19:49
  • How would I reference this normal? Just using _POST['collar']? – Welshy Sep 14 '22 at 20:06
  • Good to have validation but when passing to the function use `findUserID($_POST['collar']);` – bloodyKnuckles Sep 14 '22 at 20:07
  • You should stop using `mysqli_real_escape_string()` as it's [not as secure as you might think](https://stackoverflow.com/questions/32391315/is-mysqli-real-escape-string-enough-to-avoid-sql-injection-or-other-sql-attack). Use prepared statements using placeholders instead. You can read [how to prevent SQL injection in PHP](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) to get a quick example of how to use them. – M. Eriksson Sep 14 '22 at 20:42
  • Please read [Why not upload images of code/errors when asking a question](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question). And if you really need to upload an image for something, you should use the `image`-function in the toolbar when writing the question instead of linking to a different service. – M. Eriksson Sep 14 '22 at 20:45

1 Answers1

0

Using PHP ternary operator to show one example validating your $_POST input:

$id = ( array_key_exists("collar", $_POST) )
  ? findUserID($_POST['collar'])
  : 0;

That is shorthand for:

if ( true === array_key_exists("collar", $_POST) ) {
  $id = findUserID($_POST['collar']);
}
else {
  $id = 0;
}

Other validation checks can be included in each method:

$id = ( 
  array_key_exists("collar", $_POST) // key exists
  && "" !== $_POST['collar']         // not empty string
)
  ? findUserID($_POST['collar'])
  : 0; // if not valid, assign default value
bloodyKnuckles
  • 11,551
  • 3
  • 29
  • 37