1

I am new to PHP and am really struggling to post my PHP contact form data to my database (MySQL, MAMP, phpMyAdmin), I dont know why I am finding this so complex, I have been looking at my code for ages but can not figure it out. my database structure

connection.php

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "FutureDesign";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
//if ($conn->connect_error) {
//    die("Connection failed: " . $conn->connect_error);
//} 
//echo "Connected successfully";

$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$message = $_POST['message'];

$sql = "INSERT INTO ContactForm (name, phone, email, message ) VALUES ('$name', '$phone', '$email', '$message')";


if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

contact.php

<form name="sentMessage" id="contactForm" method="post" action="connection.php" novalidate>
            <div class="control-group form-group">
              <div class="controls">
                <label>Full Name:</label>
                <input type="text" class="form-control" name="name" id="name" required data-validation-required-message="Please enter your name.">
                <p class="help-block"></p>
              </div>
            </div>
            <div class="control-group form-group">
              <div class="controls">
                <label>Phone Number:</label>
                <input type="tel" class="form-control" name="phone" id="phone" required data-validation-required-message="Please enter your phone number.">
              </div>
            </div>
            <div class="control-group form-group">
              <div class="controls">
                <label>Email Address:</label>
                <input type="email" class="form-control" name="email" id="email" required data-validation-required-message="Please enter your email address.">
              </div>
            </div>
            <div class="control-group form-group">
              <div class="controls">
                <label>Message:</label>
                <textarea rows="10" cols="100" class="form-control" name="message" id="message" required data-validation-required-message="Please enter your message" maxlength="999" style="resize:none"></textarea>
              </div>
            </div>
            <div id="success"></div>
            <!-- For success/fail messages -->
            <button type="submit" value="submit" class="btn btn-primary" id="sendMessageButton">Send Message</button>
          </form>
Skimo
  • 45
  • 7
  • 2
    **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST`, `$_GET` or **any** user data directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman Apr 25 '18 at 03:27
  • Consider using a [development framework](http://codegeekz.com/best-php-frameworks-for-developers/) to solve problems like this. These give you patterns to follow for organizing your code into proper model, view and controller contexts and avoids ending up with a confused stew of concerns, with HTML, PHP, SQL, and JavaScript all jumbled together. Frameworks come in many forms from really lean like [Fat-Free Framework](https://fatfreeframework.com/) to exceptionally full-featured like [Laravel](http://laravel.com/) and many spots in between. – tadman Apr 25 '18 at 03:27
  • Make sure `phone` field doesn't contain a non-numeric character. – Karlo Kokkak Apr 25 '18 at 03:36
  • 1
    I will try to implement parameterised queries and bind_param, in the future as I am still very new to php development, thank you very much for your help, I will also considering using a framework in future – Skimo Apr 25 '18 at 03:37
  • Parameterized queries make it a lot harder to mess up and can save you hours and hours of debugging time. Another thing to remember is a lot of problems can be detected and resolved by [enabling exceptions in `mysqli`](https://stackoverflow.com/questions/14578243/turning-query-errors-to-exceptions-in-mysqli) so mistakes aren't easily ignored. You may find that in the process of cleaning up your code it starts working because you removed the defect. – tadman Apr 25 '18 at 04:14
  • `INT` is also only able to hold up to about 11 digits max. `INT(30)` is not going to store 30. Remember, phone numbers are not actually numbers, they're often things with lots of syntax, like `1-888-555-5555` or `+44 303 123 7300` where the notation is important not only for readability, but meaning. Use `VARCHAR(255)` for any "string"-type fields by default and only shorten them if absolutely necessary. 45 characters for an email address is way too short. – tadman Apr 25 '18 at 04:16
  • 1
    Thank you very much for all your help, I really do appreciate your advice, I will make the change to my database as regarding INT ASAP, I will also definitely look into Parameterised queries & bind_param, thank you again. You have been most helpful. – Skimo Apr 25 '18 at 04:23

3 Answers3

0

I have removed (name="sentMessage" id="contactForm") from the first line in my form and everything works perfectly?!

original line (with error)

<form name="sentMessage" id="contactForm" method="post" action="connection.php" novalidate>

edited line (removed error)

<form method="post" action="connection.php" novalidate>
Skimo
  • 45
  • 7
0

As an addition to other posts, try using Prepared Statements. This is more secure than using the mysqli function. W3schools is a great place to learn! They have a few articles on the subject. https://www.w3schools.com/php/php_mysql_prepared_statements.asp

Good Luck!

whoff
  • 154
  • 13
  • 1
    Please be *very* wary of w3schools. Much of their content is dangerously out of date and can steer you towards very dangerous practices and bad habits. The official PHP documentation is almost always higher quality and is up to date. w3schools is just in it for the clicks. PHP's documentation aims to educate. – tadman Apr 25 '18 at 04:32
-2

try to wrap your parameter with double quote like this

$sql = "INSERT INTO ContactForm (name, phone, email, message ) VALUES (".'$name'.", ".'$phone'.", ".'$email'.", ".'$message'.")";

i recommend you to bind you parameter with bind_param to avoiding sql injection

elcicko
  • 117
  • 8
  • I tried wrapping the parameters but that did not work, thank you anyway for the suggestion. – Skimo Apr 25 '18 at 03:49
  • 1
    PHP strings allow for interpolation, so normally switching to this style is doing exactly the same thing with different syntax. What you've done here is switch to *literal* `'$name'` as the insert value, which is a huge step backwards. `"...$x..."` will interpolate, `'...$x...'` won't. – tadman Apr 25 '18 at 04:08