py_script
py_script

Reputation: 831

MySQL returns weird results to PHP

I am working on a PHP application and I am trying to retrieve all the data from a table called articles to present them on screen. I have inserted the 2 sample entries, as below:

SQL result

Host: localhost
Database: samples
Generation Time: Oct 28, 2013 at 09:04 PM
Generated by: phpMyAdmin 4.0.8 / MySQL 5.5.30-log
SQL query: SELECT * FROM `articles` LIMIT 0, 30 ;
Rows: 2

article_id    article_title   article_content article_timestamp   
3 Sample title    Text    0
4 Title   Content 1234567

Here is the code that causes the error, with a small debugging print in there:

<?php
class Article {
    public function fetch_all() {
        global $pdo;
        $query = "Select * from articles";
        $result = mysql_query($query);
        $res_array = mysql_fetch_array($result);
        foreach ($res_array as $x) {
            echo $x;
            echo "............";
        }
    }
}?>

Instead of getting 2 entries, I get only the first 1...in double. To be more precise:

3............3............Sample title............Sample title............Text............Text............0............0............

I am not sure, what I am doing wrong in here. Can someone give a hint?

Upvotes: 0

Views: 204

Answers (3)

First of all, you call mysql_fetch_array only once, that's why you're getting only one row. You should call it in a loop until it returns fale value, meaning no more rows in a resultset.

Second, by default, mysql_fetch_array returns a bizzare hybrid of hash and array, an array indexed both by column numbers and column names, which explains why values are duplicated. You can pass MYSQL_NUM to get only values indexed by column numbers.

while ($res_array = mysql_fetch_array($result, MYSQL_NUM)) {
    foreach ($res_array as $x) {
        echo $x;
        echo "............";
    }
    echo "\n"; // ???
}

Upvotes: 1

MahanGM
MahanGM

Reputation: 2382

PHP Manual:

mysql_fetch_array(resource $result [, int $result_type = MYSQL_BOTH ])

Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).

So you should write this: mysql_fetch_array($result, MYSQL_ASSOC)

Upvotes: 0

ahwm
ahwm

Reputation: 692

This is what I've used in the past:

<?php
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
  foreach ($row as $x) {
    // ...
  }
}
?>

This retrieves each row in turn and loops through it to output the results.

Using mysql_fetch_assoc returns only an associative array, reducing the duplicate values in the array.

Upvotes: 3

Related Questions