While loop is not working properly - php

I am having a while loop in my function for getting the values 1 by 1 but i am getting the only 1 value
while($row= mysqli_fetch_array($this->result))
{
$image=$this->getEventDetails($row['Album_top'],'Event_image');
$alert.="<div class=facBox>
<a href='gallery.php?id=$row[Id]' style=margin-top:0px;>
<img src='admin/customer/eventgallery/$image' alt=''>
</a>
<div class=clear></div>
<a href='gallery.php?id=$row[Id]' style=margin-top:0px;>$row[Album_title]</a>
</div>";
}
I am getting the image name from another function that is
function getEventDetails($id,$fieldname)
{
$get="Select * from sarnaevent where Id='$id'";
$this->result=mysqli_query($this->con,$get);
$row=mysqli_fetch_array($this->result);
return $row[$fieldname];
}
Now i am getting the only value from the loop my $alert is having only one facbox. if i remove this line
$this->getEventDetails($row['Album_top'],'Event_image');
It works fine but i want this line to get the image name.

Inside getEventDetails(), you assign $this->result, overwriting the previous contents of $this->result. Since that occurs inside the while loop where the previous result is being used, the loop exits because there are no further results to retrieve from the inner fetch.
User a different temporary result set inside teh getEventDetails() method.
function getEventDetails($id,$fieldname)
{
$get="Select * from sarnaevent where Id='$id'";
// Different variable name...
$temporary_result = mysqli_query($this->con,$get);
$row=mysqli_fetch_array($temporary_result);
return $row[$fieldname];
}
In general, I would question the need to be storing a transient result resource into the object's $this->result for most purposes. In any case where you're using that inside a method, you are probably better off using a variable scoped only to the method, which lives only for the lifetime that result set is being used.
Please use caution when sending $id directly into the query. Although I suspect it is known to be an integer variable, and therefore it won't break the SQL, it's a good idea to get into the habit of using prepare()/execute() to prevent SQL injection.
One final point of caution: When placing the string variable into your HTML markup, be sure to use htmlspecialchars() to escape it against malforming the HTML. (If the Id is known to be an integer, it isn't necessary there)
"...<a href='gallery.php?id=$row[Id]' style=margin-top:0px;>" . htmlspecialchars($row['Album_title']) . "</a>..."

Instead of using mysqli_fetch_array() try using mysqli_fetch_assoc (see: http://php.net/manual/en/mysqli-result.fetch-assoc.php); the returned array will be associative (key-value pairs) where the keys are the column names.

You're blowing out your original query.
First, you do a query, and assign its result to $this->result. You then iterate across those results. For the first row, you immediately make a new query, overwrite $this->result with the new results, and then try to continue... but you've just replaced the rest of your results with the single result from the event details query, so mysqli_fetch_array doesn't find any more results.
Solution: use a separate variable for that result. A local one should be fine, since you don't use it outside that function. You may also need to use a separate connection; I'm not sure of that. Try it with just changing $this->result in getEventDetails() to use something like $eventResult instead.

Related

MySQLi fetch_all Error with Consecutive Calls

I've set up a class to handle my MySQLi calls. The calls are working as they should, so no problems there.
I recently removed the result handling from my class's query method to two separate setter methods. There is now an error resulting from two consecutive fetch_all calls.
The previous (working) code with a single fetch_all call loads results into the two arrays res_rows and res_cols:
// Convert results into two sets of values
// and store in properties
// $res_rows=results by row (column names in element 0)
// Each row is an indexed array
// $res_cols=results by column (associative arrays)
// Key is the column name; Value is an array
$results=$res->fetch_all(MYSQLI_ASSOC);
// $colNames is an array of the column names
$colNames=array_keys($results[0]);
// Rows
foreach($results as $r) {
$this->res_rows[]=array_values($r);
}
array_unshift($this->res_rows,$colNames);
// Columns
$vals=array();
// Count the number columns in the query
$numCols=count($colNames);
// Iterate through the columns
for($i=0;$i<$numCols;$i++) {
$col=$colNames[i];
$storage=array();
foreach($results as $r) {
$storage[]=$r[$colNames[$i]];
}
$vals[]=$storage;
}
$this->res_cols=array_combine($colNames,$vals);
I've moved this code into two methods setRes_rows and setRes_cols and called them sequentially (see code). Each method pulls results from the result object using fetch all.
$this->setRes_rows($res);
$this->setRes_cols($res);
What happens is that the first call behaves as expected, and the second call returns an empty array.
If I reverse the calls (e.g. setRes_cols first), the same thing happens (first call works as expected; second call is empty). So I know the code is good. I even changed all the variable names in one of the methods with no effect.
I dumped all properties and methods on the result object between calls and it doesn't look like it changes. But for some reason that second fetch_all does not work.
The easy fix is for me to use a single fetch_all then call my methods. But I'm interested in knowing if there's anything weird I'm missing.
Thanks, everyone.
It looks like you need to reset the result pointer after a fetch_all.
I didn't find anything in the docs specifically for fetch_all - only about resetting after a fetch_assoc(), where we can find a reference to data_seek(): http://php.net/manual/en/mysqli-result.data-seek.php
So here's what you should do:
before the second fetch_all() do a
$res->data_seek(0); // where $res is your mysqli result Object
This basicly sets the result pointer to the first record.

Custom buffering of php mysql results - strange issue

I discovered something very strange with my PHP code and mysqli functions. When I have my code in the format below:
function mainline(){
$q=mysqli_query($this->conn,"select * from table",MYSQLI_USE_RESULT);
$dataset=parse($q);
}
function parse($q){
if (!$q){return NULL;}
while($res=mysqli_fetch_array($q)){$r[]=$res;}
mysqli_free_result($q);$q=NULL;$res=NULL;return $r;
}
I'm able to retrieve data and process it. In the above example, data is returned to $dataset and each element is retrieved in the form of $dataset[row number][field name].
Now when I change my code so its like this:
function mainline(){
$q=mysqli_query($this->conn,"select * from table",MYSQLI_USE_RESULT);
$dataset=parse($q);
}
function parse($q){
if (!$q){return NULL;}
while($r[]=mysqli_fetch_array($q)); // I made change here
mysqli_free_result($q);$q=NULL;return $r;
}
The data returned is always nothing even though the select statement is exactly the same and always returns rows. During both tests, nothing has modified the data in the database.
My question then is why does while($res=mysqli_fetch_array($q)){$r[]=$res;} retrieve correct results and while($r[]=mysqli_fetch_array($q)); does not?
With the second while loop, I won't have to allocate an extra variable and I'm trying to cut down on the use of system memory so that I can run more apache processes on my system instead of waste memory unnecessarily on PHP.
Any ideas why while($r[]=mysqli_fetch_array($q)); wont work? or any ideas how I can make it work without using an extra variable? or am I stuck?
if you want to store all result in array than why not use
mysqli_fetch_all($q)
and store result in whatever you want. Though if you want to have quick access I
think caching sounds more appropriate.
mysqli_fetch_all — Fetches all result rows as an associative array, a numeric array, or both

Using a php variable inside an sql query

In my php script,i am using a php variable inside an sql query.The php variable acquires its value through a post variable as follows:
$desc0=$_POST['desc0'];
$desc1=$_POST['desc1'];
$desc2=$_POST['desc2'];
$desc3=$_POST['desc3'];
$desc4=$_POST['desc4'];
$desc5=$_POST['desc5'];
$desc6=$_POST['desc6'];
$desc7=$_POST['desc7'];
$desc8=$_POST['desc8'];
$desc9=$_POST['desc9'];
The query is:
for($i=0;$i<10;$i++)
{
$q="insert into photos(name,category,description) values ('{$name{$i}}','$category','{$desc{$i}}')";
}
The problem is that on submitting the form i am getting an error which says
"undefined variable desc".
Therefore its not taking the values from the previously defined variables?
Any help?
First of, you code is completely unsafe - you should not pass user data directly into your query. There are many topics about it, and this is a good start.
Next, you don't need to store your data in such weird way. What if you'll want to pass 20 photos? In HTML, name your fields like photos[] - and in PHP, your values will be correctly parsed as an array $_POST['photos'], so you will be able to work with array:
$photos = $_POST['photos'];
foreach($photos as $photo)
{
//$photo contains certain item, so handle it with your logic
}
Finally, your issue is because of non-obvious PHP possibility for array-dereference with curly brackets. So your $desc{$i} is an attempt to access $i-th index for non-existent array $desc. Either use $desc$i or use concatenation to separate your variables.
You must change $desc{$i} to ${"desc" . $i}

I can't echo a variable, but I can use it in a function?

I am working on a system to transfer a table into an array over PHP and html forms. In doing so I have to echo the users ID into a hidden element on the table. Here is where I am stumped:
$sqlb = mysql_query('SELECT * FROM table_row WHERE tid = 1');
$numb = 0;
while($rowsres = mysql_fetch_array($sqlb))
{
....
echo('<td style="text-align: center;"><input type="checkbox" value="'.$rowres['rid'].'" name="list[]" /></td>');
echo $rowres['rid'];
echo('<td>'.getData(1, $rowsres['rid'], 1).' '.getData(1, $rowsres['rid'], 2).'</td>');
....
}
To explain the code a little and what is happening:
I start by looping through my database.
The first .... is me doing some simple filtering of the results
Then the issues start. The first echo is me trying to put a hidden value of the row ID.
The value will NOT write. I've tried print, echo, I've tried assigning it to other variables but for whatever reason it will not write.
To make things more confusing: When I use that SAME variable in the third echo statement, it works! That function getData just accesses a database and returns the first and last name of the user, which it IS doing.
I'm extremely confused and have never come across an issue like this before.
Other things:
When I dump the $rowres it returns null, same with $rowres['rid']
I've tried echoing the variable in multiple places and none will echo but again, it works with the function because the function is returning the correct first and last name to each user.
You're using two different variable names:
$rowsres is what your assigning things to in the loop and what your passing into getData.
$rowres (note only one 's') is what you're trying to echo. This is a completely separate variable which has nothing assigned to it.

Value double echo for some reason

I'm not too sure what's going on here but I'm trying to echo a value from mysql and when I do, it just shows double for some reason
Code:
$result = MySqlQuery('SELECT value FROM table WHERE id=1');
$value = mysqli_fetch_assoc($result);
echo implode($value);
It displays 7373, the value is 73 in the DB.
I also tried echoing * instead of value, it also displays the entire row double.
Removing the echo there just displays nothing anymore so it's not like it's being echoed through another function either so I'm confused
Also the MySqlQuery() function is used by pretty much everything else on the site where it doesn't display double results as well
mysqli_fetch_array returns an array with twice as many elements as the columns you select by default (each column is represented twice). I assume that the mysqli_fetch_assoc in your code is a typo.
To solve the problem, either use mysqli_fetch_assoc instead or pass one of MYSQLI_ASSOC and MYSQLI_NUM as the second parameter to mysqli_fetch_array. As a rule of thumb, use mysqli_fetch_assoc unless you know you need something else.

Categories