1

i have tried $row[0] alone it works, but not $row[1]. It says like this "Notice: Undefined offset: 1 in C:\xampp\htdocs\t2.php on line 10"

   <?php
    $c=mysql_connect("localhost","root",""); 
//db connection
    mysql_select_db("niro");

    $re=mysql_query("select id from detail where grade >=80 ORDER BY RAND()");
//select who are all have above 80

        while($x=mysql_fetch_array($re, MYSQL_BOTH))
    {
    printf ("%s %s",$x[0],$x[1]."\n");
// i have multiple fields but it says undefined offset : 1.
    }
    ?>
3
  • print_r($x); inside the loop Commented Mar 3, 2016 at 3:43
  • 1
    try to select all instead of selecting an id column. Commented Mar 3, 2016 at 3:45
  • Gothca claudios :) but what do i do for selecting 2 rows with a single column Commented Mar 3, 2016 at 3:48

2 Answers 2

3

I guess the reason is you only have one field id in query result event if you may have mutlit field in your table. Because your sql is "select id from detail where grade >=80 ORDER BY RAND()".

You should use "select * from detail where grade >=80 ORDER BY RAND()" to get other fields in your table. And please make sure ORDER BY RAND() is what you want. It will select the data by rand order. If all you want is get all data which grade >= 80, no need to order it by random.

Update: The array index is the filed. If you only want to get and print the first 2 rows, you can use sql like: "select * from detail where grade >=80 limit 2"

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

4 Comments

Thanks melson, that works cool :), YES i do want RAND() function also.
So what do i do for both RAND() and LIMIT2 in a single query ??
"It simply works" $re=mysql_query("select id,name from detail where grade>=80 ORDER BY RAND() limit 2");
Congratulation. You got it.
2

You are getting undefined offset because you are selecting only one column in your select query try using select * or you can mention more column names.

i.e

$re=mysql_query("select * from detail where grade >=80 ORDER BY RAND()");

3 Comments

then you can't print x[1] because all the columns that you selected will be assigned as indexes to the row variable. either numeric indexes or text indexes i.e. x[0] or x['id'].
I want to select exactly 2 rows from that table, for that what do i do?
It completely depends on your select query and if you want to print both the row IDs at same time then you should save those in another Array and then print it out of while loop. because the while loop you are using allows you to iterate through rows. @AravindhGopi

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.