-1

I have this form:

<form action="contactus.php" method="post">
        <select name="formTitle">
            <option value="">Select...</option>
            <option value="M">Mr</option>
            <option value="F">Mrs</option>
        </select>

        <p><b>Name</b></p>
        <input type="text" name="formName" maxlength="50"/>

        <p><b>Enquiry</b></p>
        <input type="text" name="formEnquiry" maxlength="500"/>
    </select>

<p><input type="submit" name="formSubmit" value="Submit"/></p>

And I have a MySQL database (called 'contacts') with a table (called 'enquiries') with three columns; 'Title', 'Name', 'Enquiry'.

The database has no password or anything. It's just a localhost with a 'root' password.

What kind of PHP would I need to send the data from this HTML form to the MySQL database?

  • 3
    Possible duplicate of [Connecting PHP Code and Submit Form to mySQL Database](http://stackoverflow.com/questions/24244203/connecting-php-code-and-submit-form-to-mysql-database) – Ani Menon Apr 20 '16 at 20:09
  • 1
    @AniMenon I have looked at other people's questions similar to mine, but often their HTML form is a little different and I struggle to understand how the PHP would help my form. – Jake Flaxman Apr 20 '16 at 20:10
  • I have posted an answer which is specific to your case, hope it helps. – Ani Menon Apr 20 '16 at 20:18
  • If you're just getting started and want to develop robust applications have a look at the various [development frameworks](http://codegeekz.com/best-php-frameworks-for-developers/) available and find one that suits your style and needs. [Laravel](http://laravel.com/) has great documentation and is very easy to get started with and has a number of built-in methods that make doing this sort of thing pretty simple and straightforward. – tadman Apr 20 '16 at 20:27

2 Answers2

0

I can help you in this problem.

So, just add the following code to your php file contactus.php.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "contacts";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if(isset($_POST['formSubmit'])) {
    $formTitle = $_POST['formTitle'];
    $formName = $_POST['formName'];
    $formEnquiry = $_POST['formEnquiry'];

    $sql = "INSERT INTO enquiries (Title, Name, Enquiry) VALUES ('$formTitle', '$formName', '$formEnquiry')";
    $conn->query($sql);
?>

I hope this will solve your problem.

-1

SIMPLE ANSWER: MySQL

A LITTLE BIT MORE DEVELOPED ANSWER: MySQL is in basic terms the combination of PHP and SQL to create an easy way to do various actions to a database, which include:

  • Create table
  • Query table
  • Update table
  • and much more

There are variations of MySQL, including MySQLi and MySQL (PDO).

an example of connecting to your database via MySQL (PDO) would be:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$myDB = "databasename";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$myDB", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 

    //insert code there that you want to execute...

    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
?>

you mentioned that you don't have a password, so you might just leave the "password" slot empty ("") I suppose, though this is very insecure and I recommend you place a password.

In the code above, there is a comment that says:

    //insert code there that you want to execute...

Here you would include code that would probably do actions similar to the ones mentioned above (query table, update table, etc). An example of code similar to that would be:

//htmlspecialchars takes out special characters that might
//exist in the posted information if someone were trying
//to hack your site via sql injection
$formTitle = htmlspecialchars($_POST['formTitle']);
$formName = htmlspecialchars($_POST['formName']);
$formEnquiry = htmlspecialchars($_POST['formEnquiry']);

$sql = "INSERT INTO enquiries (Title, Name, Enquiry) VALUES (formTitleBinded, formNameBinded, formEnquiryBinded)";

$sqlPrepared = $conn->prepare($sql);
$sqlPrepared->bindParam(':formTitleBinded',$formTitle);
$sqlPrepared->bindParam(':formNameBinded',$formName);
$sqlPrepared->bindParam('formEnquiryBinded',$formEnquiry);

$sqlPrepared->execute();

The previous code both sanitizes your input and inserts a row into your table with that information.

Let me know if that helped!


EDITED: My answer has been edited with parameter binding included to prevent SQL Injection.

Webeng
  • 7,050
  • 4
  • 31
  • 59
  • 2
    I like your enthusiasm, but that query is **dangerously wrong** because you're not properly escaping those values. `htmlspecialchars` is for HTML display only, it's not useful in a database context and if you think it does anything to protect you from injection bugs you're greatly misinformed. The best way to address this is [prepared statements](http://php.net/manual/en/pdo.prepared-statements.php). That actually saves two lines of code compared to what you have here, and as a bonus completely eliminates [SQL injection bugs](http://bobby-tables.com/) if done correctly. – tadman Apr 20 '16 at 20:25
  • @tadman interesting, when you say is for HTML display only, what do you mean? From my understanding, I thought htmlspecialchars removes the special characters (<,>,:,etc) that could be used in sql injection attacks. If it removes them, and I save the new string in $var1, $var2, etc, which is being saved into the database, wouldn't that itself help prevent sql injection? And thank you for your feedback, I am always very eagered to learn, especially when being corrected :) – Webeng Apr 20 '16 at 20:29
  • 1
    `htmlspecialchars` is to prevent XSS, that is JavaScript and HTML injection when displaying things in the browser. It's completely useless for preventing SQL injection. For that you need to use prepared statements, or if those won't work, then the MySQL escaping functions. I'm not trying to beat you up here, just correct a misconception that could cost you dearly if you make a mistake like this on a production application. – tadman Apr 20 '16 at 20:32
  • @tadman I understand your not :), and am taking this opportunity to understand why I am wrong. I understand htmlspecialchars helps prevent XSS, but doesn't it do it by taking out the special characters that would be used to generate the cross site scripting attack, and why wouldn't this also be useful for preventing sql injection since those are similar characters that are used? That is where I am confused, it seems that it would do the job, so why doesn't it? and yes, I am about to update my answer with parameter binding for the prepared statement. – Webeng Apr 20 '16 at 20:35
  • 1
    Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Apr 20 '16 at 20:37
  • 1
    General rule: When displaying user content, use `htmlspecialchars`. When adding to a database use prepared statements or manual escaping if necessary. Remember, what's valid JavaScript is not valid SQL and vice-versa. They're two different concerns. This is why I test apps with strings like: `'bad' "string"` to see if they properly escape both HTML and SQL. If they don't, you'll get an error or see the text as bold. Come up with your own punishingly abusive test strings to verify you're doing it correctly. – tadman Apr 20 '16 at 20:38
  • There are tools out there that will automatically test your site, but the [features they have](http://sqlmap.org) are extremely terrifying if someone with malicious intent is using them. All it takes is a simple mistake to open yourself up to that scary list of things. – tadman Apr 20 '16 at 20:40
  • Your answer is close now. Remember that in the query you need names like `:placeholder` that match your bindings and the `htmlspecialchars` can be removed. Just bind directly to the `$_POST` variables coming in to make it more concise. – tadman Apr 20 '16 at 20:42
  • @tadman I understand your general rule but that doesn't address my question previously of why, if htmlspecialchars does take out characters, why isn't that at least a layer of protection. Now maybe the answer to that question is very big and for that reason you are giving me a general rule. If that were the case would you know what phrase I could google that would explain it to me? When I was learning MySQL on popular youtube videos, htmlspecialchars() was specifically stated to work for my previous reasons, and now I'm just trying to understand WHY, and not THAT it doesn't, but WHY it doesnt – Webeng Apr 20 '16 at 20:43
  • Escaping the HTML before inserting it into the database doesn't add any security and is just plain annoying. When you need to display that later you have to avoid escaping it, which violates one of the XSS protection rules, or it will be doubly escaped. Keep your database as raw as possible, avoid overly "sanitizing" the content. Your rules for what's acceptable might change, and re-processing your whole database is a huge pain. YouTube videos are often full of completely incorrect advice. I'd put more stock in a curated guide like [PHP the Right Way](http://www.phptherightway.com/). – tadman Apr 20 '16 at 20:45
  • [XSS protection](https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet) is sometimes nuanced and complicated, as is SQL injection prevention, but they are concerned with two completely different things. They have only a superficial amount of commonality. – tadman Apr 20 '16 at 20:50
  • @tadman thanks for your input tadman, it's definitely a different view. From what I understood, the prepared statement and binding parameters should be all that is needed, and If I am not mistaken, the reason for not using htmlspecialchars is more than anything to have as raw data as possible, so that I don't lose something that might be valuable to me. I'll keep investigating it as I prefer to give my mind some mesh time to formulate proper logic :). Don't hesitate to add anything else please, I see this all as constructive criticism! – Webeng Apr 20 '16 at 20:54
  • `htmlspecialchars` has the effect of "cooking" your data, that is, rendering things like `<` as `<`. You don't want to do that, as it'll end up as `&lt;` if you escape it on display like you're supposed to. Keeping track of which columns have been pre-processed and which are still raw makes for a very complicated application, so keeping everything in a raw state and filtering on display is the best plan. Some applications allow a white-list of certain tags, common when allowing a bit of HTML in user profiles, and these rules can change arbitrarily. Keep it raw, figure it out on display. – tadman Apr 20 '16 at 21:05