我遇到的问题是使用PHP将SQL中的变量解析为另一个SQL语句

时间:2016-01-27 09:37:29

标签: php mysql

<?php

 if(isset($_POST['submitted'])){

//Connecting to the database

include('includes/connection.php');





// Creating variables to Post selected input item into database
$meeting_type = explode('|', $_POST['meeting_type']);
$date_picker = $_POST['date_picker'];

//$query = "SELECT * FROM meeting_tb WHERE meeting_type = '$meeting_type[1]'";
$query = "SELECT meeting_id, meeting_type, date FROM meeting_tb WHERE date in (select Max(date) as mindate from meeting_tb where meeting_type = '$meeting_type[1]')";



    $query_result = mysqli_query($db_con, $query) or die("error retrieving data");

    $row_meeting = mysqli_fetch_array($query_result, MYSQLI_ASSOC) or die("Not able to retrieve information");



$query_item = "SELECT join_tb.item_id, item_name, item_description FROM join_tb INNER JOIN meeting_item_tb ON join_tb.item_id = meeting_item_tb.item_id WHERE join_tb.meeting_id = '$row_meeting[meeting_id]'";

$result = mysqli_query($db_con, $query_item) or die("error retrieving data");

echo "<table>";
echo "<tr> <th>ITEM ID</th> <th>ITEM NAME</th>  <th>ITEM DESCRIPTION</th> </tr>";

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){

echo "<tr><td>";
echo $row['item_id'];
echo "</td><td>";
echo $row['item_name'];
echo "</td><td>";
echo $row['item_description'];
echo "</td></tr>";

}

echo "</table>";


}

//End of IF statement


?>

问题涉及在第二个选择语句中使用$row_meeting[meeting_id]。如果我使用数值代替$row_meeting[meeting_id],则select语句有效,并在浏览器上显示输出。但是如果我在第二个select语句中使用$row_meeting[meeting_id],它就不会从数据库中获取数据

2 个答案:

答案 0 :(得分:0)

通过在$row_meeting[meeting_id]周围放置单个引号,将数字解析为SQL时将其转换为字符串。为避免将其解析为字符串,您只需删除单个引号即可。所以你的select语句将如下所示:

$query_item = "SELECT join_tb.item_id, item_name, item_description FROM join_tb INNER JOIN meeting_item_tb ON join_tb.item_id = meeting_item_tb.item_id WHERE join_tb.meeting_id = $row_meeting['meeting_id']";

希望这有帮助。

答案 1 :(得分:-1)

在第二个查询中尝试此操作

$query_item = "SELECT join_tb.item_id, item_name, item_description FROM join_tb INNER JOIN meeting_item_tb ON join_tb.item_id = meeting_item_tb.item_id WHERE join_tb.meeting_id = ".$row_meeting[meeting_id].";";

这是可能的,因为变量周围有单引号。