Hans van de Put
Hans van de Put

Reputation: 3

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?

Upvotes: 0

Views: 134

Answers (2)

Ibrahim Abou Khalil
Ibrahim Abou Khalil

Reputation: 322

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.

Upvotes: 0

flyingfox
flyingfox

Reputation: 13506

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'];

Upvotes: 1

Related Questions