php: iterate recordset - easier way? - php

i've just changed from ASP to php and i'm a bit confused about the way php is handling recordsets.
i'd like to know if there's an easier way to iterate a recordset by creating a php class.
here's the ASP syntax to show what i mean:
sq = "select * from myData"
set rs = db.execute(sq)
do while not rs.eof
response.write rs("name") // output data (response.write = echo)
rs.movenext
loop
any ideas?
thanks

You'd pretty much do the same thing...
$sql = "select * from myData";
$result = mysql_query($sql) or die(mysql_error()); //executes query
while($row = mysql_fetch_array($result)){ //will automatically return false when out of records
echo $row['name'];
}

You're probably looking for a function contains word fetch in it's name.
E.g. mysql_fetch_assoc() or $pdo->fetchAll().
Most of database API functions in PHP returns some sort of pointer variable called "resource", which can be passed to the fetch-family function, like this:
$res = mysql_query();
while($row = mysql_fetch_assoc($res)){
echo $row['name'];
}
However, some of them (like PDO's fetchAll method) returns but regular PHP array, which you can iterate using as regular foreach operator.

Related

PHP fetch_assoc() display issue [duplicate]

Is there a way to enable the use of fetch_assoc() several times on the same page with prepared statements?
$data = $conn->prepare("SELECT * FROM some_table WHERE id=?");
$data->bind_param('i',$id);
$data->execute();
$result = $data->get_result();
I'd like to be able to use fetch_assoc() on the same page as many times as I want as many different ways I want. If I want to loop twice, I should be able to do that. If I want to loop and do a single fetch, I should also be able to do that. Right now it seems, once fetch_assoc() is being used once, it cannot be used again on the same page.
In a loop
while($row = $result->fetch_assoc()){
...
}
Single fetch
$user = $result->fetch_assoc();
$first_name = $user['first_name'];
While technically possible (Nick shows how) to rewind the mysqli_result object, many people find it cumbersome to work with mysqli_result at all. It's much easier to fetch all the records into a PHP array and work with a multidimensional array instead of the mysqli_result object.
$result = $data->get_result()->fetch_all(MYSQLI_ASSOC);
This way you can do whatever you want with this array. You can filter, you can loop many times, you can use all the standard array functions in PHP.
$resultsFiltered = array_filter($results, fn($e) => $e['someColumn']>200);
foreach($resultsFiltered as $row) {
// only records with someColumn > 200
}
You can use mysqli_result::data_seek to reset the result pointer after each usage so you can loop over the results multiple times. For example:
while($row = $result->fetch_assoc()){
...
}
$result->data_seek(0);
while($row = $result->fetch_assoc()){
...
}

What are ways to run a MySQL query in PHP and output the result to an array in less space?

I'm getting really tired of writing:
$rows = array();
$result = $db->query("SELECT * FROM `table` WHERE `field`='".$information."'");
while($row = $result){
$rows[] = $row;
}
I tried a function, but it was kinda of messy feeling changing the input to field inputs. I thought maybe this or something similar would help:
$rows = array();
while($row = ($db->query("SELECT * FROM `table` WHERE `field`='".$information."'"))->fetch_assoc()){
$rows[] = $row;
}
but I get unexpected T_OBJECT_OPERATOR. I'm still on the line about using a function. Maybe there's a more efficient way of writing one. This is how I tried writing a function:
$array = SELECT ($db,$toSelect,$table,$where);
It still seems cumbersome, however. I would like something like $array = $db->("MYSQL");
The simplest solution is to write a function, which expects a database handle and a string query parameter, and returns all the rows.
$rows = fetch_all($db, "SELECT ...");
A bit more advanced is to write your own database class which wraps the database handle and adds such functionality.
$rows = $mydb->fetch_all("SELECT ...");
If you don't want to reinvent the wheel, simply use an existing ORM / PHP database library which does all this (and more) for you.
$db
->select('*')
->from('table')
->where('field', $information);
Note: http://www.php.net/manual/en/security.database.sql-injection.php - the third solution automatically solves this problem.

Passing PHP MySQL Result Object to Function

I'm trying to take a MySQL result row and pass it to a function for processing but the row isn't getting passed. I'm assuming this is because the actual row comes back as a object and objects can't get passed to function?
E.G
function ProcessResult($TestID,$Row){
global $ResultArray;
$ResultArray["Sub" . $TestID] = $Row["Foo"] - $Row["Bar"];
$ResultArray["Add" . $TestID] = $Row["Foo"] + $Row["Bar"];
}
$SQL = "SELECT TestID,Foo,Bar FROM TestResults WHERE TestDate !='0000-00-00 00:00:00'";
$Result= mysql_query($SQL$con);
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
$nRows = mysql_num_rows($Result);
for ($i=0;$i<$nRows;$i++)
{
$Row = mysql_fetch_assoc($Result);
$TestID = $Row[TestID];
ProcessResult($TestID,$Row);
}
}
What I need is $ResultArray populated with a load of data from the MySQL query. This isn't my actual application (I know there's no need to do this for what's shown) but the principle of passing the result to a function is the same.
Is this actually possible to do some how?
Dan
mysql_query($SQL$con); should be mysql_query($SQL,$con); The first is a syntax error. Not sure if this affects your program or if it was just a typo on here.
I would recommend putting quotes around your array keys. $row[TestID] should be $row["TestID"]
The rest looks like it should work, although there are some strange ideas going on here.
Also you can do this to make your code a little cleaner.
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
while($Row = mysql_fetch_assoc($Result))
{
$TestID = $Row['TestID'];
ProcessResult($TestID,$Row);
}
}
mysql_fetch_assoc() returns an associative array - see more
If you need an object, try mysql_fetch_object() function - see more
Both array and object can be passed to a function. Thus, your code seems to be correct, except for one line. It should be:
$Result= mysql_query($SQL, $con);
or just:
$Result= mysql_query($SQL);

