【问题标题】:How to join two table to retrieve rows from them and print it in within 1 div?如何连接两个表以从中检索行并将其打印在 1 div 内?
【发布时间】:2013-11-01 09:11:09
【问题描述】:

我已成功从一张表中提取所有必填字段 ['hotel' 是我的表名]。 另外,我想同时从另一个表中提取一些字段 ['rates' 是另一个表名]。我该怎么做?

这是我的表“酒店”的工作代码:

<!--deal-->
<?php 
$mysqli = new mysqli('localhost', 'root', '', 'swaminarayan');
if ($result = $mysqli->query("SELECT * FROM hotel")) {
$directory = "../administrator/images/hotels/";
while ($row = $result->fetch_assoc()) 
{?
<article class="one-fourth">
<figure>
<?php 
$search_dir = "$directory/{$row['name']}{$row['hotel_address']}";
$images = glob("$search_dir/*.jpg");
sort($images);
//display images
//display random image
if (count($images) > 0) { // make sure at least one image exists
// Get a random index in the array with rand(min, max) which is inclusive
    $randomImageIndex = rand(0, count($images)-1);
    $img = $images[$randomImageIndex]; // random image
    echo "<img src='$img' height='150' width='150' /> ";
}else {
// possibly display a placeholder image?
} ?
</figure>
<div class="details">
<h1><?php echo " ".$row['name']." ";?>
</h1>
<span class="price">Price per room per night from  <em>$<?php echo " ".$row['defult_price']." ";?></em> </span> // This defult_price is not from table 'hotel', it is from table 'rates' 
<div class="description">
<p><?php echo " ".$row['hotel_description']." ";?> <a href="<?php echo "".$row['hotel_address']."";?>.php">More info</a></p>
</div>
<a href="booking-step1.php" title="Book now" class="gradient-button">Book now</a>
</div>
</article><?php }}?>
<!--//deal-->

在上面,我想从“rates”表中提取房价字段并在此处显示{如这里:[&lt;span class="price"&gt;Price per room per night from &lt;em&gt;$&lt;?php echo " ".$row['default_price']." ";?&gt;&lt;/em&gt; &lt;/span&gt; }],这只是“rates”表中的值,否则全部来自“hotel”表。

【问题讨论】:

  • 呃,SQL 查询中没有 JOIN 部分,所以实际上 $row 中应该没有表 'hotel' 中的数据。由于我不知道您的表结构,我很难判断哪个是正确的 JOIN。
  • 我有两张桌子:'hotel' 和 'rates'。 'hotel'表有以下字段:hotel_id city_id country_id name photo1 photo2 photo3 photo4 photo5 hotel_address phone1 phone2 phone3 phone4 contact_email room_description area_description travel_description food_description rates_added 和,'rates'表有以下字段:id hotel_id room_type default_price price_monday price_tuesday price_wednesday price_thursday price_friday price_saturday price_sunday
  • 呃,嗯,应该类似于“SELECT * FROM hotel AS h INNER JOIN rates AS r ON r.hotel_id = h.hotel_id”。
  • 谢谢杜克林,效果很好。非常感谢您的帮助。

标签: php sql join mysqli


【解决方案1】:

请使用此查询

 Select h.*,r.default_price from hotel h left join rates r ON h.hotel_id=r.hotel_id

  or

 Select hotels.*,rates.default_price from hotel  left join rates  ON rates.hotel_id=hotel.hotel_id   

谢谢

【讨论】:

  • 感谢 ebiztrait。 Dukeling 的代码已经运行良好,但您的代码也运行良好。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2022-08-18
  • 2018-07-29
  • 2011-08-06
  • 2017-06-18
  • 2017-05-27
  • 1970-01-01
  • 2012-08-11
  • 2020-06-09
相关资源
最近更新 更多