How to get row count & loop through the result set - php

I've recently gotten over my bad habit of using the deprecated mysql functions in favor of mysqli, and I'm having some issues.
Right now, I'm using something similar to the following:
$query = $conn->prepare("SELECT * FROM table WHERE cid = ?");
$query->bind_param('i', $id);
$query->execute();
And this is where I get stuck. In order to loop through the result, I use:
while ($row = $query->get_result()->fetch_assoc()) {
//My code here
}
However, I need to determine the number of rows returned from the query before going through the results. To do this, I need to do the following:
$query->store_result();
$rows = $query->num_rows;
But I get errors when calling both get_result and store_result on the same query.. is there an easier way to do this? Am I overthinking things? I basically just want to determine if the result set has greater than x # of rows, and if so, loop through the results.
Thanks for any help.

Related

multi query select using wrong array?

I have a multi query select which half works. The first query is straight forward.
$sql = "SELECT riskAudDate, riskClientId, RiskNewId FROM tblriskregister ORDER BY riskId DESC LIMIT 1;";
The second one doesn't seem to work even when I do it on its own:
$sql ="SELECT LAST(riskFacility) FROM tbleClients";
If I get rid of the LAST it returns the first entry in that field of the table. I want to use the LAST to get the LAST entry in that field.
When I do the first query on its own I get the data returned and I can echo it to the screen. When I add the second (with out the LAST) I get nothing. Here is what I am using
$result = $conn->query($sql);
if ($result == TRUE){
$r = $result->fetch_array(MYSQLI_ASSOC);
echo $r['riskAudDate'];
echo $r['riskClientId'];
echo $r['RiskNewId'];
echo $r['riskFacility'];
echo "<pre>";
print_r($r);
echo "</pre>";
}
The last bit is just for me to see whats in the array and just for testing.
So I have worked out that its the results array that is not right.
If I change the actual query to multi query I get this:
Call to a member function fetch_array() on boolean
So the array bit seems to be wrong for a multi query. The data returned is one row from each table. It works for the top query but add in the second (which I'm not sure is correct anyway) and the whole things crashes. So I guess it's a two part question. Whats wrong with my inserts and whats wrong with my returned array?
There is no last() function in mysql, it is only supported in ms access, if I'm not much mistaken. In mysql you can do what you do in the 1st query: do an order by and limit the results to 1.
According to the error message, the $conn->query($sql) returns a boolean value (probably true), therefore you cannot call $result->fetch_array(MYSQLI_ASSOC) on it. Since we have no idea what exactly you have in $sql variable, al I can say is that you need to debug your code to detrmine why $conn->query($sql) returns a boolean value.
Although it is not that clear from mysqli_query()'s documentation, but it only supports the execution of 1 query at a time. To execute multiple queries in one go, use mysqli_multi_query() (you can call this one in OO mode as well, see documentation). However, for security reasons I would rather call mysqli_query() twice separately. It is more difficult to execute a successful sql injection attack, if you cannot execute multiple queries.
It seems to me you are trying to do two SQL-queries at once.
That is not possible. Do a separate
$result = $conn->query($sql);
if ($result == TRUE){
while( $r = $result->fetch_array(MYSQLI_ASSOC)) {
...
}
}
for each SQL-query.
concerning :
$sql ="SELECT LAST(riskFacility) FROM tbleClients";
since the last function does not exists in MySQL i would recommend doing a sort like this(because i don't know what you mean with last )
$sql ="SELECT riskFacility FROM tbleClients order by riskFacility desc limit 0,1";

Simplest method to retrieve single (and only) row in SQLite using PDO

I have this PDO
$stmt = $db->prepare('SELECT * FROM channels WHERE id=:id');
$stmt->bindValue(':id', $id, SQLITE3_INTEGER);
$result = $stmt->execute();
What now is the simplest method to access the row returned using $row['column_name']?
I know that for sure the query will only ever return a single row as it's impossible to have more than 1 row with the same id so I am looking to keep the code as simple as possible to access that row.
Examples I've seen online are quite long and complex, using while loops to loop through rows etc. that I don't need.
It should be as simple as
$row = $stmt->fetch(PDO::FETCH_ASSOC);
The examples you've seen probably have something more like
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { ...
because they're designed to process a query result with multiple rows. But if you know you'll only ever have one row, you can just forgo the loop. Of course, this is assuming your query actually executed successfully and returned a result. It would be a good idea to at least check
if ($row) { ...
before you try to use it in your subsequent code.

Multiple Nested query issue, possible to do it in sql?

I asked a question earlier on today regards to Running multiple queries in loop, and building multidimensional array This code that I wrote works, but it just doesn't feel right.
The main issue I was noticing is that to do what I needed to do involved nesting queries inside the loop over of the results of a previous query. This seemed to kick up a stink of errors once I did this more than once, and after a little google time it seems that this just isn't possible to do. So I broke the queries apart and used a for loop for the second query. But this just feels messy, I'm now running two loops and I'm sure there must be a better way of doing this. Some code:
// get all to be done by each user
$stmt = $conn->prepare("SELECT activityId FROM done WHERE userId=? ORDER BY number DESC");
$stmt->bind_param("s", $idq);
$stmt->execute();
$stmt->bind_result($aiddo);
$stmt->store_result();
$num_do = $stmt->num_rows;
while($stmt->fetch()) {
$activityId_do[] = $aiddo;
}
// get location information
for($i=0; $i<=$num_do; $i++) {
$act_done = $conn->prepare("SELECT fullAddress FROM `activity` WHERE (id=?)");
$act_done->bind_param("s",$activityId_do[$i]);
$act_done->execute();
$act_done->bind_result($fullAddress);
while($act_done->fetch()) {
$do_array[] = array(
"fullAddress"=>$fullAddress,
"type"=>"do"
);
}
}
So this code above is inside a while loop over the results on a query that gets all the users a user is following.
I was wondering if there is a better way of doing this, is it possible to use some kind of sql magic on it and do it all in the query?

Use bind_result to push into array

Is it possible to use bind_result and bind all of the columns into an array? The reason I ask is because I execute the code on lots of different tables and don't want to have to put each column in when the amount changes.
$stmt = $mysqli->prepare("SELECT * FROM " . $company . " WHERE `id` = ?");
$stmt->bind_param('s', $route);
$route = $_GET['routeid'];
$stmt->execute();
$stmt->bind_result($test);
Currently that's what my PHP looks like. Clearly it's wrong because you must bind them to something, I just need to know how to put the data into an array and bind it to that (hoping you can understand that poor explanation).
Thanks
PS. I've looked at the related answer and it only confused me. If someone could explain in a little more detail I'd appreciate it.
Why do you specifically want to use bind_result to do this when a more natural alternative already exists?
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
If fetch_assoc is not exactly what you want, other variations include fetch_row (numeric indexing) and fetch_object.
$stmt->bind_result($test['col1'], $test['col2']);
Continue adding $test['colX'] for however many columns you have.

PHP PDO mysql counting rows returned

There are a lot of questions on this and I have done a lot of research. However, I am still wondering if I am doing this right.
Here is my statement (I've simplified it):
try {
$stmt = $pdc_db->prepare("SELECT * FROM table WHERE color = :color");
$stmt->bindValue(':color', $selected_color);
$stmt->execute();
$color_query = $stmt->fetchAll();
} catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
Now, I am using the following to see if this has returned any results:
if (count($color_query) > 0) {
This works, HOWEVER... the SELECT statement will only return one result. So now to access stuff in the results, I am using $color_query[0][colorname]. I know this is because I am using fetchAll(), but I really want to be using fetch()
But if I just use fetch(), I am losing the ability to do a count(), which is pretty simple to me. I know I can do a separate query and check the results of SELECT COUNT(*), but that seems like more work (setting two separate queries up for each)
There must be a way, using PDO in PHP with mySQL, to check if fetch() has returned a result?
$stmt->rowCount() after the execute(), but doesn't work with all databases... try it with MySQL and see what you get.
You can do it with fecth, fecth will return false if no results returns.
if ($row = $stmt->fetch()) {
//get the first row of the result.
//....
}

Categories