繁体   English   中英

在php中重新加载页面时,如何从输入中获取值并将其添加到Sql语句中?

[英]How can i take value from input and add to Sql statement when page reload in php?

<div>
   <label>From</label>
   <input type=date name=from value="12-12-2017">
   <label>To</label>
   <input type=date name=to value="29-12-2017">
</div>


$query = $conn->prepare("SELECT * FROM Users WHERE age BETWEEN **From** and **To**")
$query->execute()

第一次重新加载页面时,如何从输入中获取值并添加到Sql语句中? 提前致谢

这是一个仅在第一次提交时工作的代码示例。

由于仅标记了PHP/MySQLi ,我们将举一个示例,在该示例中,用户在完成输入日期后必须按下按钮。

<?php
// session_start() has to be the first line of code
session_start();

$con = new mysqli($servername, $username, $password, $dbname);

// if there is NOT a valid POST request (means it is like a first visit)
if (!$_POST)
{
     // if the session variable is set unset it
     if(isset($_SESSION['beenHere'])) unset($_SESSION['beenHere']);

     echo 'Status: This is a fresh start.<br/>';
}
else if(isset($_POST['from']) && isset($_POST['to']) && 
   !empty($_POST['from']) && !empty($_POST['to']) && 
   !isset($_SESSION['beenHere']))
{
    // set the session variable to an arbitrary value, it's important it is set
    $_SESSION['beenHere'] = 'This is the first submit';
    // prepare the statement
    $stmt = $con->prepare("SELECT * FROM Users WHERE age > ? AND age < ?");
    // turn the input variables into proper date format and bind the to the ?
    // dates are considered strings in prepared statements
    $stmt->bind_param("ss", date('Y-m-d',strtotime($_POST['from'])), date('Y-m-d',strtotime($_POST['to'])));
    $stmt->execute();

    // Here you list all the output columns that you have. I only listed two example columns.
    $stmt->bind_result($name, $age);
    // loop for each returned row
    while ($stmt->fetch())
    {
        // print the results
        printf ("%s %s\n", $name, $age);
    }
}
?>

<!-- Leave the action empty to POST to self -->
<form action="" method="POST">
  <div>
     <label>From</label><input type="date" name="from" value="" />
     <label>To</label><input type="date" name="to" value="" />
  </div>
  <input type="submit" value="clickToEnter" />
</form>

注意:有关更高级的示例,您可以使用javascript/jQuery来设置会话变量客户端。 然后,您无需进行POST因为您可以在$_SESSION存储有价值的信息,并检查页面加载情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM