0

I'm trying to link the MySQL while loop into foreach loop using something like this :

if($something == true){
  foreach($array as $arr){
} else {
  while($row = mysql_fetch_array($mysql_query)){
}
  // loop instructions
}

It looks so wrong, I know but you see what I am trying to do ?.. I want to grab data from array if $something was true, else then grab data from database

I had another solution idea and its to manually match the array with how $mysql_query works so I can use them both with while only, something like this :

if($something == true){
  $mysql_query = array("username" => "$_GET['username']", "password" => "$_GET['password']");
} else {
  $mysql_query = mysql_query("SELECT * FROM users WHERE usern......");
}

while($row = mysql_fetch_array($mysql_query)){
...

That's a second way to do it but it looks wrong as well because the first array is normal, I want to match that normal array with how mysql_query builds it so it can fit with the while loop

P.S. : I DO NOT want to repeat writing the loop instructions, I want them both to work with only one like I mentioned above

5
  • Replace if/else with if(!$something) { $array = /* collect all results from MySQL */; }. After that, you'll be able to use foreach ($array as $arr) { for both cases. As an aside, stop using mysql_ functions and switch to mysqli/PDO instead. Commented Dec 26, 2012 at 14:07
  • It would appear that $array is a multi-dimensional array. Is that right, and is it exactly a 2-dimensional array? Are there multiple rows in the results set? Commented Dec 26, 2012 at 14:11
  • i guess collecting all results into one array will increase the huge process on PHP, let me see a way to collect them into an answer of yours though Commented Dec 26, 2012 at 14:11
  • Collecting all results into one array seems like a good idea to me. Using the WHERE and GROUP clauses thoughtfully can reduce the size of the results set. Commented Dec 26, 2012 at 14:21
  • Welcome to Stack Overflow! Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial. Commented Dec 26, 2012 at 15:48

5 Answers 5

2

Put your processing into a function:

function process_data($data) {
    // do stuff
}


if($something){
    foreach($array as $arr){
        process_data($arr);
    }
} else {
    while($row = mysql_fetch_array($mysql_query)){
        process_data($row);
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

There's no reason to even call the function twice when essentially you are dealing with an array in both cases. This will work fine, but is not the neatest solution.
@Dutchie432 yup that's what i am saying, i'm trying to find the easiest and less-code solution without repeating a single variable.. it's not that bad tho
It’s the most flexible. Consider a query that returns a million records. You will not want to assign them all into an array — a hugely expensive operation — just to get your code to look neater. You iterate over as many records as is necessary then you break. Keeping the while in there gives you the option of adding a conditional break.
Not really sure I can see any advantage of using a function. The fact remains that the programming will fetch exactly the same number of rows and process them exactly the same way if $something is not truthy.
Correct me if I’m wrong, but it seems that you’re making several assumptions. 1. You’re assuming that $array and mysql_fetch_array() would contain/return a similar number of records. 2. You’re assuming that mysql_fetch_array() returns a trivial number of records. 3. process_data() is a trivial, non-reusable piece of logic that can happily sit within a foreach block. I’d rather not make any of those assumptions.
0

You'd probably get a better answer if you expanded the scope of what you've explained a bit. Without knowing what the something is and what the data is, plus the ultimate objective then it's hard to tell what kind of structure you should be using.

It seems to me that you could achieve this by just using a function, if the code inside the loop is the same. Like this:

if($something == true)
{
    foreach($array as $arr)
    {
        doWork($arr);
    }
}
else
{
     while($row = mysql_fetch_array($mysql_query))
     {
         doWork($row);
     }
}

function doWork($arr)
{
 //...
}

Comments

0

The other answers here are fine, but you'd be better served just to make sure that $array is a valid array regardless of something ... How about

if (!something){
    $array = array();
    while($row=mysql_fetch_array($mysql_query)) {$array[] = $row;}
}

foreach($array as $arr){
   // do work
}

6 Comments

Correct me if i am wrong.. mysql_fetch_array only grabs one row data right ? there are about 32,000 out there that's why i said it will be a huge process to collect them all into one array then use another loop to do another big work
I was updating that as you commented. Good catch.
This should now accomplish what you want without repeating.
Note php.net/manual/en/function.mysql-fetch-array.php the default flag for this function is MYSQL_BOTH. The author might want duplicate data in the $row variable, but my guess is that would not be of any added value.
Each call to mysql_fetch_array() returns a record. Again, you don’t want to be sticking 32K records into an array.
|
-1

You cannot nest loop instructions inside a loop like this. You'll need to have two separate loops completely inside the IF statements.

if($something == true){
  foreach($array as $arr){
     // do work
  }
} else {
  while($row = mysql_fetch_array($mysql_query)){
    // do work
  }
}

11 Comments

Then, put your work inside a function and call the function inside the loop.
thats so complicated, cant it be done the second solution i mentioned ? how does mysql_query build its results into an array ?
Programming can be complicated. That's why we get paid the big bucks :-)
@user - this isn't really that complicated as far as programming is concerned. Pretty standard practice in fact.
This concept is simple, the solution is overly complicated.
|
-1

Maybe you could look at from this viewpoint. And take note that this code uses mysql_fetch_assoc() instead of mysql_fetch_array(). Try both functions and look at the resulting rows with var_dump(). You will see that mysql_fetch_array() has twice as much data. You may want that, but probably not.

if ($something !== true)
{
    $array = array();
    while($row = mysql_fetch_assoc($mysql_query_result_resource))
    {
        $array[] = $row;
    }
}
foreach($array as $arr)
{
    /* PROCESS */
}

7 Comments

And I agree with the other posts that indicate an end to MySQL. There shouldn't be new code written today that relies on deprecated features.
that's pretty huge process at PHP right ? collecting about 32k results into an array then do another REALLY big work, how bad would it hurt ?
So if your query returns a non-trivial number of records, then you’re going to store them all in memory when you may not even need them all?
In the example given about, the query appears to be matching values in the HTTP request $_GET when it says, SELECT * FROM users WHERE usern..... Without knowing what ... contains, I can't really advise you on how to optimize the query, but if you're expecting 32,000 rows in the results set you might want to reconsider SELECT * and instead SELECT only the columns you Must have. Be thoughtful about using WHERE and GROUP as well as ORDER and LIMIT clauses, too.
@paulgrav: I think you would only return 32,000 rows from a results set if you did not know how to get the rows you need. I can't think of much use for 32,000 rows in a web page ;-)
|

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.