Reputation: 755
So I am trying to see if a set of numbers is in an array.
array(3) {
[0]=> array(2) {
["account_ID"]=> string(10) "1781890863"
[0]=> string(10) "1781890863"
}
[1]=> array(2) {
["account_ID"]=> string(10) "2093832999"
[0]=> string(10) "2093832999"
}
[2]=> array(2) {
["account_ID"]=> string(10) "2147483647"
[0]=> string(10) "2147483647" }
}
I have the array and the values are all there and everything is just dandy. But when I compare using in_array it returns false. I don't quite know why.
class DB(){
public function getAllID(){
$result_row = $this->accessDB( 'SELECT account_ID FROM users;');
return $result_row;
}
}
That is the function that I am using to access the database and return the array and then
$app = new DB();
if(isset($_GET['user'])){
if(in_array($_GET['user'],$app->getAllID())){
include('account.php');
echo 'Account DOES exist';
} else {
var_dump($app->getAllID());
echo '<br/>'.$_GET['user'].' does NOT exist.';
}
}
Does anyone see why my code here won't work maybe I am just accessing the DB wrong?
Upvotes: 0
Views: 101
Reputation: 3070
Your function pulling the query results is returning a multi-deminsional array. You can either loop through the array to determine if $_GET['user']
is in each array within or change your function that is pulling the user ids.
In your function loop through your query results and build your array:
$user_ids = array();
foreach ($result_row as $record) {
$user_ids[] = $record['account_ID'];
}
return $user_ids;
This will create an array of user ids. Then you can use in_array()
to determine if the user id exists.
Upvotes: 0
Reputation: 3533
Your method returns array of assoc array, instead of array of int/string (on which your check is working).
Easiest solution - pull account_ID
one level up.
public function getAllID(){
$result_row = $this->accessDB( 'SELECT account_ID FROM users;');
return array_map(function($entry) { return $entry['account_ID']; }, $result_row);
}
Better solution - validate with DB query:
// must escape $userId before doing query or you are vulnerable to SQL injection
$this->accessDB("SELECT count(account_ID) FROM users WHERE account_ID = {$userId} LIMIT 1");
Upvotes: 2
Reputation: 79024
You need to loop through $app->getAllID()
because if the $_GET['user']
is there it will be in $app->getAllID()[0]
, $app->getAllID()[1]
etc..
Really, you should do this check for $_GET['user']
in the query with a WHERE clause and return true if it exists and false if not. Why query and return all account_ID
s just to check if one exists?
Upvotes: 0