Reset MySqli pointer? - php

I'm struggling a bit with resetting a pointer. I want to do this because I'm going to use the same query twice in the same script. As far as I can work out I can do this with resetting the pointer after I've looped trough the fetched array. If there is a better way to do this, I'd love to hear it.
Anyway, this is what I got.
$getEvent = $connection->prepare("SELECT * BLABLA FROM BLABLA");
$getEvent->bind_param("i", $eventID);
$getEvent->execute();
$getEvent->bind_result($eventMember, $eventStaff, $eventMemberID, $eventMemberSuper);
while($getEvent->fetch())
{
// Do stuff
}
// Then bunch of code, before finally another
//$getEvent->execute(); //Script doesn't work without this and next line
//$getEvent->bind_result($eventMember, $eventStaff, $eventMemberID, $eventMemberSuper);
while($getEvent->fetch())
{
// Do other stuff
}
I've tried with $getEvent->data_seek(0); but no luck. The script only works if I redeclare $getEvent->bind_result. Thanks in advance for any replies.

This places unnecessary extra strain on the database server. Rather than rewind and reuse the result set, store the whole thing in an array to begin with. You may then use it as many times and different ways as you like in the PHP application code.
Update Fixed code so it should work with MySQLi rather than PDO. Also, made the results into an associative array.
$results = array();
while($getEvent->fetch())
{
$results[] = array('eventMember'=>$eventMember, 'eventStaff'=>$eventStaff, 'eventMemberID'=>$eventMemberID, 'eventMemberSuper'=>$eventMemberSuper);
}
// Now use $results however you need to.

Related

Is there ever a reason to overwrite an array variable with one of its own elements?

I've recently "inherited" a PHP web app that uses a mySQL database as part of its backend. While going through the code, I came across a block that absolutely puzzled me.
$results = array();
$results[] = $mysqli_result->fetch_array();
$results = $results[0];
return $results;
So I get that the first two lines are initializing an empty array and assigning the first row of results from a previous query to that new array. But the third line doesn't make sense to me. As I understand it, fetch_array() only grabs one row at a time; I can't think of any reason to have the $results = $results[0]; line. The best I can come up with is that it's leftover code from when mysql_result was removed.
Is there any reason to have this third line?
No, there is no reason. This is just an example of a "cargo cult code". When you don't know how to do something properly, you just copy/paste some existing code without real understanding whether it is necessary or not.
Of course it makes no sense to create an array, then create a new element in this array, and then reassign this array variable with the first element. Instead, just assign a variable:
$result = $mysqli_result->fetch_array();
Or - better - since this variable is returned right after the assignment, simply return it right away, as the $result variable isn't going to be used anywhere else.
return $mysqli_result->fetch_array();

I have been taught 2 different ways of accessing data from a database. Which one performs better?

As the title suggests, I am looking to get some explanation about which of these methods would be best performance wise. I would think that #2 would be better because it uses only one loop instead of a while loop and a for loop. Is there even any point in using method #1?
The first method
// assign data from row to $users[]
while($row = mysqli_fetch_assoc($result))
{
$users[] = $row;
}
// and later on use a for loop to access the data in $users[]
for($i=0; $i < count($users); $i++)
{
echo $users[$i]['name'] . "<br>";
}
Method 2:
// only using a while loop
while ($row = mysqli_fetch_assoc($result))
{
echo $row['name'] . "<br>";
}
Second method is better if by performs better you mean more optimal. It's less intense on memory and cpu. First method makes your script to save all needed data to array from database, so you need some memory to "cache" it, and it also takes little of cpu time to rewrite and than read it. Of course those aren't big numbers.
But while that method performs better in regard of pure optimization, the first method is better if you want to use the fetched data to do something more intresting with it, but if that is for example printing record's from DB and than forgetting, it's not worth the wasted resources.
It depends so much about what you really want in your application. If you read mysqli_fetch_assoc will learn about this function is already returning an array, so call to iteration it's dispensable, principally with the order of array (vector, one dimension) is needed, because the function already do it for you, turning the seconde method the best option.
The first method is likable if you want to order your array more specifically, multidimensional kind of stuff or turn into an object.
PS: It's a good practice if your application it's fully OOP implemented, to do first method putting that information into a private var inside class.

Using Same Variable in Multiple PHP `while` Loops

I have a PHP page with multiple mysql_query instances. Almost every one uses a while loop to retrieve multiple rows of data.
As I keep a snippet of this often used code, and the example I was taught with, used the variable $row, I have multiple instances of the following on my page:
while ($row = mysql_fetch_assoc($foo_data)) {
$barArray[] = $row['barValue'];
}
I even have an instance of $row = mysql_fetch_assoc($foo_data) without a while loop.
I'm wondering if the multiple uses of $row as a variable on a single page, is all right?
The PHP is functioning fine, but I always want to be sure that my code is proper and conforms to standard rules.
Thank you.
yes, it's all right.
it's all right to use the same spoon when you're eating soup.
Yes that is fine. but if you try:
var_dump($row);
at the end of your code -- it will only return that last value of $row
Yup, not a problem at all.
Just like always using $i as your count in a for loop, you can repeatedly use $row to no ill effect.

Initiating the same loop with either a while or foreach statement

I have code in php such as the following:
while($r = mysql_fetch_array($q))
{
// Do some stuff
}
where $q is a query retrieving a set of group members. However, certain groups have there members saved in memcached and that memcached value is stored in an array as $mem_entry. To run through that, I'd normally do the following
foreach($mem_entry as $k => $r)
{
// Do some stuff
}
Here's the problem. I don't want to have two blocks of identical code (the //do some stuff section) nested in two different loops just because in one case I have to use mysql for the loop and the other memcached. Is there some way to toggle starting off the loop with the while or foreach? In other words, if $mem_entry has a non-blank value, the first line of the loop will be foreach($mem_entry as $k => $r), or if it's empty, the first line of the loop will be while($r = mysql_fetch_array($q))
Edit
Well, pretty much a few seconds after I wrote this I ended up coming with the solution. Figure I'd leave this up for anyone else that might come upon this problem. I first set the value of $members to the memcached value. If that's blank, I run the mysql query and use a while loop to transfer all the records to an array called $members. I then initiate the loop using foreach($members as as $k => $r). Basically, I'm using a foreach loop everytime, but the value of $members is set differently based on whether or not a value for it exists in memcached.
Why not just refactor out doSomeStuff() as a function which gets called from within each loop. Yes, you'll need to see if this results in a performance hit, but unless that's significant, this is a simple approach to avoiding code repetition.
If there's a way to toggle as you suggest, I don't know of it.
Not the ideal solution but i will give you my 2 cents. The ideal would have been to call a function but if you dont want to do that then, you can try something like this:
if(!isset($mem_entry)){
$mem_entry = array();
while($r = mysql_fetch_array($q))
{
$mem_entry[] = $r;
}
}
The idea is to just use the foreach loop to do the actual work, if there is nothing in memcache then fill your mem_entry array with stuff from mysql and then feed it to your foreach loop.

PHP Change Array Over and Over

I have any array
$num_list = array(42=>'0',44=>'0',46=>'0',48=>'0',50=>'0',52=>'0',54=>'0',56=>'0',58=>'0',60=>'0');
and I want to change specific values as I go through a loop
while(list($pq, $oin) = mysql_fetch_row($result2)) {
$num_list[$oin] = $pq;
}
So I want to change like 58 to 403 rather then 0.
However I always end up getting just the last change and non of the earlier ones. So it always ends up being something like
0,0,0,0,0,0,0,0,0,403
rather then
14,19,0,24,603,249,0,0,0,403
How can I do this so it doesn't overwrite it?
Thanks
Well, you explicititly coded that each entry should be replaced with the values from the database (even with "0").
You could replace the values on non-zero-values only:
while(list($pq, $oin) = mysql_fetch_row($result2)) {
if ($pq !== "0") $num_list[$oin] = $pq;
}
I don't get you more clear, i thought your asking this only. Check this
while(list($pq, $oin) = mysql_fetch_row($result2)) {
if($oin==58) {
$num_list[$oin] = $pq;
}
}
In my simulated tests (although You are very scarce with information), Your code works well and produces the result that You want. Check the second query parameter, that You put into array - namely $pg, thats what You should get there 0,0,0,0,0...403 OR Other thing might be that Your $oin numbers are not present in $num_list keys.
I tested Your code with mysqli driver though, but resource extraction fetch_row is the same.
Bear in mind one more thing - if Your query record number is bigger than $numlist array, and $oin numbers are not unique, Your $numlist may be easily overwritten by the folowing data, also $numlist may get a lot more additional unwanted elements.
Always try to provide the wider context of Your problem, there could be many ways to solve that and help would arrive sooner.

Categories