Hello i am doing an request to an SQL Database (in php) witch looks like this…
SELECT firstname FROM users WHERE job = '$jobL'
Lets assume in the Database are three users with the $jobL
namend: Mike, Steve & Danny.
Expected Output:
array("mike", "steve", "danny")
Given Output:
array("mike")
So mike
is the first result in the users
table. SQL only gets me the first result, i want to get all results matching my query, not only the first one.
Thanks
EDIT:
Its an php function…
function GetJobMembers($jobL) { //Function to get all Members of an Job in an Array
global $db;
$AllWithJobSQL = $db->query("SELECT firstname FROM users WHERE job = '$jobL'");
$AllUsersWithJob = $AllWithJobSQL->fetch_assoc();
return $AllUsersWithJob;
}
i tested it with $jobL = groove //GTA RP Server stuff
my db manual serach:
4
Answers
Ok i fixxed it... was related to how php works with sql.
You just have to set
fetch_all(MYSQLI_ASSOC);
Like this:
I think you are using wrong fetch method.Fetch, returning matched first row.
Your code should be like that:
For more information you can check here
If you are using mysqli your code should be like that.
Use
fetch_all()
to fetch all rows as a 2-dimensional array. Then you can usearray_column()
to extract thefirstname
index from each row.You should also use a prepared statement to prevent SQL injection.
fetch() is opened as a pointer ready to step through the data one by one (usually in a while loop).
In your case, you should use fetchAll(). It fetches all the data at once, without opening any pointer, storing it in an array. It is recommended when you do not expect too many results that could cause memory problems when you want to store thousands or millions of rows from a SELECT into an array at once.
In this case $AllUsersWithJob is an associative array with all the query data. If you want to read the rows in it, you can implement a loop that loops the array: