简体   繁体   中英

SQL query only display first result

the code below display the row 116 twice, it won't display row 118. Any idea how to solve this issue?

$data = mysql_query("SELECT * FROM item WHERE dcid IN('116','118')")
        or die(mysql_error()); 
$info = mysql_fetch_array($data); 

foreach ($info as $item) {
  echo($item); 
}

mysql_fetch_array only fetches a single row. Typically it is used in a while loop to cycle through all the results.

To continue your example above:

$data = mysql_query("SELECT * FROM item WHERE dcid IN('116','118')") or die(mysql_error()); 
while ($item = mysql_fetch_array($data)) {
    echo($item)
}

your query must be as:

$data = mysql_query("SELECT * FROM item WHERE dcid IN('116','118')") or die(mysql_error()); 
while ($item = mysql_fetch_array($data)) {
    echo $item['column_name1'];
}   echo $item['column_name2'];

mysql_fetch_array returns a single row in an array like this that contains both an associative array and a regular numeric-keyed result set of your row.

0=> column,
column=>column

Thats why it returns twice in foreach.Use it like this

mysql_fetch_array($result, MYSQL_ASSOC);

Also, if dcid is your key and it's autoincrementing ( ID for rows ) you can also use LIMIT 116,118.

For more info: http://php.about.com/od/mysqlcommands/g/Limit_sql.htm

use group by as this

$data =mysql_query("SELECT * FROM item WHERE dcid IN('116','118') group by dcid")
       or die(mysql_error());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM