MySQL加入和回声结果

时间:2014-09-15 14:45:29

标签: php mysql join mysqli echo

我试图做一个简单的JOIN,当我尝试加载页面时,它是空白的。当我输入查询。我试图让它打印查询。我知道如何打印结果但是打印连接时遇到问题。

SELECT user.name, course.name
    FROM `user`
    INNER JOIN `course` on user.course = course.id;

在PHPmyAdmin上的SQL中返回

NAME        Course
Alice       HTML5
Bob         HTML5
Caroline    CSS3

<?php
$con=mysqli_connect("URL,"USERNAME","PASS","DB");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT user.name, course.name
FROM `user`
INNER JOIN `course` on user.course = course.id;");

while($row = mysqli_fetch_array($result)) {
  echo $row['user.name'] . " " . $row['course.name'];
  echo "<br>";
}

mysqli_close($con);
?>

感谢您的任何见解...

1 个答案:

答案 0 :(得分:3)

您不需要使用$row['user.name']它应该是$row['name'],但因为您有两列与name同名的列,所以您必须更改将它们分配给其他变量。

[提示]:检查新查询和while循环中的echo。 请进行以下更改:

 <?php
    $con=mysqli_connect("HOST","USERNAME","PASS","DB");
    // Check connection
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $result = mysqli_query($con,"SELECT user.name as username, course.name as coursename
    FROM `user`
    INNER JOIN `course` on user.course = course.id;");

    while($row = mysqli_fetch_array($result)) {
        echo $row['username'] . " " . $row['coursename'];
        echo "<br>";
    }

    mysqli_close($con);
?>