Get the full result

Is there a PHP function to get the full result with a mysql query in a multidimensional array?
SELECT * FROM table
Usually I would make something like this:
$query = mysql_query = ("SELECT * FROM table");
while ($result = mysql_fetch_array($query){
echo $result[0];
}
You can create your own function like mysql_fetch_array_complete() and imagine that it's builtin ;-)
If you are using PDO to access mysql there is.
http://www.php.net/manual/en/pdostatement.fetchall.php
Otherwise you need to do it yourself.
$query = mysql_query = ("SELECT * FROM table");
$all_results = array();
while ($result = mysql_fetch_array($query){
$all_results[] = $result;
}
print_r($all_results);
The $all_results variable will be a multi-dimensional array with all the records.
You could always write your own function to do this, but it would often lead to an unnecessary iteration through the result set (once when you call your function, another time when you actually USE the resulting array).
Since you're in php5, you could create a database result class that implements the Iterator interface. Then, you can use your class in foreach () loops and have much of the ease-of-use that you get from an array.
As of PHP 5.3 there is a built in function:
fetch_all

PHP DELETE immediately after select

I have a PHP server script that SELECTs some data from a MySQL database.
As soon as I have the result from mysql_query and mysql_fetch_assoc stored in my own local variables, I want to delete the row I just selected.
The problem with this approach is that it seems that PHP has done pass-by-reference to my local variables instead of pass-by-value, and my local variables become undefined after the delete command.
Is there anyway to get around this? Here is my code:
$query="SELECT id, peerID, name FROM names WHERE peer = $userID AND docID = '$docID' AND seqNo = $nid";
$result = mysql_query($query);
if (!$result)
self::logError("FAIL:1 getUsersNamesUpdate() query: ".$query."\n");
if (mysql_num_rows($result) == 0)
return array();
$row = mysql_fetch_assoc($result);
$result = array();
$result["id"] = $row["id"];
$result["peerID"] = $row["peerID"];
$result["name"] = $row["name"];
$query="DELETE FROM names WHERE id = $result[id];";
$result = mysql_query($query);
if (!$result)
self::logError("FAIL:2 getUsersNamesUpdate() query: ".$query."\n");
return $result;
You are overwriting your $result variable with your second statement:
$query="DELETE FROM names WHERE id = $result[id];";
$result = mysql_query($query); // result does not contain the array anymore
Change the name to something else. It has nothing to do with call-by-reference or such.
Actually, your first assignment of the values is unnecessary as $row is already an array:
$row = mysql_fetch_assoc($result);
$result = array();
$result["id"] = $row["id"];
$result["peerID"] = $row["peerID"];
$result["name"] = $row["name"];
You could just do:
$row = mysql_fetch_assoc($result);
// at the end
return $row;
Then you don't even have to change your variable name for the second statement. But consider to use meaningful variable names.
First of all, why not just use only one query to delete the row that interests you ?
Something like this should do the trick, I suppose :
delete
from names
where peer = $userID
AND docID = '$docID'
AND seqNo = $nid
Of course, don't forget to escape/convert the values that should be ;-)
This way, no need for a select query, followed by a delete one.
Second : to make your code more easier to read / understand / maintain, you should probably not re-use the same variable for several different purposes.
Here, your $result variable is used for more than one thing, and it makes things harder to understand :
resource returned by the first mysql_query
then, array containing data from the first row
then, resource returned by the second mysql_query
It's a bit confusing, and will, one day or another, lead to errors...
Actually, it already has ;-) : the third assignment is overriding the data you're getting with the second ones, and boom, you've lost the information that corresponds to the row you've just deleted ;-)

Categories