【问题标题】:Not able to pre populate data from database in a form无法在表单中预先填充数据库中的数据
【发布时间】:2016-04-13 16:17:42
【问题描述】:

无法找出问题所在。连接工作正常。我使用相同的 connection.php 文件来存储数据。但无法以不同的形式预先填充。请帮忙。 这是我写的代码:

<?php 
session_start();
if (!isset($_SESSION['email']))
    header('location: index.php');
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Welcome</title>
    </head>
    <body>
<form  action="app_script.php" method="POST">
<input class="form-control" placeholder="Name" name="name" required = "true" value="<?php require_once("connection.php"); $eventid = $_GET['ID'];$field = $_GET['Name'];$result = mysql_query("SELECT $field FROM `persons` WHERE `ID` = '$eventid' ");$row = mysql_fetch_array($result);echo $row[$field]; ?>">
<button type="submit" name="submit" class="btn btn-primary pull-right">Submit</button>
                </form>
</body>
</html>

【问题讨论】:

  • 哇哦,以前从未见过那个。输入value 中的查询。您收到的错误是什么? “无法预填充”没什么用处。
  • 表单中的字段为空。我希望从数据库中预先填充名称
  • 您可以将value 属性中的整个代码移动到页面上方的某个位置,然后将echo 移动到那里,看看您是否能够获得该值。可能没有什么不同,但现在很混乱而且容易出错。
  • 是的,您确实需要echo 您的查询才能看到格式正确,即。 $field 是您正在寻找的价值吗?等等。您的查询对 SQL 注入 (php.net/manual/en/security.database.sql-injection.php) 开放。您也需要对此进行调查。
  • 我试过单独写。它不工作。我在 php 部分有问题。现在我更具体地知道了这个问题。问题在于在“$eventid=$_GET['ID']”中获取当前用户 ID。有没有人知道如何获得它?

标签: php html mysql database forms


【解决方案1】:
 <?php 
   session_start();
    if (!isset($_SESSION['email']))
        header('location: index.php');

     require_once("connection.php");
     $eventid = $_GET['ID'];
     $field = $_GET['Name'];
     $result = mysql_query("SELECT $field FROM `persons` WHERE `ID` = '$eventid' ");
     if(mysql_num_rows($result)>0)
     {
     $row = mysql_fetch_array($result);
     $output =  $row[$field]; // to populate
     }
     else
     {
    $output ='';         
         }
     ?>

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>Welcome</title>
        </head>
        <body>
    <form  action="app_script.php" method="POST">
    <input class="form-control" placeholder="Name" name="name" required = "true" 
    value="<?php echo $output; ?>">
    <button type="submit" name="submit" class="btn btn-primary pull-right">Submit</button>
                    </form>
    </body>
    </html>

【讨论】:

  • 更改代码 $result = mysql_query("SELECT $field FROM persons WHERE ID = '$eventid' ") or die(mysql_error());您是否在 Query 中遇到任何错误?
  • stop using mysql_* functionsThese extensions 已在 PHP 7 中删除。了解PDOMySQLiprepared 语句并考虑使用 PDO,it's really pretty easy
  • 为什么 OP 应该尝试这个? 好的答案将始终解释所做的事情以及为什么以这种方式完成,不仅是为了 OP,也是为了 SO 的未来访问者。跨度>
  • @seguro 问题在于“$eventid=$_GET['ID']”。我想获取当前的用户 ID,但这不会给我当前的用户 ID。有没有人知道如何获取当前用户 ID?
猜你喜欢
  • 2021-06-30
  • 2019-05-02
  • 2013-03-08
  • 1970-01-01
  • 1970-01-01
  • 2012-08-14
  • 1970-01-01
  • 2011-03-06
  • 2014-10-01
相关资源
最近更新 更多