While writing a login system for a web project Im working on I came across the problem of binding an unknown number of parameters and found this function on the php manual pages. I always like to fully understand an peice of code I put into anything Im working on and Im quite stumped as to how a few sections of this function work.
Ive commented everything I think i understand(if im wrong please let me know) and left my major questions in the comments:
<?php
function getresult($stmt) {
//Define var for holding the result
$result = array();
//asign metadata of the statments result
$metadata = $stmt->result_metadata();
//grab the feilds from the metadata and assign to var
$fields = $metadata->fetch_fields();
//for loop with internal break
for (;;) {
//pointers array (not sure why this is an array and not a stdClass)
$pointers = array();
//row empty class
$row = new stdClass();
//set pointers array to the value of the passed statement (casting $pointers to mysqli_stmt class I assume(?)
$pointers[] = $stmt;
//iterate through all fields
foreach ($fields as $field) {
//each time set $fieldname to the name from the current element of $fields
$fieldname = $field->name;
//?? this is my big issue no idea whats going on here $row hasnt been set from what i can see, and no idea why its being refered to by reference and not value
$pointers[] = &$row->$fieldname;
}
//call bind result for all values
call_user_func_array(mysqli_stmt_bind_result, $pointers);
//internal break if
if (!$stmt->fetch()) {
//if there is nothing left to fetch break
break;
}
//set the result
$result[] = $row;
}
//free resources
$metadata->free();
//return result
return $result;
}
?>
Thanks in advance!
It creates a new stdClass (pretty much like an empty array) for each row.
With $pointers[] = &$row->$fieldname; a reference to the various fields of the object is stored.
After that, mysqli_stmt_bind_result is used to tell mysqli where to store the data of the next row. When calling $stmt->fetch(), mysqli assigns it to the references in $pointers and thus to the fields in the $row object.
$pointers is an array because mysqli_stmt_bind_result expects one. Objects do not have 0..n fields but rather named values - so to assign columns based on their position using a non-associative array makes much more sense.
It does pretty much the same what mysqli::fetch_object() does.
Related
So, here's my issue: I have a function that queries sql and pulls it into a resource. In this function, I run:
if (odbc_num_rows($rs) === 0) {
return FALSE;
} else {
if ($type !== "Issues") {
while (odbc_fetch_row($rs)) {
$issues['tvi'][] = odbc_result($rs, 'TitleVolumeIssue_c_');
}
}
return $rs;
}
This does exactly what it is supposed to do. However, when I pass $rs into the next method for parsing into html, it seems as though $rs gets unset. Oddly, I can call odbc_num_rows($rs) and it gives me the correct number of rows, but dumping the var shows it is false and I can't loop through the resource to get any values.
How can I either free up that resource so that it can be used in the next function or how can I rewrite the IF condition so that I get the values without unsetting the resource?
Each time you fetch it moves the database cursor to the next row.
So odbc_fetch_row() keeps going to the next row, until the last one. After that it returns false.
Unfortunately you cannot move the row pointer back to the first record.
You will have to query your DB one more time.
Another option for this would be to store the odbc result in an array that you can loop through using a foreach. This preserves the data and you only have to query once vs multiple times (helps when dealing with a lot of data).
while($row = odbc_fetch_array($rs)) {
$resultsArray[] = $row;
}
Then loop through it like this...
foreach ($resultsArray as $key=>$value){
//Do what you need to do...
}
I had a similar problem in my question here and #Jeff Puckett was able to explain it pretty well.
I'm using PDO to get an array of relations from my DB.
$dbRelaties = $dbh->query("SELECT pkRelatieId,naam,email FROM relaties");
in another function i need to acces one specific row in this array. I've managed to do it like this:
$klant = array();
foreach($dbRelaties as $dbRelatie)
{
if($dbRelatie["pkRelatieId"] == $relatie){ $klant = $dbRelatie; break; }
}
sendMail("Subject",$klant);
The above code works. But i'me looking for a neater solution and a quicker one, the above code is called in a function and that function is called inside a loop. So everytime it executes is has to loop through $dbRelaties to get the correct relation.
Can anyone set me in the right direction?
assuming the pk means primary key, then
while($row = mysql_fetch_assoc($result)) {
$dbRelatie[$row['pkRelatieID']] = $row;
}
would produce an array keyed with your primary key field, so
$dbRelatie[$pk]['naam']
will give you that particular pk's naam value.
To show a PDO specific version of Marc B's answer.
Assuming a query was executed through PDO like so:
$sql = "SELECT pkRelatieId,naam,email FROM relaties";
$resultSet = $pdo->query($sql);
The results can be read into a PHP array using PDO's fetch method.
$dbRelaties = array();
while ($row = $resultSet->fetch(PDO::FETCH_ASSOC)) {
$dbRelaties[$row['pkRelatieID']] = $row;
}
This can then be used to access values based on the PK of the row.
sendMail("Subject", $dbRelaties[$relatie]['naam']);
Furthermore. PDO lets you assign a default fetch mode to each PDO instance, and the PDOStatement class is Traversable, so that you don't actually have to call the fetch() method in a while loop to go through a result set.
If you were to do this to a PDO object before a query: (Ideally only once right after creating the object.)
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
Then you can use a foreach loop on the result set to get row arrays with field names, instead of using a while loop.
$dbRelaties = array();
foreach ($stmt as $row) {
$dbRelaties[$row['pkRelatieID']] = $row;
}
I continue to struggle with array! This is probably easy to answer.
I'm retrieving a data set from MYSQL w/ PHP. I get an array that has the 1st row (ala the mysql_fetch_array). Typically I would just loop through this and get each value, but in this case I'm already in the middle of a loop and I need to find out if a particular value exists in the full data set (which will be more than 1 row).
I figured I could just loop through and put all the values into an array with something like:
$query = "SELECT MapId FROM Map Where GameId = $gl_game_id";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
$map_set = array();
while($row = mysql_fetch_assoc($result_set)) {
$map_set[] = $row;
}
When I print_r this, I do in fact get the full data set (e.g. all rows of MapId from table Map).
So now, when I go to look in there and see if a value (that is coming out of this other loop) exists, it won't find it.
So my code looks like:
if (in_array($i, $map_set)) {
echo "yes, it's there baby!";
}
But it doesn't work. I tried hard coding the array, and that does in fact work. So there is simply something wrong with the way I'm constructing my array that this function doesn't like it.
if (in_array($i, array(40,12,53,65))) {
echo "yes, it's there baby!";
}
arrrg... I do hate being a noobie at this.
Function mysql_fetch_assoc returned array.
If you make print_r($map_set) then you will see that is 2-dimension array. Sure in_array not worked.
Just replace $map_set[] = $row; by $map_set[] = $row["MapId"]; and then try again.
as the question states.
I have implemented a function wherein it fetches multiple rows from a database (*1) and then (*2) instantiate each row as an Object. After instantiation, the Objects are then stored into an array and then return the result to caller function and then iterates through the result array and displays each Object and add html formatting for each.
Here is the snippet of the code:
function find_all() {
//(*1) Fetch 30 comments from DB
$sql = 'SELECT * FROM comments';
$sql .= ' ORDER BY datetime DESC LIMIT 30';
return find_by_sql($sql);
}
function find_by_sql($sql='') {
global $database;
$result_set = $database->query($sql);
$object_array = array();
while($row = $database->fetch_array($result_set)) {
//(*2) Instantiate each row to a Comment object
// and then stores each comment to an object array
$object_array[] = Comment::instantiate($row);
}
return $object_array;
}
//(*3) Format and display each result.
$comments = find_all();
foreach ( $comments as $comment ) {
// Not sure if syntax is correct.. anyhow..
echo "<li>$comment->get_text()</li>";
}
However, I like the above approach since it's cleaner, easier to read, maintainable, and more OOP. But the problem is it takes a longer time to display than just simply iterating through each result than display each result once it's fetched, like so:
while ($row = mysql_fetch_array($sql)) {
echo "<li>$row['text']</li>";
}
I know the reason behind why it is slow. What I want to know is there a better way to solve the problem above?
While caching might be a good idea, it won't help because I need an updated list every time the list is fetched.
I think it can be a little faster if the script gets only the part you are interested in the result set, because fetch_array() returns 2 arrays with the same result set: associative, and numeric.
By adding MYSQLI_ASSOC (if you use mysqli): mysqli_fetch_array($result, MYSQLI_ASSOC), or try with mysql_fetch_assoc(), the script receives only the associative array.
You can test in pmpMyAdmin to see the diferences.
I have this method in my db class
public function query($queryString)
{
if (!$this->_connected) $this->_connectToDb(); //connect to database
$results = mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error());
return mysql_num_rows($results) > 0 ? mysql_fetch_assoc($results) : false;
}
This works great for queries that return 1 row, but how can I get an array returned something like this?
$array[0]['name'] = 'jim'
$array[0]['id'] = 120
$array[1]['name'] = 'judith'
$array[1]['ID'] = 121
Now I know I could use a while loop to insert this data into the array like so, but I was wondering if PHP could do this with an internal function? I havn't been able to find on the docs what I'm after.
The reason I don't want to run the while within the method is because I am going to reiterate back over the array when it's returned, and I'd rather not run through the results twice (for performance reasons).
Is there a way to do this? Do I have a problem with my general query method design?
Thank you muchly!
public function query($queryString)
{
if (!$this->_connected) $this->_connectToDb(); //connect to database
$results = mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error());
$data = array();
while($row = mysql_fetch_assoc($results))
{
$data[] = $row;
}
return $data;
}
this will always return an array.
EDIT:
I didn't read the question well.
If you realy don't want to use the loop then I would do this:
public function query($queryString)
{
if (!$this->_connected) $this->_connectToDb(); //connect to database
return mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error());
}
then loop over it, however I would just use the loop.
You might also want to look at the PDO extension. You can load the entire result set into an array or you can loop using foreach.
<?php
$db = new PDO($connection_string, $username, $password);
$result = $db->query($queryString);
foreach($result as $row) {
// do something
}
// or
$result = $db->query($queryString);
$result_array = $result->fetchAll(PDO::FETCH_ASSOC);
?>
Most people use a while() loop in the query to do exactly what you want and then loop over the array to process it.
However, you're right: it wastes memory, which could be a problem with a large dataset. An alternative is for your query method to return the resultset resource. Then your while loop can use that to fetch each row as it requires it.
To abstract that away, I would suggest another class to do that for you. Then your query call would return a new instance of that class which has the MySQL resultset resource as an instance variable and packages up the mysql_fetch_assoc() call.
Look at PEAR::MDB2 (Quickstart Cheatsheet). It provides lots of different functions for doing something like this. It also does not tie you down into using MySQL specific functions because it is a database abstraction layer.
$result = $db->queryRow($query, MDB2_FETCHMODE_ASSOC);
There are other abstraction layers such as ADO as well.
thanks for the ideas. I have a function that returns an associative array from the sql (used in Moodle).
$results = get_records_sql($sql);
//to create a numerically indexed array:
$data = array();
foreach ($results as $row)
{
$data[] = $row;
}
return $data;
}