php 提交表格。使用php在数据库中存储信息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13181733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:55:34  来源:igfitidea点击:

Submitting a form. Using php to store information in a database

phpmysqldatabasephpmyadminxampp

提问by RarkMowe

I'm quite new to PHP and have an assignment where I have to make a html form, which is fine. I'm required to have the data submitted to a database and stored in a table. This table should allow the user to view edit and delete entries in the table.

我对 PHP 很陌生,并且有一个任务,我必须制作一个 html 表单,这很好。我需要将数据提交到数据库并存储在表中。此表应允许用户查看表中的编辑和删除条目。

I'm not asking for any code or for somebody to do this for me or anything like that, I want to learn the language myself. I would appreciate it greatly if somebody could just outline the steps required?

我不是要求任何代码或有人为我做这件事或类似的事情,我想自己学习这门语言。如果有人可以概述所需的步骤,我将不胜感激?

At the moment I have a simple html form, which is linked to a php document called process.php that echos the inputted values to the screen.

目前我有一个简单的 html 表单,它链接到一个名为 process.php 的 php 文档,该文档将输入的值回显到屏幕上。

I'm using xampp to create a local php server and using PhpMyAdmin I created a database called my_db and within it I created a table called userProfile.

我正在使用 xampp 创建一个本地 php 服务器,并使用 PhpMyAdmin 创建了一个名为 my_db 的数据库,并在其中创建了一个名为 userProfile 的表。

I know I have to create another php file that connects to the database but after that I'm completely stumped.

我知道我必须创建另一个连接到数据库的 php 文件,但在那之后我完全被难住了。

EDITI'll post my code below, please excuse it as I'm very new to this.

编辑我将在下面发布我的代码,请原谅,因为我对此很陌生。

**

**

My html form:

我的 html 表单:

**

**

<!Doctype html public>
<body>

Please fill out the following form:

<table border="1" cellpadding="10">

<td>
<h1> Games Console Survey </h1>
<form action="createProfile.php" method = "post"> 

First Name: <br /> <input type="text" name="firstname" /><br />
<br />

Surname: <br /> <input type="text" name="lastname" /> <br />

<br />

<u>Gender</u>: <br />
<br />

<input type="radio" name="gender" value="Male" /> Male<br />
<input type="radio" name="gender" value="Female" /> Female <br />

<br />

<u>I Have The Following:</u> <br />
<br />

<input type="checkbox" name="Console" value="Playstation 3" /> Playstation 3<br />
<input type="checkbox" name="Console" value="Xbox 360" />  Xbox 360 <br />
<input type="checkbox" name="Console" value="Wii" />  Wii <br />

<br />
<input type="submit" />
</form>

</form>

</td>
</table>

</body>

</html>

process.php

进程.php

<?php
echo "First Name: ".$_POST['firstname'];
?>

</br>

<?php
echo "Surname: ".$_POST['lastname'];
?>

</br>

<?php
echo "Gender: ".$_POST['gender'];
?>

</br>

<?php
echo "Console: ".$_POST['Console'];
?>

</br>


<?php
require_once 'Connection.php';
?>

**

**

Connection.php

连接.php

**

**

<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "my_db";
$dsn = "mysql:host=$host;dbname=$database";
try {
$conn = new PDO( $dsn, $username, $password );
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

//$conn = null;
}
catch (PDOException $e) {
$conn = null;
exit("Connection failed: " . $e->getMessage());
}
?>

createProfile.php

创建配置文件

<?php

$firstname = $_Post['firstname'];
$lastname = $_Post['lastname'];
$gender = $_Post['gender'];
$Console = $_Post['Console'];

try {
    $host = "localhost";
    $username = "root";
    $password = "";
    $database = "my_db";
    $dsn = "mysql:host=$host;dbname=$database";

    $conn = new PDO( $dsn, $username, $password );
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "INSERT INTO userprofile("
    . "firstname, lastname, sex, console" 
    . " ) VALUES (" 
    . "'" . $firstname . "',"
    . "'" . $lastname . "',"
    . "'" . $gender . "',"
    . "'" . $Console .")";

    $conn->query($sql);

    $sql = "SELECT * FROM userdata";
    $userdata = $conn-query($sql);
    echo '<table>';
    echo '<tr>';
    echo '<th>First Name</th>
          <th>Last Name</th>
          <th>Gender</th>
          <th>Console</th>';
    echo '<tr>';
    foreach ($userdata as $userdata) {
    echo '<tr>';
    echo '  <td>' . $userprofile['firstname'] . '</td>';
    echo '  <td>' . $userprofile['lastname'] . '</td>';
    echo '  <td>' . $userprofile['gender'] . '</td>';
    echo '  <td>' . $userprofile['Console'] . '</td>';
    echo '  </tr> ';
}

echo '</table>';

        $conn = null;
    }
    catch (PDOException $e) {
        $conn = null;
        exit("Connection failed: " . $e->getMessage());
    }
