Putting SQL while loop query inside a PHP function

1.1k Views Asked by At

There was a similar question on these site before but my varies a bit that I want to do a while loop inside the function(the other did not ask for that).

What I want to do is run different SELECT queries on different parts of my site, so to avoid repeating those similar versions of SELECT queries, i want to create a function that does that for me inside a functions.php file. So i am thinking of doing these on the functions.php file:

function imasde($level) { 
    /* $level is to select custom tables for different pages not just the same table */
    $value = "";    
    $sql = "SELECT * FROM labs WHERE level = $level";
    $resu = mysql_query($sql);
    $row = while( $fila=mysql_fetch_array($resu));
    $value = $row;
    return $value;
}

So on the HTML template i all put these code to use the function.

<?php echo imasde('Medium'); ?>
<div class="task medium"> /*It should loop the different values on the Selected tables not just one value */
    <div class="title"><?php echo $value["name"]; ?></div>
    <div class="date"><?php echo $value["category"]; ?></div>
</div>

Of course there is a bug on these cause it doesn't work, sorry if it sounds stupid query but i have lost practice on back end coding for a while, too use to WordPress little coding to be done with a premium theme and plugins...

If possible explain me a bit what I am doing wrong.

1

There are 1 best solutions below

2
On BEST ANSWER

Suggestion: Stop using mysql_* function as they deprecated (read more here)

instead, consider using mysqli_* functions or PDO

And for your question, you basically are keep setting the same value on the while. and then handle it as array which the $row aren't array to fix this, you can use it as an array like this:

function imasde($level)
{ 
    /* $level is to select custom tables for different pages not just the same table */
    $value = "";    
    $sql = "SELECT * FROM labs WHERE level = $level";
    $resu = mysql_query($sql);

    // Declare the rows array
    $rows = array();

    // Insert each row to the array
    while($row = mysql_fetch_array($resu))
        $rows[] = $row;

    // Return the array
    return $rows;
}

Then:

$rows = imasde('Medium');

foreach($rows as $row)
{
    echo '<div class="task medium">';
    echo '<div class="title">'. $row["name"] .'</div>';
    echo '<div class="date">'. $row["category"] .'</div>';
    echo '</div>';
}