Mohammad Saberi
Mohammad Saberi

Reputation: 13166

Unexpected variable scope in PHP

I would like to show 3 random images from database in my website. Below is its code:

$query = mysql_query ("SELECT id,url FROM tbl_gallery2");
if (mysql_num_rows($query) >= 3) {
    $my_array = array();
    $last_array = array();
    while ($r = mysql_fetch_row($query)) {
        $my_array[] = $r[1];
    }

    function makernd () {
        $number = array_rand($my_array,1);
        if (in_array($number,$last_array)) {
            makernd();
        } else {
            $last_array[] = $number;
            return $number;
        }
    }

    for($i = 1 ; $i < 3 ; $i++) {
        $item = makernd();
        echo '<img src="./images/slider/'.$item.'.jpg" alt="" class="slider" />';
    }

}

But whenever I run this code, I get the error below:

Undefined variable: my_array in line ... // The first line of makernd() function.

But I expected $my_array to be an accessible array for this function.
What's the problem?

Upvotes: 1

Views: 77

Answers (1)

Steven Moseley
Steven Moseley

Reputation: 16325

To simply fix your problem, you should pass $my_array to makernd() as a parameter:

$query = mysql_query ("SELECT id,url FROM tbl_gallery2");
if (mysql_num_rows($query) >= 3) {
    $my_array = array();
    $last_array = array();
    while ($r = mysql_fetch_row($query)) {
        $my_array[] = $r[1];
    }

    function makernd ($my_array) {
        $number = array_rand($my_array,1);
        if (in_array($number,$last_array)) {
            makernd($my_array);
        } else {
            $last_array[] = $number;
            return $number;
        }
    }

    for($i = 1 ; $i < 3 ; $i++) {
        $item = makernd($my_array);
        echo '<img src="./images/slider/'.$item.'.jpg" alt="" class="slider" />';
    }

}

HOWEVER, I strongly suggest putting the randomization in MySQL, to

  1. Simplify your code
  2. Significantly improve the performance, and
  3. Eliminate excessive loops & recursion in PHP

Example:

$sql = "SELECT id,url 
        FROM tbl_gallery2 
        ORDER BY RAND() 
        LIMIT 3";
$query = mysql_query ($sql);
if (mysql_num_rows($query) >= 3) {
    while ($r = mysql_fetch_row($query)) {
        echo '<img src="./images/slider/' . $r[1] . '.jpg" alt="" class="slider" />';
    }
}

PS - I also suggest you update your code to use mysqli, as mysql is deprecated

PPS - I also suggest you look into mysqli_fetch_assoc so you can reference query results by name instead of index (e.g. $r['url'] instead of $r[1] - as if you ever change the order of your query, you will break references by index.

Upvotes: 3

Related Questions