如何填充表单以编辑现有数据

时间:2018-12-12 02:00:02

标签: php mysql forms session

代码已更新,以反映双引号与单引号。

我没有从mysql表中填充date_requested值,而是得到了以下内容。

Date  <input type="text" id="datepicker" name="date_requested" value="$date_requested"> <br/><br/>

此行将 $ date_requested 放置在文本框中。

我也尝试过

Date  <input type="text" id="datepicker" name="date_requested" value="<?php echo "$date_requested" ?>"/> <br/><br/>

此行在文本框中放置 php echo

任何方向都值得赞赏。这是代码的周围部分:

if($_SERVER['REQUEST_METHOD'] == "POST")
{
    mysql_connect("localhost", "root","") or die(mysql_error()); //Connect to server
    mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
    $query = mysql_query("Select * from time_off_requests Where time_off_key='$time_off_key'"); // SQL Query
    $date_requested = $_POST["date_requested"];
    $time_off_begin = $_POST["time_off_begin"];
    $time_off_end = $_POST["time_off_end"];//date
    $use_pto = $_POST["use_pto"];
    $user = $_SESSION["user"];
    $time_off_key = $_SESSION["time_off_key"];
    mysql_query("UPDATE time_off_requests SET date_requested='$date_requested', time_off_begin='$time_off_begin', time_off_end='$time_off_end', use_pto='$use_pto' WHERE time_off_key='$time_off_key'") ;
    header("location: home.php");
}
if($tok_exists)
    {
    Print '
    <form action="edit.php" method="POST">
        Date  <input type="text" id="datepicker" name="date_requested" value="<?php echo "$date_requested" ?>"/> <br/><br/>
        All Day  <input type="checkbox" name="all_day[]" value="no" /> <br/>
        Start Time  <input type="time"  id="timepicker" name="time_off_begin" /> <br/>
        End Time  <input type="time" id="timepicker2" name="time_off_end" /> <br/> <br/>
        Use PTO <Select name="use_pto">
        <option value="">Select</option>
        <option value="Yes">Yes</option>
        <option value="No">No</option>
        </select> <br/><br/>
       <input type ="submit" value="Edit Request">  
    </form>
    ';
    }
    else
    {
        Print '<h2 align="center">There is no data to be edited.</h2>';
    }
?>

1 个答案:

答案 0 :(得分:0)

您将单引号和双引号混合使用错误。将变量中的值设置为字符串的一种更简单的方法是使用变量插值,它需要使用双引号("")。

所以

Print "<form action='edit.php' method='POST'>
    Date  <input type='text' id='datepicker' name='date_requested' value='$date_requested'/> <br/><br/>
</form>";

确实会输出

<form action='edit.php' method='POST'>
    Date  <input type='text' id='datepicker' name='date_requested' value='2018-12-12'/> <br/><br/>
</form>

这是因为PHP在双引号中包含的普通字符串中看到变量$date_requested并将其替换为其值。变量周围的单引号将按字面意义进行解释,并输出为包含HTML属性值的引号