?>

<?php
require_once 'Connection.php';
?>

回答by PiotrN

If that is just school assignment, and You don't need to worry about security and real world problems with it, then single file will do.

如果这只是学校作业,并且您无需担心安全性和现实世界中的问题,那么单个文件就可以了。

  1. Do an IF statement and check if data is submitted (you can look at $_POST variable), use isset() and strlen() functions to make sure data is in the arrays

  2. Use PHP PDO object to connect and talk with database see http://www.php.net/manual/en/book.pdo.php, see the example and comments

  3. If there are data submitted, You can save them with $pdo->query('insert ...');, You will need to learn some basic SQL as well, check http://www.sqlcourse.com/insert.html

  4. at any case, fetch all the data from the database, and display them in a table, with "edit" link.

  5. Let the edit link, target your process.php file, with a param, for example process.php?id=1, ect., the id param should refer to the row id in the database (now You know your rows should have id column)

  6. in Your process.php file, look at the $_GET['id'] param, to see if there is id given. If there is, use $pdo->query("select ... where id = {$_GET['id']}") to fetch the data, check http://www.sqlcourse.com/select.html, and the pdo php manual on how to use it.

  7. if there was an ID, prepopulate Your form with the data, and add extra hidden input in the form, that will contain the ID of row to update.

  8. In process.php, if there is $_POST and it has an ID, update the row with $pdo->query('update ...').

  9. Look at Your IF statements, arrange them in logical flow, You will always need to open database connection, You will always need to check $_POST and $_GET params, so do those things before IFs

  10. Be sure to read the php manual, read the comments as well. Read the MySql docs. It takes time, but it's time well spent.

  11. Play as You code, that's the best way to learn :)

  1. 执行 IF 语句并检查数据是否已提交(您可以查看 $_POST 变量),使用 isset() 和 strlen() 函数确保数据在数组中

  2. 使用 PHP PDO 对象连接和与数据库对话见http://www.php.net/manual/en/book.pdo.php,见示例和注释

  3. 如果有数据提交,可以用$pdo->query('insert ...');保存,还需要学习一些基本的SQL,查看http://www.sqlcourse.com/insert。 html

  4. 无论如何,从数据库中获取所有数据,并将它们显示在带有“编辑”链接的表中。

  5. 让编辑链接,定位你的 process.php 文件,用一个参数,例如 process.php?id=1 等,id 参数应该指的是数据库中的行 id(现在你知道你的行应该有 id柱子)

  6. 在你的 process.php 文件中,查看 $_GET['id'] 参数,看看是否有给定的 id。如果有,使用 $pdo->query("select ... where id = {$_GET['id']}") 来获取数据,检查http://www.sqlcourse.com/select.html,以及关于如何使用它的 pdo php 手册。

  7. 如果有 ID,请使用数据预填充您的表单,并在表单中添加额外的隐藏输入,这将包含要更新的行的 ID。

  8. 在 process.php 中,如果有 $_POST 并且它有一个 ID,则使用 $pdo->query('update ...') 更新该行。

  9. 看看你的 IF 语句,按照逻辑流程排列它们,你总是需要打开数据库连接,你总是需要检查 $_POST 和 $_GET 参数,所以在 IF 之前做这些事情

  10. 一定要阅读php手册,阅读评论。阅读 MySql 文档。这需要时间,但时间是值得的。

  11. 边玩边玩,这是最好的学习方式:)

If this is for production, or You want to do things right, use $pdo->quote, to make sure You are not passing something wrong to Your database.

如果这是用于生产,或者您想正确地做事,请使用 $pdo->quote,以确保您没有将错误的内容传递给您的数据库。

EDIT:

编辑:

You are on the right track, now combine it. Look at the following code (You might need to debug it, haven't tested)

你在正确的轨道上,现在结合起来。看下面的代码(可能需要调试,没测试过)

<?php

$host = "localhost";
$username = "root";
$password = "";
$database = "my_db";
$dsn = "mysql:host=$host;dbname=$database";

TRY {
$conn = new PDO( $dsn, $username, $password );
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if (isset($_POST['submit'])) {
    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $gender = $_POST['gender'];
    $Console = $_POST['Console'];

    if (isset($_POST['id'])) {
        //update mode, we have both POST data and ID, update the record
        $id = $_POST['id'];

        $sql = "UPDATE userprofile SET"
            . "firstname=".$conn->quote($firstname)
            . ",lastname=".$conn->quote($lastname)
            . ",sex=".$conn->quote($gender)
            . ",console=".$conn->quote($Console)
            . " WHERE id = ".$conn->quote($id);
        $userdata = $conn->query($sql);
    } else {
        // insert mode, there is no ID, but there are data, insert them as new
        $sql = "INSERT INTO userprofile("
            . "firstname, lastname, sex, console"
            . " ) VALUES ("
            . $conn->quote($firstname).","
            . $conn->quote($lastname).","
            . $conn->quote($gender).","
            . $conn->quote($Console).")";
        $userdata = $conn->query($sql);
    }
} elseif (isset($_GET['id'])) {
    // edit mode, no POST data, but there is an ID param, prepopulate the form
    $userEditDataRows = $conn->query('SELECT * FROM userdata WHERE id ='.$conn->quote($_GET['id']));
    if (sizeof($userEditDataRows)>0) {
        $row = $userEditDataRows[0];
        $firstname = $row['firstname'];
        $lastname = $row['lastname'];
        $gender = $row['sex'];
        $Console = $row['console'];
        $id = $_GET['id'];
    }

} else {
    // set empty data
    $firstname = '';
    $lastname = '';
    $gender = '';
    $Console = '';
    $id = false;
}
    //build the table
    $sql = "SELECT * FROM userdata";
    $userdata = $conn->query($sql);
    $table = '<table>';
    $table .= '<tr>';
    $table .= '<th>First Name</th>
          <th>Last Name</th>
          <th>Gender</th>
          <th>Console</th>
          <th>Edit</th>';
    $table .= '</tr>';
    foreach ($userdata as $userdata) {
        $table .= '<tr>';
        $table .= '  <td>' . $userdata['firstname'] . '</td>';
        $table .= '  <td>' . $userdata['lastname'] . '</td>';
        $table .= '  <td>' . $userdata['gender'] . '</td>';
        $table .= '  <td>' . $userdata['Console'] . '</td>';
        $table .= '  <td><a href="/process.php?id='.$userdata['id'].'">Edit</a></td>';
        $table .= '  </tr> ';
    }

    $table .= '</table>';

} catch (PDOException $e) {
    exit("Connection failed: " . $e->getMessage());
}
?>

<!Doctype html public>
<html>        
<body>

Please fill out the following form:

<table border="1" cellpadding="10">

    <td>
        <h1> Games Console Survey </h1>
        <form action="createProfile.php" method = "post">

            First Name: <br /> <input type="text" name="firstname" value="<?php $firstname ?>" /><br />
            <br />

            Surname: <br /> <input type="text" name="lastname" value="<?php $lastname ?>" /> <br />

            <br />

            <u>Gender</u>: <br />
            <br />


            <input type="radio" name="gender" value="Male" <?php if($gender == 'Male') echo "checked=checked"; ?> /> Male<br />
            <input type="radio" name="gender" value="Female" <?php if($gender == 'Feale') echo "checked=checked"; ?>/> Female <br />

            <br />

            <u>I Have The Following:</u> <br />
            <br />

            <input type="checkbox" name="Console" value="Playstation 3" <?php if($Console == 'Playstation 3') echo "checked=checked"; ?> /> Playstation 3<br />
            <input type="checkbox" name="Console" value="Xbox 360" <?php if($Console == 'Xbox 360') echo "checked=checked"; ?> />  Xbox 360 <br />
            <input type="checkbox" name="Console" value="Wii" <?php if($Console == 'Wii') echo "checked=checked"; ?> />  Wii <br />

            <?php if($id !== false):?>
                <input type="hidden" name="id" value="<?php echo $id; ?>"/>            
            <?php endif; ?>            

            <br />
            <input type="submit" name="submit"/>
        </form>

    </td>
</table>

<h1>Current data:</h1>
<?PHP echo $table ?>
</body>

</html>

回答by nahid hasan

First, you have to design your html form.

首先,您必须设计您的 html 表单。

Second, you have to modify your table 'userProfile'.

其次,您必须修改表“userProfile”。

Third, change your input 'name' in html form exactly like the field name in table. such as:

第三,像表中的字段名称一样,以 html 形式更改您的输入“名称”。如:

 <form>
       Name:<input name="firstname" type="text">
 </form>

Here, "firstname" will be one of your fieldname in the table "userProfile"

在这里,“firstname”将是您在“userProfile”表中的字段名之一

回答by Thomas Vincent Blomberg

To outline the steps. I would create a database class in PHP to handle all database requests CRUD. For example: -SELECT -UPDATE -INSERT -DELETE -QUERY -OUTPUTQUERY

概述步骤。我会在 PHP 中创建一个数据库类来处理所有数据库请求 CRUD。例如: -SELECT -UPDATE -INSERT -DELETE -QUERY -OUTPUTQUERY

I would also create an additional class User to get and set all data related to the user.

我还将创建一个额外的类 User 来获取和设置与用户相关的所有数据。

You should be able to use these two classes to pretty much accomplish everything you want to do. Implement the classes in your current process.php page.

您应该能够使用这两个类来完成您想做的所有事情。在您当前的 process.php 页面中实现这些类。

Doing this will keep you organized and will also give you a lot of flexibility when it comes to adding to the project. For example if you are adding multiple pages that will all have access to editing the same table you want to use the same consistent code each time. This way if something breaks you are only going to one class.

这样做将使您井井有条,并且在添加到项目时也会为您提供很大的灵活性。例如,如果您要添加多个页面,这些页面都可以编辑同一个表格,您希望每次都使用相同的一致代码。这样,如果出现问题,您只能去上一节课。

I hope this helps. It is hard to explain without giving you the code.

我希望这有帮助。不给你代码就很难解释。

Here is a good resource: http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql/

这是一个很好的资源:http: //net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql/

回答by Matthemattics

Sure. First, you'll need to create a Database table. To keep things simple, make 1 column for each form field, plus one for a unique ID.

当然。首先,您需要创建一个数据库表。为简单起见,为每个表单字段创建 1 列,加上一个用于唯一 ID 的列。

DISCLAIMER: I'm keeping this basic, for clarity. So, security steps are omitted. Don't run this in a public / production environment, as it could compromise your web server!

免责声明:为了清楚起见,我保持这个基本原则。因此,省略了安全步骤。不要在公共/生产环境中运行它,因为它可能会危及您的 Web 服务器!

Steps to save data:

保存数据的步骤:

1) Establish connection w/ MySQL

