SQLite query not returning all result rows - php

I am trying to pull out a section of rows from a SQLite 3 database using the following code:
function getunsolved($user) {
$sql = "SELECT challenge FROM completed WHERE status = 0 AND username = '$user';";
$rez = $this->query($sql);
$temp = $rez->fetchArray(SQLITE3_NUM);
return $temp;
}
Unfortunately, the code is only returning 1 row, and should be returning 9 rows.
Running the above SQL code on the database, and substituting a valid username for $user returns the correct amount of rows, so I know the problem isn't the SQL code.
My table format is as follows:
username (TEXT), challenges (TEXT), status (INTEGER) (in that order, if it matters)

According to the manual:
SQLite3Result::fetchArray - Fetches a result row as an associative or numerically indexed array or both. By default, fetches as both.
So if you want to get all of the results, you should iterate over them and return the aggregated data:
$ret = array();
while($row = $rez->fetchArray(SQLITE3_NUM)) {
$ret[] = $row;
}
return $ret;

Related

SQL | Get all results from query not just the first

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:
Use fetch_all() to fetch all rows as a 2-dimensional array. Then you can use array_column() to extract the firstname index from each row.
You should also use a prepared statement to prevent SQL injection.
function GetJobMembers($jobL) { //Function to get all Members of an Job in an Array
global $db;
$stmt = $db->prepare("SELECT firstname FROM users WHERE job = ?");
$stmt->bind_param("s", $jobL);
$stmt->execute();
$result = $stmt->get_result();
$AllUsersWithJob = $result->fetch_all(MYSQLI_ASSOC);
return array_column($AllUsersWithJob, 'firstname');
}
fetch() is opened as a pointer ready to step through the data one by one (usually in a while loop).
while($row= $AllWithJobSQL->fetch_assoc()) {
echo $row["job"].PHP_EOL;;
}
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.
$AllUsersWithJob = $AllWithJobSQL-> fetch_all(MYSQLI_ASSOC);
return $AllUsersWithJob;
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:
$resultado= GetJobMembers("doctor");
foreach ($resultado as $row){
echo $row["job"].PHP_EOL;
}
Ok i fixxed it... was related to how php works with sql.
You just have to set fetch_all(MYSQLI_ASSOC);
Like this:
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_all(MYSQLI_ASSOC);
return $AllUsersWithJob;
}
I think you are using wrong fetch method.Fetch, returning matched first row.
Your code should be like that:
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
For more information you can check here
If you are using mysqli your code should be like that.
$AllWithJobSQL = $mysqli->query("SELECT firstname FROM users WHERE job = '$jobL'");
$AllUsersWithJob = $AllWithJobSQL ->fetch_all(MYSQLI_ASSOC);
return $AllUsersWithJob;

Php PDO request for data from the sum of a derived table column

Here is an SQL query that I am attempting to use in some php PDO code:
SELECT SUM(credit_hours) AS hours FROM(SELECT Course_List.credit_hours FROM Program_Courses, Course_List
WHERE program_id= :pid and concentration_id= :conid
and fulfills_major=1 and Program_Courses.course_id = Course_List.course_id ) AS major_credits
When I run this query on my database in SQL Workbench I get a derived table with a single column named
"hour" and a single row with the value 76 in it.
Here is the php code I'm using to try to get this same data stored in a variable $major_hours:
$result = $conn->prepare("SELECT * FROM students WHERE username = :un");
$result->bindParam(':un',$user);
$result->execute();
$data = $result->fetch(PDO::FETCH_ASSOC); //returns an associated array where the indices are the column names
$program = $data['program_id'];
$concentration = $data['concentration_id'];
//get the total number of credit hours in the student's major/concentration
$result = $conn->prepare("SELECT SUM(credit_hours) AS hours FROM(
SELECT Course_List.credit_hours FROM Program_Courses, Course_List
WHERE program_id= :pid and concentration_id= :conid
and fulfills_major=1 and Program_Courses.course_id = Course_List.course_id
) AS major_credits");
$result->bindParam(':pid',$program);
$result->bindParam(':conid',$concentration);
$result->execute();
$major_hours = $result->fetchColumn();
I know that the variables $user, $program, and $concentration all have legitimate values because when I echo those to the page, I get the correct result. However, echoing $major_hours gives absolutely nothing. What am I doing wrong?
Use fetch as you may guess it fetches the next row from a result set
The fetch_style parameter determines how PDO returns the row, in your case FETCH_ASSOC would be a good one since it returns an array indexed by column name as returned in your result set.
$row = $result->fetch(PDO::FETCH_ASSOC);//row is an associative array
$major_hours = $row['hours']; //access the column name hour
echo $majors_hours; //will print the hour value from db
I have not used sql workbench, but you may want to use isnull() or coalesce() on your SUM(credit_hours) expression. I think that should result in $major_hours showing 0.
Use this
$major_hours = $result->fetch(PDO::FETCH_ASSOC);
echo $majors_hours['hours'];
There is 2 way to return a data from database. fetch(PDO::FETCH_ASSOC) and fetchAll(PDO::FETCH_ASSOC). Fetch only return 1 row from database .. but fetchAll will return all row from the database query you make.
And (PDO::FETCH_ASSOC) it means will return the data with an array.

