Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

How to Connect html inquiry form That Stores Data in a MySQL Database Using PHP

i am using AppServ v2.5.9 i already done making form the probleme is i dont know how to connect ...i tired this code

 <?php

define('DB_NAME', 'inquiry_box');
define('DB_USER', 'root');
define('DB_PASSWORD', '*****');
define('DB_HOST', 'localhost');

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

if (!$link) {
    die('Could not connect: ' .mysql_error());
}

$db_selected = mysql_select_db(DB_NAME, $link);

if  (!$db_selected) {
die('Cant\'t use ' . DB_NAME . ': ' . mysql_error());
}
 $value = $_POST['name'];
 $value = $_POST['email'];
 $value = $_POST['contact_no'];
 $value = $_POST['comment'];

$sql ="INSERT INTO contact_form (name, email, contact_no, comment) VALUES ('$value','$value2','$value3','$value4')";

if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}

mysql_close();
?> 

then what happen is it connect but when i type in the form data doesn't insert in the mysql but it actually show the id only but then no name email conatct and comment appears please help please

3 Answers

Chris Shaw
Chris Shaw
26,650 Points

Hi Maie,

Currently you're overwriting the variable $value with each value from your $_POST array and then looking for variables such as $value2 which isn't defined, what you want to do is assign each value to their variable instead and also escape the string to prevent XSS injection.

<?php

$name       = mysql_real_escape_string($_POST['name']);
$email      = mysql_real_escape_string($_POST['email']);
$contact_no = mysql_real_escape_string($_POST['contact_no']);
$comment    = mysql_real_escape_string($_POST['comment']);

$sql = sprintf(
    "INSERT INTO contact_form (name, email, contact_no, comment) VALUES ('%s', '%s', '%s', '%s')",
    $name,
    $email,
    $contact_no,
    $comment
);

Also the MySQL module as of PHP 5.5 no longer exists and has been deprecated since PHP 5.4, from now on it's recommended that you use either MySQLi or PDO.

<?php

$con=mysqli_connect("localhost","root","rinu","inquiry_box");

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

// escape variables for security
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$contact_no = mysqli_real_escape_string($con, $_POST['contact_no']);
$comment = mysqli_real_escape_string($con, $_POST['comment']);

$sql="INSERT INTO form (name, email, contact_no, comment) VALUES ('$name', '$email', '$contact_no', '$comment')";

if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); }
echo "1 record added";

mysqli_close($con);

?>

is this right???

but why still data does not enter to mysql ?? but it shows id then blank blank blank for example 64 then no name email contact_no comment

Chris Shaw
Chris Shaw
26,650 Points

Hi Maie,

Everything above looks correct, if you're still receiving empty values then it means your $_POST data either has different key names than what you have set above or nothing is been submitted from the form using a method type of POST.

i want to ask how can we make form validation using Java Script and ajax form content is name email contact_no comment i use this code above but i found out the problem is in the js where the code is making send to mail i want it send to mysql

jQuery(document).ready(function($){

    // hide messages 
    $("#error").hide();
    $("#sent-form-msg").hide();

    // on submit...
    $("#contactForm #submit").click(function() {
        $("#error").hide();

        //required:

        //name
        var name = $("input#name").val();
        if(name == ""){
            $("#error").fadeIn().text("Name required.");
            $("input#name").focus();
            return false;
        }

        // email
        var email = $("input#email").val();
        if(email == ""){
            $("#error").fadeIn().text("Email required");
            $("input#email").focus();
            return false;
        }

        // contact_no
        var contact_no = $("input#contact_no").val();
        if(contact_no == ""){
            $("#error").fadeIn().text("Contact number required");
            $("input#contact_no").focus();
            return false;
        }

        // comments
        var comments = $("#comments").val();


        // data string
        var dataString = 'name='+ name
                        + '&email=' + email        
                        + '&contact_no=' + contact_no
                        + '&comments=' + comments

        // ajax
        $.ajax({
            type:"POST",
        });
    });  


    // on success...
     function success(){
        $("#sent-form-msg").fadeIn();
        $("#contactForm").fadeOut();
     }

    return false;
});