Mysqli查询多个表

时间:2014-05-03 12:41:21

标签: php mysql sql mysqli

我尝试制作一个查询,然后根据以前的查询显示某些结果

这个想法是,当有人登录页面时,它会获取会话用户名并将其保存到可用状态,从那里第一个查询根据会话用户名选择一行,获取该值并在第二个查询,但在另一个表上,这次根据查询1和查询3的结果得到的行与2相同,然后它的意思是回应它

继承人的代码

$con = mysqli_connect("localhost","root","","boats4u");
$search = $_SESSION['myusername'];

if(mysqli_connect_errno())
{
    echo "Failed to connect to database". mysqli_connect_error();

}
$pre_res = mysqli_query($con,"SELECT ownerNo FROM boatowner WHERE email ='$search'");
$pre_res = $pre_res -> fetch_assoc();
$result = mysqli_query($con,"SELECT boatNo FROM boatforrent WHERE ownerNo ='$pre_res'");
$result = $result -> fetch_assoc();
$result2 = mysqli_query($con,"SELECT * FROM boatviewing WHERE boatNo = '$result'");

echo "<table border='1'>
<tr>
<th>Client No</th>
<th>Boat No</th>
<th>View Date</th>
<th>Comments</th>
</tr>";

while ($row = mysqli_fetch_array($result2)) 
{
    echo "<tr>";
    echo "<td>". $row['clientNo']."</td>";
    echo "<td>". $row['boatNo']."</td>";
    echo "<td>". $row['viewDate']."</td>";
    echo "<td>". $row['comment']."</td>";
}
echo "</table>";


?>

这就是显示

的内容
  

注意:数组转换为字符串   第29行的E:\ Download \ Xampp \ htdocs \ owner.php

如果我删除第一个查询,那么它没有错误,但显然搜索不起作用

任何帮助表示赞赏

2 个答案:

答案 0 :(得分:2)

您应该执行一个查询,并参数化 search 参数。类似的东西:

$stmt = $con->prepare('
   SELECT boatviewing.*       
   FROM boatowner owner
   LEFT JOIN boatforrent ON boatforrent.ownerNo = owner.ownerNo 
   LEFT JOIN boatviewing ON boatviewing.boatNo = boatforrent.boatNo
   WHERE owner.email = ?
');

$stmt->bind_param("s", $search);
$stmt->execute();
$result = $stmt->get_result();

此类代码通常对SQL注入更加强大,并且在您更改数据库布局时也更容易。

除此之外,您实际运行一个查询而不是三个查询,这允许数据库优化数据检索并保持PHP脚本和数据库服务器之间的往返低。

答案 1 :(得分:0)

试试这个..但你还是要说你可以加入那些表,这样你的查询会更简单,更快..

$pre_res = mysqli_query($con,"SELECT ownerNo FROM boatowner WHERE email ='$search'");
$pre_res = $pre_res -> fetch_assoc();
//$pre_res = ($pre_res)?$pre_res['ownerNo']:"some defaule_value" for exception if pre_res have empty data set then use it in query 
$result = mysqli_query($con,"SELECT boatNo FROM boatforrent WHERE ownerNo ='".$pre_res['ownerNo']."'");
$result = $result -> fetch_assoc();
$result2 = mysqli_query($con,"SELECT * FROM boatviewing WHERE boatNo = '".$result['boatNo']."'");