Enumerating over several cells in MySQL DB using PHP

Problem: I have several rows of results, for a single survey. Each survey can have any number of rows in the "Results" Table. There's a column called key_value. It's either 0 or -1. What is the fastest way in PHP to enumerate over several rows in a MySQL database, access each object, and flag a Boolean in PHP to tell me whether or not this particular survey has any rows with a key_value of 0?
something like this, except not brute forcing it...
for (i = 0; i < mysqlrows.length; i++){
if (mysqlrow.key_value == 0)
flag = true;
else
flag = false;
}
To operate on all matching (key_value = 0) Results:
$query = <<<EOD
SELECT result_id
FROM Results
WHERE key_value = 0
EOD;
$pdo = new PDO(....);
$stmt = $pdo->prepare($query);
if ($stmt->execute()) {
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result_id = $result['result_id'];
//do something with this result?
}
}
But if you only wanted the number of Results with key_value = 0, use some SQL like:
SELECT COUNT(*) as num_with_zero FROM Results WHERE key_value = 0

Checking if a value is in the db many times

I have a table A, with just two columns: 'id' and 'probably'. I need to go over a long list of ids, and determine for each one whether he is in A and has probability of '1'. What is the best way to do it?
I figured that it would be best to have 1 big query from A in the beginning of the script, and after that when I loop each id, I check the first query. but than i realized I don't know how to do that (efficiently). I mean, is there anyway to load all results from the first query to one array and than do in_array() check? I should mention that the first query should had few results, under 10 (while table A can be very large).
The other solution is doing a separate query in A for each id while I loop them. But this seems not very efficient...
Any ideas?
If you have the initial list of ids in array, you can use the php implode function like this:
$query = "select id
from A
where id in (".implode (',', $listOfIds).")
and probability = 1";
Now you pass the string as first parameter of mysql_query and receive the list of ids with probability = 1 that are within your initial list.
// $skip the amount of results you wish to skip over
// $limit the max amount of results you wish to return
function returnLimitedResultsFromTable($skip=0, $limit=10) {
// build the query
$query = "SELECT `id` FROM `A` WHERE `probability`=1 LIMIT $skip, $limit";
// store the result of the query
$result = mysql_query($query);
// if the query returned rows
if (mysql_num_rows($result) > 0) {
// while there are rows in $result
while ($row = mysql_fetch_assoc($result)) {
// populate results array with each row as an associative array
$results[] = $row;
}
return $results;
} else {
return false;
}
}
for each time you call this function you would need to increment skip by ten in order to retrieve the next ten results.
Then to use the values in the $results array (for example to print them):
foreach ($results as $key => $value) {
print "$key => $value <br/>";
}
Build a comma separated list with your ids and run a query like
SELECT id
FROM A
WHERE id IN (id1, id2, id3, ... idn)
AND probability = 1;
Your first solution proposal states that:
You will query the table A, probabyly using limit clause since A is a table with large data.
You will place the retrieved data in an array.
You will iterate through the array to look for the id's with probability of '1'.
You will repeat the first three steps several times until table A is iterated fully.
That is very inefficient!
Algorithm described above would require lots of database access and unneccessary memory (for the temporary array). Instead, just use a select statement with 'WHERE' clause and process with the data you want.
You need a query like the following I suppose:
SELECT id, probably FROM A WHERE A.probably = 1
If i understood you correctly, you should filter in the SQL query
SELECT * FROM A WHERE A.probably = 1

Read data from all rows in column PHP MySQL

I am doing some work that requires me to add the data from a specific column, say Column 1, to a PHP array. I can get the data from the first row in Column 1, but it stop there. How do I collect that columns data from every row in the table?
You have to loop over the result set in a while loop:
$result = mysql_query('SELECT...');
$data = array();
while(($row = mysql_fetch_array($result))) {
$data[] = $row['columnName'];
}
Every call to mysql_fetch_array will get the next row of the result set. If there is no row anymore, it will return null and the loop stops.
The documentation provides good examples.
Update:
Regarding duplicates: Either specify your SQL query correctly (preferred), e.g.
SELECT DISTINCT columnName FROM table
or use array_unique after you fetched all the data:
$data = array_unique($data);
//Variable declaration as a small sql query
$query = "select RowName FROM Table;";
//Execute Query
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
//Do Stuff
}

Categories