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

Rar*_*owe 2 php mysql database xampp phpmyadmin

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

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

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

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

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

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

**

我的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>
Run Code Online (Sandbox Code Playgroud)

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';
?>
Run Code Online (Sandbox Code Playgroud)

**

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());
}
?>
Run Code Online (Sandbox Code Playgroud)

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';
?>
Run Code Online (Sandbox Code Playgroud)

小智 7

如果这只是学校作业,而你不需要担心安全性和现实世界的问题,那么单个文件就可以了.

  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. 让编辑链接,使用param定位你的process.php文件,例如process.php?id = 1,等等,id param应该引用数据库中的行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. 玩你编码,这是最好的学习方式:)

如果这是用于生产,或者您想要做正确的事情,请使用$ pdo-> quote,以确保您没有向您的数据库传递错误.

编辑:

你走在正确的轨道上,现在将它结合起来.查看以下代码(您可能需要调试它,尚未测试)

<?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>
Run Code Online (Sandbox Code Playgroud)