php和mysqli需要帮助

时间:2017-03-14 10:48:21

标签: php mysql sorting mysqli

我很简单,但我想知道如何用公司名称获取我的身份证。 我知道所有名字都出现但不是ID。我只获取列表中的最后一个ID 我该怎么办?

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$con=mysqli_connect("localhost","root","root","****");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }   

        // hent fra db: SELECT ... FROM tabell ORDER BY sted, brukernavn
$sql="SELECT * FROM fotograf ORDER BY sted, firma ";
$data = mysqli_query($con,$sql);
$sortedData = [];

// organiser 
foreach ($data as $d)
{
    $place = $d['sted'];
    $id = $d['id'];
    $sortedData[$place][] = $d['firma'];
}

// output
foreach ($sortedData as $place => $userNames)
{
    echo '<h3>' . $place . '</h3>';

    foreach ($userNames as $userName)
    {
        echo '<div><p><a href="fotograf.php?id='. $id .'"><strong>' . $userName . ' </strong></a></div>';
    }

}
?>

2 个答案:

答案 0 :(得分:0)

问题是你得到多行并将你的id存储在一个变量中,每个循环都会被覆盖。

我建议你创建一个类(如果你是以OO的方式)并将其添加到列表中

$sortedData = [];

class Fotograf {
    public $Id;
    public $Firma;
}

// organiser 
foreach ($data as $d)
{
    $obj = new Fotograf();
    $obj->Id = $d['id'];
    $obj->Firma = $d['firma'];
    $sortedData[$d['sted']][] = $obj;   
}

从那里你可以访问对象本身,现在将Id变量与Place变量一起使用。现在访问它:

// output
foreach ($sortedData as $place => $userNames)
{
    echo '<h3>' . $place . '</h3>';

    foreach ($userNames as $userName)
    {

        echo '<div><p><a href="fotograf.php?id='. $userName->Id .'"><strong>' . $userName->Firma . ' </strong></a></div>';
    }

}

答案 1 :(得分:0)

更新您的代码:

foreach ($data as $d)
{
 $place = $d['sted'];
 //$id = $d['id']; this is unused variable
 $sortedData[$place] = array("username" => $d['firma'],"id"=>$d['id']);
}

// output
foreach ($sortedData as $place => $userNames)
{
  echo '<h3>' . $place . '</h3>';

  foreach ($userNames as $userName)
  {
    echo '<div><p><a href="fotograf.php?id='. $userName["id"] .'"><strong>' . $userName["username"] . ' </strong></a></div>';
  }

}