0

In the example below I am taking an array of the ID's only to turn it into a while and then back into an array only to explode it on the comma on the page. Surely there must be an easier way of doing this.

I am after an array of the $row['ID']s

function get_other_elector_phone($telephone,$current,$criteria){
    $the_others = mysql_query("SELECT * FROM electors WHERE telephone = '$telephone' $criteria"); $results = '';
    while($row = mysql_fetch_array($the_others))  { 
    $results .= $row['ID'].','; } return $results;
}


$others = get_other_elector_phone(g('electors',$elector,'telephone'),$elector,$criteria); 
                    if($others){ $others = explode(',',$others);
1
  • 2
    Just... build and return an array instead of a string? Commented Jun 25, 2012 at 10:36

2 Answers 2

0

just as @daverandom said, just rebuild an array, this is the syntax :

function get_other_elector_phone($telephone,$current,$criteria){
  $the_others=mysql_query("SELECT * FROM electors WHERE telephone = '$telephone' $criteria"); 
  $results = array();
  $i=0;
  while($row = mysql_fetch_array($the_others))  { 
    $results [$i]= $row['ID'];
    $i++; 
  } 
  //results returned outside loop
  return $results;
}

$others = get_other_elector_phone(g('electors',$elector,'telephone'),$elector,$criteria); 

The $others will return an array.

Sign up to request clarification or add additional context in comments.

3 Comments

That is only returning the first result nor all of them as mine did
In this example, return $results needs to be outside of the while loop. You can also dispense with $i; assigning $results[] = $row['ID'] will do the same.
thank @joe bowman, I mean like that, I just placed the wrong place
-1

instead of

function get_other_elector_phone($telephone,$current,$criteria){
  $the_others = mysql_query("SELECT * FROM electors WHERE telephone = '$telephone' $criteria"); $results = '';
  while($row = mysql_fetch_array($the_others))  { 
    $results .= $row['ID'].','; } return $results;
  }
}

just return the result of mysql_fetch_array()

function get_other_elector_phone($telephone,$current,$criteria){
  $the_others = mysql_query("SELECT * FROM electors WHERE telephone = '$telephone' $criteria"); $results = '';
  return mysql_fetch_array($the_others);
} 

then there is no need to explode the output of the function.

2 Comments

Something's wrong as its getting results for a lot more than just the ID column
use SELECT ID ... rather than SELECT * ... if you just want the ID column.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.