Home > Enterprise >  PHP AJAX - Function not Returning SQL ID
PHP AJAX - Function not Returning SQL ID

Time:09-15

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']);
    }
}

CodePudding user response:

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
  • Related