Results 1 to 5 of 5

Thread: get the index from mysql_fetch_array

  1. #1
    Join Date
    Jan 2008
    Posts
    441
    Thanks
    67
    Thanked 4 Times in 4 Posts

    Default get the index from mysql_fetch_array

    if i have a query that outputs with order
    Code:
    $query0 = mysql_query("SELECT name FROM mytable ORDER BY numVar");
    $result0 = mysql_query($query0);
    
    while ($row0 = mysql_fetch_array($result0)){
    	$name = $row0['name'];
    }
    if the result = g, b, r, c
    how can i find the index number of say 'r' ?
    is there a way of doing something like
    Code:
    foreach ($sub as $key => $value) {
    }
    Last edited by ggalan; 05-20-2012 at 11:19 PM.

  2. #2
    Join Date
    Apr 2012
    Location
    Chester, Cheshire
    Posts
    329
    Thanks
    7
    Thanked 35 Times in 35 Posts

    Default

    By "index", do you mean the index within the generated array, or the index of where it was originally positioned in the db (it's id)?

  3. #3
    Join Date
    Apr 2012
    Location
    Chester, Cheshire
    Posts
    329
    Thanks
    7
    Thanked 35 Times in 35 Posts

    Default

    For the former, try using array_search

    PHP Code:
    <?php
    $array 
    = array(=> 'blue'=> 'red'=> 'green'=> 'red');

    $key array_search('green'$array); // $key = 2;
    $key array_search('red'$array);   // $key = 1;
    ?>
    For the latter, you'll need to add the mytable_ID field to the SELECT statement, if you have one. If you don't have one then you'll have to create an AutoNumber field in the table. (For this, it's best to build a new table from scratch and repopulate it)

    PHP Code:
    <?php
    $query1 
    mysql_query("SELECT id, name FROM mytable ORDER BY name");
    ?>

  4. #4
    Join Date
    Jan 2008
    Posts
    441
    Thanks
    67
    Thanked 4 Times in 4 Posts

    Default

    i need to make a sql query within a query to look for a rows index within a subset
    i think pushing items into an array then use 'array_search' should do it
    thanks

  5. #5
    Join Date
    Apr 2012
    Location
    Chester, Cheshire
    Posts
    329
    Thanks
    7
    Thanked 35 Times in 35 Posts

    Default

    Quote Originally Posted by ggalan View Post
    i need to make a sql query within a query to look for a rows index within a subset
    That hurt my head just reading it!

    PHP Code:

    // mytable record field "names: ['d', 'b', 'a', c']"

    $sql "SELECT name FROM mytable ORDER BY name";
    $result mysql_query($sql); // ['a', 'b', 'c', d']

    $key array_search('a'mysql_fetch_array($result)); // $key = 2; 
    Maybe?
    Last edited by ApacheTech; 05-21-2012 at 02:53 AM.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •