1

i hope to iterate the elements fetched from datebase
But the result looks very unexpected .
I found the code below print the $value and echo "<td id=".$key.$tag.">".$value."</td>";twice. Is there anything i misunderstood?

   function selectTable($table){
        $sql= "SELECT * FROM ".$table ;
         $result=mysql_query($sql)
                          or die(mysql_error());
        return $result;
  }

  $table = 'battery_con';
  $result = selectTable($table);
  unset($table);

 while($row = mysql_fetch_array($result)){
        ......
        foreach ($row as $key => $value) {
                  print $value; 
                  echo "<td id=".$key.$tag.">".$value."</td>";
                }       
        .....
    }
4
  • 1
    off topic, but just to warn you: the mysql_xxx() functions in PHP are deprecated. You should consider using a more modern library such as PDO for your DB code. Commented Jul 29, 2013 at 9:55
  • @Spudley I know it ,but still appreciate for your ideas Commented Jul 29, 2013 at 10:06
  • @Akam query updated. Thanks Commented Jul 29, 2013 at 10:10
  • @Anigel query updated Thanks Commented Jul 29, 2013 at 10:10

3 Answers 3

3

You are using mysql_fetch_array which by default returns an array with two elements per column (this is what the second (optional) paramter means: result_type = MYSQL_BOTH).

One is indexed with an integer representing the column index, one is indexed with the column name.

That's why you get two entries in your list. You would set the second parameter to MYSQL_ASSOC to get just one value per column.

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

Comments

3

Please use mysql_fetch_assoc() place of mysql_fetch_array() I hope it will help

2 Comments

@sonusindhhu can you explain why?
mysql_fetch_array return two index one is integer like and second is field name
1

In addition to @Andreas's answer by default mysql_fetch_array gives both associative and numeric indexes, if you don't want this you can limit it with the second parameter in your while loop:

$row = mysql_fetch_array($result, MYSQL_NUM); // numeric keys only
$row = mysql_fetch_array($result, MYSQL_ASSOC); // associative keys only

As previously mentioned by @sonusindhu you can also use mysql_fetch_row to only get numeric keys, or mysql_fetch_assoc to only get associative keys.

Update

The mysql_xxx() functions being deprecated you should consider using the mysqli_xxx() functions instead.

See the example 1 of the php manual for more details: http://php.net/manual/en/mysqli-result.fetch-array.php

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.