Tompo
Tompo

Reputation: 17

Results from mySQL using php show twice

I am connecting to my SQL server getting information from it using the following code:

if ($_POST['searchdb']) {
$searchi="".$_POST['search'];
$query = "SELECT * FROM consume WHERE  type LIKE '%{$searchi}%' OR description LIKE '%{$searchi}%'";
if($result= mysqli_query($link, $query)) {
while ($row = mysqli_fetch_array($result)) {
    print_r($row);
      }
   } 
}

I have each value stored only once in my database but I get the following output:

Array
(
    [0] => RF Connector
    [Type] => RF Connector
    [1] => Male N Type Angle Cable Mtg.
    [Description] => Male N Type Angle Cable Mtg.
    [2] => Carousel
    [Location] => Carousel
    [3] => 2
    [Drawer] => 2
    [4] => Test
    [Supplier] => Test
    [5] => 12345678
    [Order Code] => 12345678
    [6] => 1
    [id] => 1
)

Why does the data seem to appear twice? Or is this normal?

Upvotes: 0

Views: 362

Answers (4)

Vodzo
Vodzo

Reputation: 1

Yes, it is normal when using mysqli_fetch_array

Replace it with mysqli_fetch_assoc and you will get associative array which contains data only once or use mysqli_fetch_row to get enumerated array which also contains data only once.

source: http://php.net/manual/en/function.mysql-fetch-assoc.php http://php.net/manual/en/function.mysql-fetch-row.php

Upvotes: 0

Syed mohamed aladeen
Syed mohamed aladeen

Reputation: 6755

this is because you used while mysqli_fetch_array($result)

                                    ^^^^^

it will give you both object and associative

use while mysqli_fetch_assoc($result)

you will get associative values

Upvotes: 0

Jason Spicer
Jason Spicer

Reputation: 239

Because you're using mysqli_fetch_array which puts two copies of the data into the result, once using the column number (starting from the left most column, numbered as 0) and once using the column's name.

You might find using mysqli_fetch_assoc instead of mysqli_fetch_array to be more useful, you get one copy of the data and you get useful column names.

Upvotes: 1

Alex Andrei
Alex Andrei

Reputation: 7283

This is normal behaviour, see here http://php.net/manual/en/mysqli-result.fetch-array.php
If you want numeric indices use this
mysqli_fetch_array($result,MYSQLI_NUM);
and for associative indices use this
mysqli_fetch_array($result,MYSQLI_ASSOC);

If you don't pass any parameter you will get an array containing both.

Upvotes: 1

Related Questions