1

Using select query am select some data from database.

i fetched data using while loop.

while($row=mysql_fetch_array($query1))
 {

}

now i want to print only index of $row.

i tried to print using following statements but it prints index and value(Key==>Value)

foreach ($row as $key => $value) {
    echo $key ;
}

and i tried array_keys() also bt it is also not helpful to me.

echo implode(array_keys($row));

please help to get out this.

i need to print only index.

4
  • What do u mean by index? Index of an array (in your case columns names) or maybe id of record? Commented Jan 13, 2014 at 14:15
  • i need to print key not value. Commented Jan 13, 2014 at 14:16
  • Are you using same $row in first and second loops? If yes - then you're overwriting it in first loop and then you'll get only 1 row in second Commented Jan 13, 2014 at 14:16
  • am using only one loop. Commented Jan 13, 2014 at 14:18

4 Answers 4

2

You are fetching the results row as both associative array and a numeric array (the default), see the manual on mysql_fetch_array.

If you need just the numeric array, use:

while($row=mysql_fetch_array($query1, MYSQL_NUM))

By the way, you should switch to PDO or mysqli as the mysql_* functions are deprecated.

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

1 Comment

Simple and best without additional Work :-)
0

You should pass separator(glue text) in Implode function.

For comma separated array keys, you can use below code.

echo implode(",",array_keys($row));

4 Comments

using above statement also it printing 0,sa,1,ff,2df like this but i need only key vales 0,1,2.
then what do you want to do?
The glue parameter is optional -- implode() can work without it.
@sandeep jeroen gave best best solution for your question.
0

The $row variable in your while loop gets overwritten on each iteration, so the foreach won't work as you expect it to.

Store each $row in an array, like so:

$arr = array();
while($row=mysql_fetch_array($query1)) {
    $arr[] = $row;
}

Now, to print the array keys, you can use a simple implode():

echo implode(', ', array_keys($arr));

Comments

0

$query1 from while($row=mysql_fetch_array($query1)) should be the result from

$query1 = mysql_result("SELECT * FROM table");
//then
while($row=mysql_fetch_array($query1))

To get only the keys use mysql_fetch_row

$query = "SELECT fields FROM table";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
  print_r(array_keys($row));
}

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.