Having an odd problem with mysql_fetch_array() - php

Why am I not able to get inside the while loop in the getCustomers() function?
$stores = $bl->getStoresForGuide($gID); //Returns 6 stores
$storelist = getStoreList($stores); //Generate the HTML for the store list
$brandlist = getCustomers($stores); //Generate the HTML for brand list
function getStoreList($stores)
{
while ($row = mysql_fetch_array($stores)) {
// Do stuff
}
//return result
}
function getCustomers($stores)
{
echo mysql_num_rows($stores); //Outputs 6
while ($row = mysql_fetch_array($stores)) {
echo "test "; // Outputs nothing
}
// Return some result
}

You're looping twice. The first time you loop, you get to the end, and the pointer isn't reset before you loop again.
If you're sure you want to do this, check out mysql_data_seek, and seek to the beginning of the result. Otherwise, I'd recommend just storing the results and iterating over the array.

You are calling getStoreList first, then by the time you call getCustomers, $stores has already had all its rows fetched.

Related

while loop getting second value onward not first value? PHP MSQL SP FPDF

my while loop starts from the second value onward, it does not show the first value. Please any help would be much appreciated.
while loop statement shown below I am using FPDF to export results but I am not sure if this got anything to do with it calling 2nd value onward.
while($dbRow = sqlsrv_fetch_array($dbQuery, SQLSRV_FETCH_ASSOC)) {
$pdf->cell(0,10,'Impact for'.' '.$dbRow['Stakeholder_ID'].' is: '.iconv("UTF-8", "ISO-8859-1", "£").''.$dbRow['Stakeholder_Return'],0,1 ,'',true );
}
thanks
If you take a look at this line of your code:
if($dbRow = sqlsrv_fetch_array($dbQuery, SQLSRV_FETCH_ASSOC))
You will see that:
It comes before your while loop
Hence your while loop gets the second row (since sqlsrv_fetch_array returns the next available row)
What it means that by calling sqlsrv_fetch_array in the if statement you increment the counter and with the next call you will get the 2nd row.
Solution:
$isFirstRow = true;
while($dbRow = sqlsrv_fetch_array($dbQuery, SQLSRV_FETCH_ASSOC)) {
if($isFirstRow){
$pdf->cell(0,10,'Overall socio-environmental impact ratio: '.iconv("UTF-8", "ISO-8859-1", "£").''.$dbRow['Schema_Return'],0,1,'',true );
$isFirstRow = false;
}
$pdf->cell(0,10,'Impact for'.' '.$dbRow['Stakeholder_ID'].' is: '.iconv("UTF-8", "ISO-8859-1", "£").''.$dbRow['Stakeholder_Return'],0,1 ,'',true );
}
You Can remove this lines as well:
do{
//...Code in between
} while ( sqlsrv_next_result($dbQuery));

The code outputs only the 1st row

I want to get employee name from $projSDE_1 that consists of emp ID for each row in the for loop below from function func_GetEmpName($empID).For the code below it should display 10 rows with $projSDE_1's namebut the problem is the code outputs only the 1st row .Why the other 9 rows could not be display?Im already stuck with this problem for 1 week.If i remove the function it will display 10 rows
.All help appreciated.
<?php
for($i=0; $i<db_rowcount();$i++){
//loop through every result set
$projID=db_get($i,0);
$projNo=db_get($i,1);
$projDesc=db_get($i,2);
$projSDE_1=db_get($i,8);//1st Services Development Engineer
$projSDE_1_name = func_GetEmpName($projSDE_1);//get name from function
}//endfor
function func_GetEmpName($empID) {
$sqlEmp="select EmpID,LastName2_c from empbasic WHERE EmpID= '".$empID."'";
db_select($sqlEmp);
$rowcount=db_rowcount();
if(db_rowcount()>0){
for($f=0;$f<count($empID);$f++){
$empID=db_get($f,0);
$empName=db_get($f,1);
}
}
return $empName;
} // function
?>
this the output from the code
need to display like this
removed function
As CBroe said, you're overwritting $empName in each loop. Put the variable in an array to avoid that.
<?php
$projSDE_1_IDs = [];
for($i=0; $i<db_rowcount();$i++){
//loop through every result set
$projID=db_get($i,0);
$projNo=db_get($i,1);
$projDesc=db_get($i,2);
$projSDE_1=db_get($i,8);//1st Services Development Engineer
array_push($projSDE_1_IDs, $projSDE_1) // Store all `$projSDE_1` in an array
}//endfor
$projSDE_1_names = func_GetEmpName($projSDE_1_IDs); // Pass the IDs' array to the function
function func_GetEmpName($empIDs) {
$names = [];
foreach($empIDs as $empId){
$sqlEmp="select EmpID,LastName2_c from empbasic WHERE EmpID= '".$empID."'";
db_select($sqlEmp);
$rowcount=db_rowcount();
if(db_rowcount()>0){
for($f=0;$f<count($empID);$f++){
$empID=db_get($f,0);
$empName=db_get($f,1);
array_push($names, $empName)
}
}
}
return $names;
} // function
var_dump($projSDE_1_names) // Display the array to see if you get all the correct data
Not very sure for the foreach part in the function but yb modifying little thing by your own if it's not working, you should be able to do what you want. I think the logic is here.

Indexing certain elements within a PHP array

I have a PHP array created by the mysqli_fetch_array() function. The array holds several rows, and without looping through them, can I grab each row one by one?
I have tried:
$links= mysqli_fetch_array($links_result);
echo $links['link'][0];
But I can't seem to get it to work. What could I be doing wrong? Is this possible?
when you do
$links= mysqli_fetch_array($links_result);
you get the next row in result set in $links just access them by the column names.
you can loop over the results like
if(mysqli_num_rows($links_result)) {
while($links= mysqli_fetch_array($links_result)) {
//each row in here
var_dump($links);
}
}
If the field name is 'link'
Without looping:
echo $links[0]['link'];
where '0' is your row number
so, for row #505 it will be:
echo $links[505]['link'];
Just make sure it exists ;)
Without loop you can grab each row of array using recursive function
like this:
function printarray_withoutloop($userarray,$elementindex)
{
if(count($userarray) > $elementindex + 1)
{
echo $userarray[$elementindex]['link'];
printarray_withoutloop($userarray,$elementindex + 1)
}
elseif(count($userarray) == $elementindex + 1)
{
echo $userarray[$elementindex]['link'];
}
}
$links= mysqli_fetch_array($links_result);
$elementindex=0;
printarray_withoutloop($links,$elementindex);

PHP Go to the next element of array

I have created an array list with the following code:
<?php
$ids = array();
if (mysql_num_rows($query1))
{
while ($result = mysql_fetch_assoc($query1))
{
$ids["{$result['user_id']}"] = $result;
}
}
mysql_free_result($query1);
?>
Now, i need to read two elements from the array. The first is the current and the second one is the next element of array. So, the simplified process is the following:
i=0: current_element (pos:0), next_element (pos:1)
i=1: current_element (pos:1), next_element (pos:2)
etc
To do this, i have already written the following code, but i cant get the next element for each loop!
Here is the code:
if (count($ids))
{
foreach ($ids AS $id => $data)
{
$userA=$data['user_id'];
$userB=next($data['user_id']);
}
}
The message i receive is: Warning: next() expects parameter 1 to be array, string given in array.php on line X
Does anyone can help? Maybe i try to do it wrongly.
The current, next, prev, end functions work with the array itself and place a position mark on the array. If you want to use the next function, perhaps this is the code:
if (is_array($ids))
{
while(next($ids) !== FALSE) // make sure you still got a next element
{
prev($ids); // move flag back because invoking 'next()' above moved the flag forward
$userA = current($ids); // store the current element
next($ids); // move flag to next element
$userB = current($ids); // store the current element
echo(' userA='.$userA['user_id']);
echo('; userB='.$userB['user_id']);
echo("<br/>");
}
}
You'll get this text on the screen:
userA=1; userB=2
userA=2; userB=3
userA=3; userB=4
userA=4; userB=5
userA=5; userB=6
userA=6; userB=7
userA=7; userB=8
You get the first item, then loop over the rest and at the end of each loop you move the current item as the next first item ... the code should explain it better:
if (false !== ($userA = current($ids))) {
while (false !== ($userB = next($ids))) {
// do stuff with $userA['user_id'] and $userB['user_id']
$userA = $userB;
}
}
Previous answer
You can chunk the arrays into pairs:
foreach (array_chunk($ids, 2) as $pair) {
$userA = $pair[0]['user_id']
$userB = $pair[1]['user_id']; // may not exist if $ids size is uneven
}
See also: array_chunk()

Speed Up While loop In php

right the problem is a smallish one but hope someone can help.
Basically we use memcache to cache some of our mysql queries and then store the results in an array for memcache. Then when the query runs again it grabs the array results from memcache and processes the results like normal.
So the code looks like this.
$query = "SELECT x,y,z FROM a WHERE b = 3";
$result = mysql_query_run($query,'memcache_name');
while($row = mysql_mem_fetch_array($result,'memcache_name')) {
//do processing
}
mysql_query_run basically just either runs the query or returns the array from memcache.
The mysql_mem_fetch_array either processes the results from mysql or transverses the array.
The transversing part uses this code.
if(is_array($result)) {
$return = current($result);
//get the current result - based on the internal pointer
next($result);//increment pointed
return $return;//return result
}
else {
//mysql result tab
//so get the array from the mysql_fetch_array
$array = mysql_fetch_array($result);
if(is_array($MEMCACHE_SERVER_RESULTS[$memcache])==false) {
//if there is no results then just set the results as array
$MEMCACHE_SERVER_RESULTS[$memcache] = array();
}
//push the array onto the end of the current array - from memcache
//if there are some results then push them on
if($single_row == 1) {
//only one row so just combine the 2 steps and store
array_push($MEMCACHE_SERVER_RESULTS[$memcache],$array);
$MEMCACHE_SERVER->set($memcache, $MEMCACHE_SERVER_RESULTS[$memcache],0,$memcache_time);
}
else if($array!==false) {
array_push($MEMCACHE_SERVER_RESULTS[$memcache],$array);
//and set it
}
else {
//set the memcache to the array that it has been making.
$MEMCACHE_SERVER->set($memcache, $MEMCACHE_SERVER_RESULTS[$memcache],0,$memcache_time);
}
//return array
return $array;
}
The problem is the current and next commands - in large arrays (which are very rare) it causes some hanging.
Currently we are in php version 5.1.6 and we are going to 5.3 will the problem be solved?
Or is there a better way to handle the array?
Thanks for your help.
Richard
in large arrays (which are very rare) it causes some hanging.
Easy. Just avoid storing large arrays in memcache.
If you do:
if (is_array($result)) {
$return = each($result); //get the current result and advance the array pointer
return $return['value']; //return result
} else // ...and so on
...is it any better?

Categories