简体   繁体   English

如何在不重复php中显示值的情况下显示mysql数据库中的值

[英]how to show values from mysql database without repeating values in php

When Iam showing database value from table its just repeating them according to content. 当Iam从表中显示数据库值时,它只是根据内容重复它们。 First table which is content. 第一个表是内容。

 id | category_id  |  name
-----------------------------
 1  |     2        |  Jason
 2  |     1        |  Richard
 3  |     2        |  John

category table:- 类别表:-

 id | name
 ---------
  1 | Manager
  2 | Employee

I use query: 我使用查询:

$query=mysql_query("SELECT * FROM content");
while($row=mysql_fetch_array($query)){
                 $data[] = array('id'=> $row['id'],
                                'category_id' => $row['category_id'], 
                                'name' => $row['name']
                           );
            }
  for($i=0;$i<count($data);$i++){
     echo $data[$i]['category_id'];
     echo $data[$i]['name']."<br/>";
  }

  OUTPUT:-
  2 Jason 
  2 John
  1 Richard

But what i want is:- 但是我想要的是:

 OUTPUT:-
 2 Jason John
 1 Richard

Now when echo out the result it shows me category_id 2 times having category_id=2 with its 2 name but what i want is to show only category_id 1 times and its corresponding 2 name of category_id=2. 现在,当回显结果时,它向我显示category_id 2次,category_id = 2及其2个名称,但我要显示的仅是category_id 1次,其对应的2个名称,category_id = 2。 Please help. 请帮忙。

Try this approach, it worked for me: 试试这种方法,对我有用:

$query = mysql_query("SELECT COUNT(*), category_id, name, 

 GROUP_CONCAT(name separator ' ') as name FROM content  
 WHERE category_id=1 OR category_id=2 GROUP BY category_id 
 ORDER BY category_id DESC");

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

        echo $row['category_id'] . " " . $row['name'] . "<br>";

    }

Plus, just a quick note about mysql_* functions being deprecated. 另外,关于不推荐使用的mysql_*函数的简要说明。

Use mysqli with prepared statements , or PDO with prepared statements , they're much safer. mysqli与预处理语句一起使用,或将PDO与预处理语句一起使用它们会更安全。

Use this query: 使用此查询:

SELECT id, category_id, GROUP_CONCAT(name SEPARATOR ' ') AS name
FROM content
GROUP BY category_id

See here for some quick tutorials on how to use GROUP BY and GROUP_CONCAT: 有关如何使用GROUP BY和GROUP_CONCAT的一些快速教程,请参见此处:
w3schools.com / GROUP BY w3schools.com / GROUP BY
mysqltutorial.org / GROUP_CONCAT mysqltutorial.org / GROUP_CONCAT

You shouldn't be using mysql as it is deprecated so to help you along I've done this with PDO to show its not as daunting as you may think. 您不应该使用已弃用的mysql ,以便为您提供帮助,以帮助我完成PDO以显示其不像您想象的那样令人生畏。

PDO connection to database: PDO与数据库的连接:

try{
    $db = new PDO ('mysql:host=YourHost;dbname=YourDatabaseName', 'YourDatabaseUserName', 'YourDatabasePassword');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
    echo $e->getMessage();
    die();
}

The above connection uses aa try catch with a way of making any errors cleaner and easier to read by making use of the getMessage() function which removes a lot of the un needed info. 上面的连接使用了try catch ,并通过使用getMessage()函数来删除所有不必要的信息,从而使所有错误更清晰易读。

The query you're after in PDO: 您在PDO中执行的查询:

$sql = "SELECT GROUP_CONCAT(name SEPARATOR ' ') AS names FROM yourtable GROUP BY category_id";
$query = $db->query($sql);
$results = $query->fetchAll(PDO::FETCH_OBJ);

foreach($results as $result){
    echo "<pre>", ($result->names), "</pre>";
}

This is the most basic way to use PDO to query your database but if you start using it like this you will find it easier to then develop the more in depth and secure ways of putting data in and getting data out of your database that help to prevent sql injection. 这是使用PDO查询数据库的最基本方法,但是,如果您像这样开始使用它,您会发现,更容易开发出更深入,更安全的数据放入和取出数据库的方法,这些方法有助于防止SQL注入。

Hope this is a little food for thought and helps in getting you to move to a more secure API. 希望这能为您带来一点思考,并有助于您转向更安全的API。

try this 尝试这个

select DISTINCT(*) from content or you can be more specific with ie DISTINCT(columnname) select DISTINCT(*) from content也可以使用DISTINCT(columnname)来更具体

<?php

// Using MySQL GROUP_CONCAT

$sql = 'SELECT category_id, GROUP_CONCAT(name separator \' \') FROM content GROUP BY category_id';


// Or PHP reduce as below
// Dummy Records
$records = [
    ['id' => 1, 'category_id' => 2, 'name' => 'Jason'],
    ['id' => 2, 'category_id' => 1, 'name' => 'Richard'],
    ['id' => 3, 'category_id' => 2, 'name' => 'John']
];

$result = array_reduce($records, function($carry, $record) {
    if (!array_key_exists($record['category_id'], $carry)) {
        $carry[$record['category_id']] = [];
    }

    $carry[$record['category_id']][] = $record['name'];

    return $carry;
}, []);

foreach ($result as $categoryId => $names) {
    echo $categoryId . ' ' . implode(' ', $names) . "\n";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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