JPeroutek
JPeroutek

Reputation: 568

Why is MySQL not accepting this value, or why is php not transmitting it properly?

I am working on a contact form for my company, and I made this large elaborate form with over 20 fields for the user to fill out. Upon clicking submit, the php page sends an email to a sales rep with a detailed report of the order. The next step is to get the info into a database. I wrote the code for it, but it is not working, so I created a secondary table for me to use for testing purposes until I am ready to use the one for the company. In this small test database, there are 3 fields, orderID, companyName, and contactName. When I specify an orderID, and only an orderID, it gets stored in the database, no problem, using the code below.

$mysqli = new mysqli ("host", "username", "pass", "dbname");
    if($mysqli->connect_errno)
    {
        echo "Failed to connect: " . $mysqli->connect_error;
    }
    $mysqli->query("insert into testTable (orderID) values (5000)");

But if I use this code below, this time including a companyName value, nothing happens at all. I get no errors(that I see) and php says nothing.

$mysqli = new mysqli ("host", "username", "pass", "dbname");
    if($mysqli->connect_errno)
    {
        echo "Failed to connect: " . $mysqli->connect_error;
    }
    $mysqli->query("insert into testTable (orderID, companyName) values (5000, \'".$_POST['companyName']."\')");

Any and all help is appreciated, and thank you in advance.

Upvotes: 0

Views: 239

Answers (1)

Dany Caissy
Dany Caissy

Reputation: 3206

Try this instead :

$mysqli = new mysqli ("host", "username", "pass", "dbname");
if($mysqli->connect_errno)
{
    echo "Failed to connect: " . $mysqli->connect_error;
}

$companyName = $mysqli->real_escape_string($_POST['companyName']);

$mysqli->query("insert into testTable (orderID, companyName) values (5000, '$companyName')");

I think you were escaping the single quotes and it wasn't necessary, also I sanitized your company name to help protect you against MySQL injections.

It is best to use prepared queries none the less, for more information, visit the following links :

https://www.php.net/manual/en/mysqli.real-escape-string.php

How can I prevent SQL injection in PHP?

Upvotes: 1

Related Questions