简体   繁体   English

显示名称而不是ID

[英]Display the name instead of the ID

Database setup: 数据库设置:

Table: customers 表:客户

id | name | address | zipcode | city | phone | email | active

Table: todo 表:待办事项

id | customerid | description | information | active


$sql = "
SELECT * 
  FROM todo
  ORDER 
    BY `customerid` ASC
     , `description` ASC
";

show results: 显示结果:

echo $row['customerid'] $row['description'] $row['information'];

output: 输出:

customerid description information

desired output: 所需的输出:

customername (from table customers) description information



I have been reading this forum and i find that i should use INNER JOIN but i can't get it to work. 我一直在阅读这个论坛,我发现我应该使用INNER JOIN,但我无法使其正常工作。
Could anyone assist me? 有人可以帮我吗?

First,you need use join to get the customername value 首先,您需要使用join来获取客户名值

SELECT t.description,t.information,c.name 
    FROM todo t JOIN customers c ON c.id=t.customerid 
ORDER BY `t.customerid` ASC, `description` ASC

Then try with below: 然后尝试以下方法:

echo $row['name'] $row['description'] $row['information'];

The thing is when you use "ORDER BY" you can't use the "*". 问题是,当您使用“ ORDER BY”时,不能使用“ *”。 Here is how your code should go: 这是代码的运行方式:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT customers.customerid,name, description, information FROM  customers INNER JOIN todo ON customers.customerid=todo.customerid ORDER 
BY customers.customerid ASC
 , description ASC";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "<br>". $row["name"]." ".$row["description"]. " " . $row["information"] . "<br>";
 }
 } else {
echo "0 results";
 }

 $conn->close();
 ?>

This should do it. 这应该做。

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

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