显示具有公共字段的组合行

时间:2016-03-23 10:39:27

标签: php mysql

所以,我有一个包含我们产品的非常大的数据库,每个产品都有几种不同的变体。表格的结构如下:

id  |  Name  |  VariantName  |  dim1
 1  |  Smth  |  SmthCool     |  120
 2  |  Smth  |  SmthHot      |  160
 3  |  Smth  |  SmthRed      |  320
 4  |  Othr  |  OthrCool     |  220
 5  |  Othr  |  OthrBlue     |  128

等...

现在,我希望能够根据Name字段获取数据,以便输出类似于:

Name: Smth
Variant 1: SmthCool  Dimensions: 120
Variant 2: SmthHot   Dimensions: 160
Variant 3: SmthRed   Dimensions: 320

我目前找到了一个根据Name值输出所有条目的代码,但我需要将它们组合起来,如上所示。

<?php
$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id, Name, VariantName, dim1
        FROM products
        WHERE VariantName="something"';

mysql_select_db('test');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
    echo "ID :{$row['id']}  <br> ".
     "Name: {$row['Name']} <br> ".
     "Variant name: {$row['VariantName']} <br> ".
     "Dimensions: {$row['dim1']} <br> ".
     "--------------------------------<br>";
} 
echo "Fetched data successfully\n";
mysql_close($conn);
?>

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

首先,请不要使用自PHP 5.5以来已弃用的mysql函数,并完全从PHP 7中删除。请改用PDOmysqli

话虽如此,您试图从数据库中获取与名称名称对应的行,因此您的语句应如下所示:

$name="Smth";
$sql = "SELECT id, Name, VariantName, dim1
       FROM products
       WHERE Name=".$name;

您也可以使用prepared statements执行上述操作。

就在循环之前:

echo "Name = ".$name."<br>";
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
    echo "Variant {$row['id']}: {$row['VariantName']}  Dimensions: {$row['dim1']};
}

答案 1 :(得分:0)

Dunno为什么用mysqli标记,但是因为你必须退出使用mysql_ *函数,这里是使用one the best features of PDO的解决方案:

$dbhost = 'localhost';
$dbuser = 'user';
$dbname = 'test';
$dbpass = '';
$dbcharset = 'utf8';

$dsn = "mysql:host=$dbhost;dbname=$dbname;charset=$dbcharset";
$opt = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new PDO($dsn, $dbuser, $dbpass, $opt);

$sql = 'SELECT Name, id, VariantName, dim1 FROM products WHERE VariantName=?';
$stmt = $pdo->prepare($sql);
$stmt->execute(["something"]);
$data = $stmt->fetchAll(PDO::FETCH_GROUP); 

并且在$data变量中,您将有一个按名称分组的嵌套数组

<? foreach($data as $name => $products): ?>
    Name: <?=$name?><br>
    <? foreach($products as $row): ?>
        Variant <?=$row['id']?>: <?=$row['VariantName']?>  Dimensions: <?=$row['dim']?>
    <? endforeach ?>
<? endforeach ?>