简体   繁体   中英

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.
Could anyone assist me?

First,you need use join to get the customername value

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 "*". 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.

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