1

i'm trying to get a group of random rows without repeat any of a BBDD, at the end, the code gies me the questions... but with some errors.... could anyone help me? P.D. the error is in the bolded line. (Undefined offset (in each iteration)) Thanks in advance

mysql_query('SET CHARACTER SET utf8');
$sql=mysql_query("SELECT * FROM Questions");
$num_rows = mysql_num_rows($sql);
$max_value = (int )$num_rows;
$ids[] = array(5);
for ($i = 0; $i < 5; $i++) {
    $repetido = true;

    while($repetido == true){
    $repetido = false;
    $quest_id = rand ( 1, $max_value);//Obtiene el aleatorio

    for ($j = 0; $j < count($ids); $j++) {
        **if ($quest_id == $ids[$i])  $repetido = true;**

    }

    }
    $ids[$i] = $quest_id;
    $sql=mysql_query("SELECT * FROM Questions WHERE id_quest = $quest_id");
    $row = mysql_fetch_array($sql);

    $output[$i]=$row;
}



    echo(json_encode($output));
mysql_close();
2
  • I see you're a C programmer transitioning to PHP Commented Apr 14, 2012 at 16:29
  • more or less :P i'm a student... in witch university only teach Java, SQL and C. ;) Commented Apr 14, 2012 at 16:30

3 Answers 3

1
$sql = mysql_query("SELECT DISTINCT * FROM Questions ORDER BY RAND() LIMIT 5");
$output = array();
for ($i = 0; $i < 5; $i++) {
    $output[] = mysql_fetch_array($sql);
}

echo(json_encode($output));
mysql_close();
Sign up to request clarification or add additional context in comments.

2 Comments

and in this code the "question" will NEVER repeat? (i mean... each time i invoke the php, the result will be diferent without any repeated question?)
Really dude, thank you so much... now i see why you said that i'm a C programmer. i were making it so difficult. Thnaks!! :)
1

First of all :

$ids[] = array(5);

Doesn't do what You think it does, it just creats array with one element with index 0 and value 5.

If You need just five random rows You can do it easly with MySql:

SELECT * FROM Questions ORDER BY RAND() LIMIT 5;

Comments

0

After:

$ids[] = array(5);

Add:

var_dump( $ids ); exit;

Use the @joeframbach solution

Comments

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.