首页 > 解决方案 > 无法将数据从网站添加到数据库

问题描述

我正在尝试将输入到我的网站的数据发送到我的数据库中的表中...网页加载,一切正常,但是当我点击“提交”时,页面重新加载并且实际上并没有输入到请求的表中. 我尝试了许多不同的编辑,但我无法弄清楚它为什么不起作用的原因。关于我在这里可能做错的任何想法?

{source}
<html>
<head>
<title>Carrier Search</title>
<style type="text/css">

table {
background-color: #FCF;
}

th {
width: 150px;
text-align: left;
}

hh {
width: 90px;
text-align: left;
}
</style>
</head>
<body>


<div align="left">
<div id="contact_form">
<form action="https://truckingboard.000webhostapp.com/testing/index.php/add-a-carrier" method="post">
<b>Carrier</b>: <input type="text" name="Carrier">

<p>

<fieldset>
<b>MC</b>: <input type="number" id="MC" name="MC"
placeholder="000000"
pattern="[0-9]{6}"
required />
<span class="validity"></span>

</fieldset>



<p>
<b>Contact</b>: <input type="text" name="contact">

<p>

<fieldset>
<b>Phone</b>: <input type="tel" id="phone" name="phone"
placeholder="123-456-7890"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
required />
<span class="validity"></span>

</fieldset>

<p>

<fieldset>
<b>Email</b>: <input type="email" placeholder="example@example.com"
size="35" multiple
title="Zero or more addresses, separated with ','" />

<p>
<b>Fax</b>: <input type="text" name="fax">

<p>
<input type="submit" name="Add Carrier">

</div>
</form>
</div> 

<?php

// connect to the database
//include('connect.php');
DEFINE ('DB_USER', 'id6524903_admin1') ;
DEFINE ('DB_PSWD', 'admin123') ;
DEFINE ('DB_HOST', 'localhost') ;
DEFINE ('DB_NAME', 'id6524903_truckboard') ;

$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);

if (isset($_POST['submit']))
{

$Carrier = $_POST['Carrier'];
$MC = $_POST['MC'];
$contact = $_POST['contact'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$fax = $_POST['fax'];

$sql= ("INSERT INTO carriers (Carrier, MC, contact, phone, email, fax) VALUES ('$Carrier','$MC','$contact','$phone','$email','$fax')");
$a=mysqli_query($sql);

if (!$a)
{
echo mysqli_error();
}
else
{
echo "New record added succesfully";
}

///mysqli_close($con);

}

?> 

</body>
</html>


{/source}

表定义:

 CREATE TABLE carriers ( 
    ID int(11) DEFAULT NULL,
    Carrier varchar(255) DEFAULT NULL,
    MC varchar(255) DEFAULT NULL,
    contact varchar(255) DEFAULT NULL,
    phone varchar(255) DEFAULT NULL,
    fax varchar(255) DEFAULT NULL,
    email varchar(255) DEFAULT NULL
)

标签: phphtmlsql

解决方案


发现问题及解决方法:

1)if (isset($_POST['submit']))不起作用,因为没有带有name="submit". 因此,将按钮更改为:

<input type="submit" id="submit" name="submit" value="Add Carrier">

2)$email = $_POST['email'];返回 NULL,因为您name="email"在电子邮件输入中没有。因此,将电子邮件输入更改为:

<input type="email" id="email" name="email"
         placeholder="example@example.com"
         size="35" multiple
         title="Zero or more addresses, separated with ','"  />

3) 发出如下警告:

警告:mysqli_query() 至少需要 2 个参数,1 个在第 103 行的 [path-to]/index.php 中给出

因此,将连接对象作为参数传递给函数:

$a = mysqli_query($dbcon, $sql);

4) 表中没有自动增量主键字段carriers。所以定义一个:

