Database query return: Check if a parameter is an array or an object

Related searches

When trying to log into this app using php and mysql, the Authorization failed error used in the app is displayed. When reading the php_error.log it displays:

[05-May-2019 03:31:51 UTC] PHP Notice: Undefined index: result in /Applications/MAMP/htdocs/iReporter/api.php on line 43 [05-May-2019 03:31:51 UTC] PHP Warning: count(): Parameter must be an array or an object that implements Countable in /Applications/MAMP/htdocs/iReporter/api.php on line 43

Log in function

//login API
function login($user, $pass) {

// try to match a row in the "login" table for the given username and password
$result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);

//Line 43
if (count($result['result'])>0) {
    // a row was found in the database for username/pass combination
    // save a simple flag in the user session, so the server remembers that the user is authorized
    $_SESSION['IdUser'] = $result['result'][0]['IdUser'];

    // print out the JSON of the user data to the iPhone app; it looks like this:
    // {IdUser:1, username: "Name"}
    print json_encode($result);
//edit
var_dump($result);

} else {
    // no matching username/password was found in the login table
    errorJson('Authorization failed');
}

}

This application use to let users log in seamlessly but stopped working abruptly without any changes made to the code. Even the unchanged backup files are receiving the same error. How can the code be be changed to allow users to log in successfully?

Update: index.php. The main file the app accesses functions

switch ($_POST['command']) {
case "login":
    login($_POST['username'], $_POST['password']); 
    break;

Solved

Changed the iOS app to post the password instead of the salted password to the database as it was creating an error.

Based on the error, you are not getting the result value within your $result variable. To check for this you can use:

if (isset($result['result']) && count($result['result']) > 0)

Which first checks that the value is set.

You will also want to investigate why you aren't getting your expected result from your DB. For that, you will need to look into what is being returned in your $result variable, and looking for any errors that your DB querying may be returning.

Efficient way to check if a mysql query returned no results?, I have been using this to check if there are any results from a query: $result = mysqli_query($link, $dsn is a database connection string, containing username, password * and other The array contains multiple possible * parameters to the query. or EXPLAIN queries mysqli_query() will return a mysqli_result object. For� The query must return all the tracked fields and properties of the object (except those that are loaded on a deferred basis) when all the following conditions are true: T is an entity explicitly tracked by the DataContext .

function login($user, $pass) {

// try to match a row in the "login" table for the given username and password
$result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);

$rows=$result->num_rows;
//Line 43

if ($rows>0) {
    // a row was found in the database for username/pass combination
    // save a simple flag in the user session, so the server remembers that the user is authorized
    $_SESSION['IdUser'] = $result['result'][0]['IdUser'];

    // print out the JSON of the user data to the iPhone app; it looks like this:
    // {IdUser:1, username: "Name"}
    print json_encode($result);
} else {
    // no matching username/password was found in the login table
    errorJson('Authorization failed');
}

}

Manual :: Runs a query and returns the data as an array, array - associative array with the query results or a DB_Error object on failure Quantity of parameters didn't match quantity of placeholders in the prepared Check the database related section of PHP-Manual to detect the reason for this� This method returns the query result as an array of objects, oran empty arrayon failure. Typically you’ll use this in a foreachloop, like this: $query=$this->db->query("YOUR QUERY");foreach($query->result()as$row){echo$row->title;echo$row->name;echo$row->body;} The above method is an alias of result_object().

You might add a is_array in addition to isset(), else access denied.

function login($user, $pass)
{

// try to match a row in the "login" table for the given username and password
    $result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);

    if (is_array($result) && isset($result) && count($result) > 0) {
        if (isset($result['result'])) {
            // a row was found in the database for username/pass combination
            // save a simple flag in the user session, so the server remembers that the user is authorized
            $_SESSION['IdUser'] = $result['result'][0]['IdUser'];

            // print out the JSON of the user data to the iPhone app; it looks like this:
            // {IdUser:1, username: "Name"}
            print json_encode($result);
        }else{
            errorJson('Sorry! There is a problem with $result["result"]!'); 
        }
    } else {
        // no matching username/password was found in the login table
        errorJson('Authorization failed');
    }

}

The error is returning since your array is not an array and is not countable.

is_array - Manual, is_array — Finds whether a variable is an array Returns TRUE if var is an array , FALSE otherwise. Examples �. Example #1 Check that variable is an array an array $b = array_values($a); test($b); // an object $c = (object)$a; test($c); a list of possible flags which in a database we have stored whether each of the flags� For single result queries, the return type can be any java object. For queries that return multiple values, you can use List or Array. In addition to these, any query may return Cursor or any query result can be wrapped in a LiveData. RxJava2 If you are using RxJava2, you can also return Flowable<T> or Publisher<T> from query methods

PHP array_key_exists() Function, The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist. Tip: Remember that if you � Query represents a SELECT SQL statement in a way that is independent of DBMS. Query provides a set of methods to facilitate the specification of different clauses in a SELECT statement.

MySQL 8.0 Reference Manual :: 12.18.3 Functions That , Returns NULL if any argument is NULL , or if the path argument does not To check only whether any data exists at the path, use JSON_CONTAINS_PATH() instead. Starting with MySQL 8.0.17, queries using JSON_CONTAINS() on InnoDB Returns the keys from the top-level value of a JSON object as a JSON array,� Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.

Returns the status of an asynchronous insert or update operation that’s identified by a Database.SaveResult object. getAsyncSaveResult(asyncLocator) Returns the status of an asynchronous insert or update operation based on the unique identifier associated with each modification. getDeleted(sObjectType, startDate, endDate)

Comments
  • Can you check whether it fetches data from the database. make sure that it is connected to MySQL databases
  • @Sathiraumesh it does. It successfully shows a username is already taken error when an existing username is tried when attempting the register function. It also successfully displays pictures from the app's database on the app's home screen.
  • use this I think it may work $rows = $result->num_rows; if($rows>0){ }
  • Thank you. Where should I add it to the code?
  • Thank you for your reply. It weirdly still shows the Authorization failed error also without any output to the error log
  • Thank you for your reply. Now the error log says ` [05-May-2019 05:18:23 UTC] PHP Notice: Trying to get property 'num_rows' of non-object in /Applications/MAMP/htdocs/iReporter/api.php on line 44 `
  • can you just check whether the $result variable gets populated after the query is executed
  • Earlier error_reporting(E_ALL); ini_set('display_errors', 1); was added to the index file. When the app was run, the browser output something like array(0). But now Expected status code in (200-299), got 500 is being displayed when trying to run the app with the error reporting statements.
  • Updated the question with the where the log in function is used
  • Thank you for your reply. Now the error log displays [05-May-2019 05:05:26 UTC] PHP Parse error: syntax error, unexpected 'count' (T_STRING) in /Applications/MAMP/htdocs/iReporter/api.php on line 44
  • Not yet. The error log says [05-May-2019 05:33:16 UTC] PHP Notice: Undefined index: result in /Applications/MAMP/htdocs/iReporter/api.php on line 44
  • when var_dump($result); is added to the log in function like the edited question, no output in seen in the browser when trying to access the index.php file via browser
  • Yeah, it was working before with $result['result'] , it just stopped abruptly. Granted it's from 2012. Source: raywenderlich.com/… Download is at the bottom 😏 hehe
  • Ok. I see the 'Sorry! There is a problem with $result["result"]!' Error. Thanks again. Will see what can be done...