-1

I am trying to get the data inputted to my website sent into a table in my database... The webpage loads, everything works fine, but when I hit "SUBMIT", the page reloads and doesn't actually input into the table requested. I've tried many different edits and I can't figure out the reason to why it won't work. Any ideas on what I could be doing wrong here?

{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}

Table definition:

 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
)
PajuranCodes
  • 303
  • 3
  • 12
  • 43
Jordan S
  • 35
  • 5
  • 1
    `$a=mysqli_query($sql);` is a bug. You can't just add `i`s to the old `mysql_` functions. You also will be open to SQL injections with this code. The query should be parameterized. – user3783243 Jul 19 '18 at 21:35
  • That would work. Procedural requires connection link as parameter 1. – user3783243 Jul 19 '18 at 21:54
  • Still having the same issue after reworking that – Jordan S Jul 19 '18 at 22:00
  • Side note: you should put indentation in your code. It helps readability and makes it easier to spot useless markup. Ex. you have a couple `

    ` that are never closed with `

    `. If you add something to the question, put it in the question. The SQL statement you put in the comment is barely readable. In the question, you can format it as code.
    – Nic3500 Jul 19 '18 at 22:09
  • @JordanS I updated my answer with an alternative code. Good luck. – PajuranCodes Jul 20 '18 at 08:02

2 Answers2

-1
$a=mysqli_query($sql);

Add

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

And remove because the query doesn't pass in the if with:

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

My code for test :

    <?php

// connect to the database
//include('connect.php');
DEFINE ('DB_USER', 'root') ;
DEFINE ('DB_PSWD', 'testdb') ;
DEFINE ('DB_HOST', 'localhost') ;
DEFINE ('DB_NAME', 'stack') ;

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

//$dbcon = mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }




$sql= ("INSERT INTO test (name) VALUES ('testadd')");
$a=mysqli_query($sql);

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

///mysqli_close($con);



?> 
Max ime
  • 13
  • 3
-1

Found problems and solutions:

1) if (isset($_POST['submit'])) doesn't work, because there's no button with name="submit". So, change the button to:

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

2) $email = $_POST['email']; returns NULL because you have no name="email" in the email input. So change the email input to:

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

3) A warning like bellow is raised:

Warning: mysqli_query() expects at least 2 parameters, 1 given in [path-to]/index.php on line 103

So pass the connection object to the function, as argument:

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

4) You have no autoincremental primary key field in the carriers table. So define one:

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

5) Unfortunately your html code is a mess. You should change it properly. For example, a paragraph tag must be closed. But it also can not contain a fieldset inside. Other example: your closing form tag is not properly positioned. Etc.


Working code:

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

Alternative:

This is how I would have wrote the code for your page.

  • I am using prepared statements to avoid any mysql injection.
  • I am using the object-oriented mysqli.
  • In regard of error handling, you'll notice that I didn't do any. You should read this and this articles to find out, how it should be applied properly.
  • Change my db credentials with yours, in "connection.php".
  • Extract the css rules into a separate file.

Form page:

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

connection.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);

Table definition:

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;
PajuranCodes
  • 303
  • 3
  • 12
  • 43
  • Works like a charm. Thank you so much! – Jordan S Jul 23 '18 at 18:41
  • @JordanS You are very welcome. For the future: if your _reputation_ points are enough to do it, you can - and should - accept the answers that offer the solutions to your questions. Also, if you like an answer you can upvote it. Or you can downvote it, if you don't like it. But it's always fair to argument your downvotes with comments on the corresponding answers. Have fun and good luck. – PajuranCodes Jul 23 '18 at 20:06
  • I tried but I don't have enough rep to upvote you :( – Jordan S Jul 23 '18 at 20:47
  • @JordanS You don't need to accept or upvote my answer. I wrote the previous comment just so you know how to proceed in the future. Btw: Welcome on SO! :-) – PajuranCodes Jul 23 '18 at 21:46
  • Thanks friend. Appreciate the help and friendly welcoming. Have a great day! – Jordan S Jul 24 '18 at 14:00