按下按钮时如何从mysql获取数据?

时间:2019-05-04 17:24:58

标签: php html mysql

单击按钮时,我试图从mysql随机获取数据,这是我的代码。

<?php
    $con=mysqli_connect("localhost","root","","school");
// Check connection
    if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT description From task ORDER BY RAND() LIMIT 2");
    echo "<p><strong>Question:</strong></p>";

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

    echo "<p>". $row['description'] ."</p>";

}

    mysqli_close($con);
?>

     <input type="button" value="Get Assignment" onclick="myfunc()">

</body>
</html>

我希望在我单击“获取分配”按钮时得到输出,它将显示随机问题,直到显示空框。

1 个答案:

答案 0 :(得分:0)

您应该将php代码包装到isset函数中,该函数将检查是否发送了数据,然后运行,否则不发送。

  

isset函数检查变量是否已设置且不为空

或者,您可以调用Ajax来添加点击数据。 here

<?php
    $con=mysqli_connect("localhost","root","","school");
// Check connection
    if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){
$result = mysqli_query($con,"SELECT description From task ORDER BY RAND() LIMIT 2");
    echo "<p><strong>Question:</strong></p>";

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

    echo "<p>". $row['description'] ."</p>";

}

    mysqli_close($con);
}
?>

     <input type="button" name="submit" value="Get Assignment" onclick="myfunc()">

</body>
</html>

修改修正了我的代码

您需要将输入按钮包装到一个表单中,该表单会将表单提交到页面本身

<form method="post" action="">
<input type="submit" name="submit" value="Get Assignment">
</form>