CREATE TABLE `carriers` (
    `ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
    [...],
    PRIMARY KEY (`ID`)
)

5)不幸的是,您的 html 代码是一团糟。你应该正确地改变它。例如,段落标签必须关闭。但它也不能在里面包含一个fieldset。其他示例:您的结束form标签未正确定位。等等。


工作代码:

<html>
    <head>
        <title>Carrier Search</title>
        <style type="text/css">
            table {
                background-color: #FCF;
            }

            th {
                width: 150px;
                text-align: left;
            }

            hh {
                width: 90px;
                text-align: left;
            }
        </style>
    </head>
    <body>

        <div align="left">
            <div id="contact_form">
                <form action="https://truckingboard.000webhostapp.com/testing/index.php/add-a-carrier" method="post">
                    <b>Carrier</b>: <input type="text" name="Carrier" />

                    <p>

                    <fieldset>
                        <b>MC</b>: <input type="number" id="MC" name="MC"
                                          placeholder="000000"
                                          pattern="[0-9]{6}"
                                          required />
                        <span class="validity"></span>

                    </fieldset>



                    <p>
                        <b>Contact</b>: <input type="text" name="contact">

                    <p>

                    <fieldset>
                        <b>Phone</b>: <input type="tel" id="phone" name="phone"
                                             placeholder="123-456-7890"
                                             pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
                                             required />
                        <span class="validity"></span>

                    </fieldset>

                    <p>

                    <fieldset>
                        <b>Email</b>: <input type="email" id="email" name="email"
                                             placeholder="example@example.com"
                                             size="35" multiple
                                             title="Zero or more addresses, separated with ','"
                                             />

                        <p>
                            <b>Fax</b>: <input type="text" name="fax" />

                        <p>
                            <input type="submit" id="submit" name="submit" value="Add Carrier">

                            </div>
                            </form>
                            </div>

                            <?php
                            // connect to the database
                            //include('connect.php');
                            DEFINE('DB_USER', 'id6524903_admin1');
                            DEFINE('DB_PSWD', 'admin123');
                            DEFINE('DB_HOST', 'localhost');
                            DEFINE('DB_NAME', 'id6524903_truckboard');

                            $dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);

                            if (isset($_POST['submit'])) {

                                $Carrier = $_POST['Carrier'];
                                $MC = $_POST['MC'];
                                $contact = $_POST['contact'];
                                $phone = $_POST['phone'];
                                $email = $_POST['email'];
                                $fax = $_POST['fax'];

                                $sql = ("INSERT INTO carriers (Carrier, MC, contact, phone, email, fax) VALUES ('$Carrier','$MC','$contact','$phone','$email','$fax')");
                                $a = mysqli_query($dbcon, $sql);

                                if (!$a) {
                                    echo mysqli_error();
                                } else {
                                    echo "New record added succesfully";
                                }

                                ///mysqli_close($con);
                            }
                            ?>

                            </body>
                            </html>

选择:

这就是我为您的页面编写代码的方式。

  • 我正在使用准备好的语句来避免任何mysql 注入
  • 我正在使用面向对象的mysqli。
  • 关于错误处理,你会注意到我没有做任何事情。您应该阅读这篇文章和这篇文章,以了解如何正确应用它。
  • 在“connection.php”中用你的更改我的数据库凭据。
  • 将 css 规则提取到单独的文件中。

表格页面:

<?php
require 'connection.php';

// Signalize that the record was not (yet) inserted.
$recordSaved = FALSE;

if (isset($_POST['submit'])) {
    $carrier = isset($_POST['carrier']) ? $_POST['carrier'] : NULL;
    $mc = isset($_POST['mc']) ? $_POST['mc'] : NULL;
    $contact = isset($_POST['contact']) ? $_POST['contact'] : NULL;
    $phone = isset($_POST['phone']) ? $_POST['phone'] : NULL;
    $email = isset($_POST['email']) ? $_POST['email'] : NULL;
    $fax = isset($_POST['fax']) ? $_POST['fax'] : NULL;

    // Validate the MC.
    if (!isset($mc) || empty($mc)) {
        $errors[] = 'Please provide the MC.';
    }

    // Validate the phone.
    if (!isset($phone) || empty($phone)) {
        $errors[] = 'Please provide the phone.';
    }

    // If no errors, insert the record.
    if (!isset($errors)) {
        /*
         * The SQL statement to be prepared. Notice the so-called markers,
         * e.g. the "?" signs. They will be replaced later with the
         * corresponding values when using mysqli_stmt::bind_param.
         *
         * @link http://php.net/manual/en/mysqli.prepare.php
         */
        $sql = 'INSERT INTO carriers (
                    Carrier,
                    MC,
                    contact,
                    phone,
                    email,
                    fax
                ) VALUES (
                    ?, ?, ?, ?, ?, ?
                )';

        /*
         * Prepare the SQL statement for execution - ONLY ONCE.
         *
         * @link http://php.net/manual/en/mysqli.prepare.php
         */
        $statement = $connection->prepare($sql);

        /*
         * Bind variables for the parameter markers (?) in the
         * SQL statement that was passed to prepare(). The first
         * argument of bind_param() is a string that contains one
         * or more characters which specify the types for the
         * corresponding bind variables.
         *
         * @link http://php.net/manual/en/mysqli-stmt.bind-param.php
         */
        $statement->bind_param('sissss', $carrier, $mc, $contact, $phone, $email, $fax);

        /*
         * Execute the prepared SQL statement.
         * When executed any parameter markers which exist will
         * automatically be replaced with the appropriate data.
         *
         * @link http://php.net/manual/en/mysqli-stmt.execute.php
         */
        $statement->execute();

        /*
         * Close the prepared statement. It also deallocates the statement handle.
         * If the statement has pending or unread results, it cancels them
         * so that the next query can be executed.
         *
         * @link http://php.net/manual/en/mysqli-stmt.close.php
         */
        $statement->close();

        /*
         * Close the previously opened database connection.
         * Not really needed, because the php engine closes all
         * connections when the php script finishes processing.
         *
         * @link http://php.net/manual/en/mysqli.close.php
         */
        $connection->close();

        // Signalize that the record was successfully inserted.
        $recordSaved = TRUE;

        // Reset all values so, that they are not shown in the form anymore upon saving.
        $carrier = $mc = $contact = $phone = $email = $fax = NULL;
    }
}
?>

<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Carrier Search</title>

        <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800" rel="stylesheet">
        <style type="text/css">
            body {
                margin: 0;
                padding: 20px;
                color: #000;
                font-family: "Open Sans", Verdana, Arial, sans-serif !important;
                font-size: 0.9375rem;
            }

            .form-container {
                padding: 30px;
                width: 50%;
                background-color: #f4f4f4;
            }

            .form-group {
                margin-bottom: 15px;
            }

            .form-group label {
                display: inline-block;
                min-width: 90px;
                font-weight: 400;
            }

            input[type="text"],
            input[type="number"],
            input[type="tel"],
            input[type="email"] {
                padding: 5px;
                width: 180px;
            }

            .messages div {
                margin-bottom: 20px;
            }

            .messages div {
                padding: 10px;
            }

            .success {
                color: #3c763d !important;
                border-color: #d6e9c6 !important;
                background-color: #dff0d8 !important;
            }

            .error {
                color: #a94442 !important;
                border-color: #ebccd1 !important;
                background-color: #f2dede !important;
            }

            button {
                padding: 7px 10px;
                color: #fff;
                font-size: 14px;
                border: none;
                background-color: #8daf15;
            }

            .advice {
                color: #bbb;
                font-size: 0.875rem;
            }

            sup {
                color: red;
            }
        </style>
    </head>
    <body>

        <h2>
            Demo
        </h2>

        <div class="form-container">
            <div class="messages">
                <?php
                if (isset($errors)) {
                    ?>
                    <div class="error">
                        <?php echo implode('<br/>', $errors); ?>
                    </div>
                    <?php
                } elseif ($recordSaved) {
                    ?>
                    <div class="success">
                        Your data was successfully saved.
                    </div>
                    <?php
                }
                ?>
            </div>

            <form id="contactForm" action="https://truckingboard.000webhostapp.com/testing/index.php/add-a-carrier" method="post">
                <div class="form-group">
                    <label for="carrier">Carrier:</label>
                    <input type="text" id="carrier" name="carrier" value="<?php echo isset($carrier) ? $carrier : ''; ?>" />
                </div>

                <div class="form-group">
                    <label for="mc">MC:</label>
                    <input type="number" id="mc" name="mc"
                           placeholder="000000"
                           pattern="[0-9]{6}"
                           required
                           value="<?php echo isset($mc) ? $mc : 0; ?>" />
                    <sup>*</sup>
                    <span class="advice">(max. 10)</span>
                    <span class="validity"></span>
                </div>

                <div class="form-group">
                    <label for="contact">Contact:</label>
                    <input type="text" id="contact" name="contact" value="<?php echo isset($contact) ? $contact : ''; ?>" />
                </div>

                <div class="form-group">
                    <label for="phone">Phone:</label>
                    <input type="tel" id="phone" name="phone"
                           placeholder="123-456-7890"
                           pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
                           required
                           value="<?php echo isset($phone) ? $phone : ''; ?>" />
                    <sup>*</sup>
                    <span class="validity"></span>
                </div>

                <div class="form-group">
                    <label for="email">Email:</label>
                    <input type="email" id="email" name="email"
                           placeholder="example@example.com"
                           size="35" multiple
                           title="Zero or more addresses, separated with ','"
                           value="<?php echo isset($email) ? $email : ''; ?>" />
                    <span class="validity"></span>
                </div>

                <div class="form-group">
                    <label for="fax">Fax:</label>
                    <input type="text" id="fax" name="fax" value="<?php echo isset($fax) ? $fax : ''; ?>" />
                    <span class="validity"></span>
                </div>

                <div class="form-group">
                    <label for="submit">&nbsp;</label>
                    <button type="submit" id="submit" name="submit" value="Add Carrier">
                        Add carrier
                    </button>
                </div>
            </form>
        </div>

    </body>
</html>

连接.php:

<?php

/*
 * This page contains the code for creating a mysqli connection instance.
 */

// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'tests');
define('USERNAME', 'root');
define('PASSWORD', 'root');

/*
 * Enable internal report functions. This enables the exception handling,
 * e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions
 * (mysqli_sql_exception).
 *
 * MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
 * MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings.
 *
 * @link http://php.net/manual/en/class.mysqli-driver.php
 * @link http://php.net/manual/en/mysqli-driver.report-mode.php
 * @link http://php.net/manual/en/mysqli.constants.php
 */
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/*
 * Create a new db connection.
 *
 * @see http://php.net/manual/en/mysqli.construct.php
 */
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);

表定义:

CREATE TABLE `carriers` (
  `ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `Carrier` varchar(255) DEFAULT NULL,
  `MC` varchar(255) DEFAULT NULL,
  `contact` varchar(255) DEFAULT NULL,
  `phone` varchar(255) DEFAULT NULL,
  `fax` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

推荐阅读