1)与 MySQL 建立连接

2) String-build an INSERT INTO statement, using the proper sql syntax

2)使用正确的 sql 语法字符串构建 INSERT INTO 语句

3) Execute your SQL query

3)执行您的 SQL 查询

Steps to view data:

查看数据的步骤:

1) (same) Establish connection w/ MySQL

1)(相同)与MySQL建立连接

2) String-build a SELECT statement, using the proper sql syntax

2)使用正确的 sql 语法字符串构建 SELECT 语句

3) Execute your SQL query, loop over the results, & echo them to screen as you wish

3)执行您的 SQL 查询,遍历结果,并根据需要将它们回显到屏幕上

Steps to update data:

更新数据的步骤:

1) (same) Establish connection w/ MySQL

1)(相同)与MySQL建立连接

2) String-build an UPDATE statement, using the proper sql syntax, & feed it your POST data from the form submission

2)使用正确的 sql 语法字符串构建 UPDATE 语句,并将表单提交中的 POST 数据提供给它

(make sure you pass in the row ID as an input type=hidden, so you can pass the row id into the UPDATE statement)

(确保将行 ID 作为输入 type=hidden 传入,以便可以将行 ID 传递到 UPDATE 语句中)

3) Execute your SQL query

3)执行您的 SQL 查询

That's pretty much it!

差不多就是这样!

回答by 000

You are almost there..now it's just the last mile..the following steps would be

你快到了..现在只是最后一英里..以下步骤将是

  • Make connection to database
  • Check that connection was made successfully
  • Sanitize values that you get from your form
  • Insert those sanitized values into the databse table
  • Close your connection
  • 建立与数据库的连接
  • 检查连接是否成功
  • 清理您从表单中获得的值
  • 将这些清理过的值插入到数据库表中
  • 关闭连接

Please feel free to update in case i am missing something..

如果我遗漏了什么,请随时更新..

回答by david strachan

Before you start php mysql_ functions are [being deprecated. You are left with using either mysqli or PDO. You can use either but I would suggest PDO.

在你开始 php mysql_ 函数之前 [正在被弃用。您只能使用 mysqli 或 PDO。您可以使用任何一种,但我建议PDO

As process.phpalready echos the inputted values to the screen and created the database you are half way there.

由于process.php已经将输入的值回显到屏幕并创建了数据库,您已经完成了一半。