Mysql Select,Where语法来回显许多表的结果

时间:2014-02-03 08:34:43

标签: php mysql select

我无法弄清楚以下语法出了什么问题。

$con = mysqli_connect("localhost","*****","*****");
$rank = 78;
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

mysqli_select_db($con,"******") or die ("no database"); 

$result = mysqli_query($con,"
SELECT first_name FROM table_1 WHERE reputation=$rank;
 SELECT first_name FROM table_2 WHERE reputation=$rank;
SELECT first_name FROM table_3 WHERE reputation=$rank;
SELECT first_name FROM table_4 WHERE reputation=$rank
");


while($row = mysqli_fetch_row($result)) {

echo "$row[0] ";

echo "$row[1] ";

echo "$row[2] ";

echo "$row[3] ";

}

我没有收到任何错误,也没有任何结果。我该如何解决这个错误?谢谢。

2 个答案:

答案 0 :(得分:0)

尝试执行UNION

SELECT `first_name` FROM `table_1` WHERE `reputation` = '$rank'
UNION
SELECT `first_name` FROM `table_2` WHERE `reputation` = '$rank'
UNION
SELECT `first_name` FROM `table_3` WHERE `reputation` = '$rank'
UNION
SELECT `first_name` FROM `table_4` WHERE `reputation` = '$rank'


if($result !== FALSE){
    while($row = mysqli_fetch_row($result)) {
        echo $row['first_name'];
    }
}else{#error}

答案 1 :(得分:0)

首先替换

$con = mysqli_connect("localhost","*****","*****");
$rank = 78;
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

mysqli_select_db($con,"******") or die ("no database"); 

。通过

$con = mysqli_connect(hostname,user,password,database);
$rank = 78;
if (mysqli_connect_errno($con))
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

现在要么使用UNION,要么使用多个查询或使用mysqli_multi_query

$sql = "SELECT first_name FROM table_1 WHERE reputation='$rank';";
$sql .= "SELECT first_name FROM table_2 WHERE reputation='$rank';";
$sql .= "SELECT first_name FROM table_3 WHERE reputation='$rank';";
$sql .= "SELECT first_name FROM table_4 WHERE reputation='$rank'";


if (mysqli_multi_query($con,$sql))
{
  do
    {

    if ($result=mysqli_store_result($con))
      {
      while ($row=mysqli_fetch_row($result))
        {
        printf("%s\n",$row[0]);
        }
      mysqli_free_result($con);
      }
    }
  while (mysqli_next_result($con));
}