【问题标题】:HTML form and PHP function to save form data to mysql in same file/pageHTML表单和PHP函数将表单数据保存到同一文件/页面中的mysql
【发布时间】:2013-11-26 23:40:50
【问题描述】:

我不会声称确切地知道我在做什么,因为我不知道,这可能很明显。我试图将表单和更新数据库的功能保留在同一个文件中。我做错了什么?

以下是重要的部分:

HTML:

<form id="billing" action="?updatebilling" method="post">

PHP:

<!-- Function to update billing -->
<?php 
function updatebilling() {
    // Connecting to the MySQL server
    $host="localhost";
    $user_name="root";
    $pwd="bluebox";
    $database_name="rewired";
    $db=mysql_connect($host, $user_name, $pwd) or die(mysql_error());
    if (mysql_error() > "") print mysql_error() . "<br>";
    mysql_select_db($database_name, $db);
    if (mysql_error() > "") print mysql_error() . "<br>";

    // Static info - account number
    $account_id=users::getAttr('Account', 'account_id');

    // Storing form values into PHP variables
    $zip = mysql_real_escape_string($_POST['billingzip']);
    $name = mysql_real_escape_string($_POST['name']);


    // Inserting variables into database
    $sql = "INSERT INTO `web_signup`
      SET `account_id` = '{$account_id}',
     `zip` = '{$billingzip}',
     `cardholder_name` = '{$name}',
     `updated_at` = NOW()";

    $result = mysql_query($sql) or die(mysql_error().$sql);

    mysql_close($db);

}   ?>

【问题讨论】:

  • 你遇到了什么错误?
  • 应该将您的数据库连接保持在单独的安全页面上。此外,您不能将其用作表单操作。应该是&lt;form id='billing' action='&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;' method='post'&gt;。如果您是游戏新手,请使用new mysqli() 和面向对象的 PHP。它会节省大量的击键!
  • 那么你是如何调用函数的呢?您遇到了哪些具体问题?
  • 这个函数如何访问静态的东西?

标签: php html mysql forms post


【解决方案1】:

您的&lt;form&gt; 标签很奇怪。

<form id="billing" action="?updatebilling" method="post">

这将重新加载同一页面,但?updatebilling 操作毫无意义。您需要检查页面顶部提交的内容并采取相应措施。许多人会检查submit 按钮,如果找到则跳转到处理代码。

if (!isset($_POST['submit'])) {
   // echo form here
} else {
   // process submitted data here.
}

您的action 然后可以留空或设置为指向带有action='&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;' 的页面文件名

【讨论】:

  • @PHPglue 哎呀!固定。
【解决方案2】:

我认为答案在这里可能有点明显。你是在提交后调用该函数吗?从我在您的代码中可以看到,您定义了一个 HTML 表单,并且您的代码定义了一个将数据保存到数据库的函数,但您实际上是在执行该函数吗?例如:

<?php
// function to save billing info
function updatebilling() { ... }

if (isset($_POST)) { // only call function when a post request is being processed
  updatebilling(); // execute function to save the billing info
}
?>
<form action="?updatebilling" method="post">
  <!-- your inputs here -->
  <input type="submit"/>
</form>

【讨论】:

    猜你喜欢
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    相关资源
    最近更新 更多