本文介绍了提交表单。使用php将信息存储在数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的PHP和有一个任务,我必须做一个html表单,这是罚款。我需要将数据提交到数据库并存储在表中。此表应允许用户查看表中的编辑和删除条目。

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.

我没有要求任何代码,或者有人为我做这样的事情,我想自己学习这门语言。如果有人可以简单地描述所需的步骤,我会非常感谢。

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?

目前我有一个简单的html表单,它链接到一个名为process.php

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.

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

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.

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

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

EDIT
我将在下面发布我的代码,请原谅我,因为我很新。

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

**

**

<!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


$ b b

process.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';
?>

**

**

<?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



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';
?>


推荐答案

如果这只是学校作业,

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. 执行IF语句和检查如果数据被提交(你可以查看$ _POST变量),
    使用isset()和strlen()函数来确保数据在数组中

  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

使用PHP PDO对象连接并与数据库进行通信,请参见,请参阅示例和注释

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

如果提交了数据,可以用$ pdo-> query('insert ...');
保存它们您还需要学习一些基本的SQL,检查

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

从数据库中获取所有数据,并将其显示在一个表格中,并带有编辑链接。

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

让编辑链接,使用一个参数来定位您的process.php文件,例如process.php?id = 1等,id参数应该在您的process.php文件中引用数据库中的行ID(现在您知道您的行应该包含ID列)

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)

['id'] param,看看是否有id给出。如果有,使用$ pdo-> query(select ... where id = {$ _GET ['id']})来获取数据,检查和pdo php手册,了解如何使用它。

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.

如果有ID,请预先填写您的表单与数据,并在表单中添加额外的隐藏输入,其中包含要更新的行的ID。

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.

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

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

看看你的IF语句,安排他们在逻辑流程,你总是需要打开数据库连接,你总是需要检查$ _POST和$ _GET params,所以做那些事情之前IFs

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

请务必阅读php手册,并阅读评论。阅读MySql文档。

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.

以您代码的形式播放,这是最好的学习方式:)

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

如果这是为了生产,或者你想做正确的事情,使用$ pdo-> quote,以确保你不会传递错误给你数据库。

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.

编辑:

你是在正确的轨道,现在结合它。
查看下面的代码(您可能需要调试它,未测试)

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>

这篇关于提交表单。使用php将信息存储在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 23:17