如何使用php在查询中包含变量?

时间:2016-11-01 09:15:46

标签: php

<?php
$connect = mysqli_connect($hostname, $username, $password, $database);
$query = 'select stopname from greenline';
$result = mysqli_query($connect, $query);
?>
<html>
  <body>
    <form action="try.php" method="get">
      <?php
echo "<select name='myselect'>";

while ($row1 = mysqli_fetch_array($result)):;
    echo '<option value=" ' . $row1[0] . ' " name="row" >' . $row1[0] . '</option>';
endwhile;
echo "</select>";
?>
      <input type="submit" name="submit"/>
    </form>
    <?php

if (isset($_GET['submit']))
{
    $variable = $_GET['myselect'];
    $query1 = 'select placeno from greenline where stopname = " ' . $variable . '"';
    $result1 = mysqli_query($connect, $query1) or die(mysql_error());
    $row2 = mysqli_fetch_assoc($result1);
    echo "success";
    $var = $row2['placeno'];
    echo " this is $var";
} ?>
  </body>
</html>

我已经在sublime中完成了以上..它不是在我们的查询中提取变量值。请你给出一个解决方案.. $ var没有显示

2 个答案:

答案 0 :(得分:0)

;之后你while。这使得你的循环基本上是无操作。

同时在同一位置删除:

答案 1 :(得分:0)

查询中有一个额外的空格:

$query1='select placeno from greenline where stopname = " '.$variable.'"';
                                                         ^

删除该空格,它将起作用。

但如果你使用一个替换变量的预备语句instad会更好。

$stmt = mysqli_prepare($connect, 'select placeno from greenline where stopname = ?');
mysqli_stmt_bind_param($stmt, "s", $variable);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $placeno);
mysqli_stmt_fetch($stmt);
echo "this is $placeno";

您还在html中添加了额外的空格:

echo '<option value=" ' . $row1[0] . ' " name="row" >' . $row1[0] . '</option>';
                     ^                ^

也摆脱这些空间。