简体   繁体   中英

Not returning data from multiple tables (php/sql)

I am trying to return data from shoes table and types table. I have done an inner join on type_id. It is only returning data from the types table, I think it may have something to do with my if statement ?

Any help would be appreciated.

<!DOCTYPE HTML>
<html>
<head>
<title>Shoe Details</title>
<h1>Shoe Details</h1>
<a href="index.php">Search Engine</a>
<br> <br/>
<a href="design.php">Database Design and Implementation</a>
<br> <br/>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
</head>
<body>
<?php
try{

    $conn = new PDO( 
    'mysql:host=localhost;dbname=u1553758',  
    'u1553758', 
    '19apr96'
   );
} catch (PDOException $exception) {
    echo "Oh no, there was a problem" . $exception->getMessage();
}

 $shoesID=$_GET['id'];

       $stmt = $conn->prepare("SELECT shoes.name, shoes.description, shoes.price, types.typeOfShoe FROM shoes INNER JOIN types on types.types_id = shoes.type_id WHERE shoes.id = :id"); 

    $stmt->bindValue(':id',$shoesID);
    $stmt->execute();

    if ($types=$stmt->fetch()){
        echo "<h2>".$types['typeOfShoe']."</h2>";  

    }

    else { if ($shoes=$stmt->fetch()){
        echo "<h2>".$shoes['name']."</h2>";
        echo "<p>".$shoes['description']."</p>";
        echo "<p>".$shoes['price']."</p>";  

    }
         }



$conn=NULL;
?>

$stmt->fetch() should be called once (assuming you are expecting one row of data). The returned array will contain all data from both tables.

if ($shoedata=$stmt->fetch()){
    echo "<h2>".$shoedata['typeOfShoe']."</h2>";
    echo "<h2>".$shoedata['name']."</h2>";
    echo "<p>".$shoedata['description']."</p>";
    echo "<p>".$shoedata['price']."</p>";  
}

You're calling $stmt->fetch() twice. The first one returns the first row of results, the second one returns the second row of results. But your query only returns one row, so the second if fails and doesn't print anyting.

Call $stmt->fetch() once, and use the variable to print all the information.

if ($row = $stmt->fetch()) {
    echo "<h2>".$row['typeOfShoe']."</h2>";
    echo "<h2>".$row['name']."</h2>";
    echo "<p>".$row['description']."</p>";
    echo "<p>".$row['price']."</p>";  
}

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