Skip to content Skip to sidebar Skip to footer

Insert Data To Database Via Html Form In The Same Page

Lab03
Name: .$_POST['name']."', '".$_POST['fn']."',". $_POST['sid'].", '".$_POST['email']."'");

Solution 2:

your query should like this:

mysqli_query($con,"INSERT INTO lab_03 (name, fname, sid, email) VALUES ('".$_POST['name']."', '".$_POST['fn']."',". $_POST['sid'].", '".$_POST['email']."'");

Solution 3:

This is a good way to do it:

mysqli_query(
    $con,
    "INSERT INTO lab_03 (
        name, 
        fname, 
        sid, 
        email
    ) 
    VALUES (
        '{$_POST['name']}',
        '{$_POST['fn']}',
        '{$_POST['sid']}',
        '{$_POST['email']}'
    "
);

To make sure it works, remove the single quotes around {$_POST['something']} if your field in the database is an integer (or anything else not requiring quotes).

Also, keep in mind that currently your code is vulnerable to SQL injections, since you're not sanitizing the input data. Take a look at this question to see how to prevent it.

Solution 4:

Using this answer as a reference, I'd like to point out a major flaw in your code.

You need to put a check if your $_POST variable exists or not, else it'll still throw errors.

Put it like this:

if(isset($_POST['name'])) {
    mysqli_query($con,"INSERT INTO lab_03 (name, fname, sid, email) VALUES ('".$_POST['name']."', '".$_POST['fn']."',". $_POST['sid'].", '".$_POST['email']."'");
}

Also, I suggest you call your PHP code before the form, cause that's the way to do it.

Solution 5:

Put all your PHP code above HTML, and you have used wrong variable for getting POST values. It should be $_POST not $POST_

It is ideal to use mysqli_real_escape_string to escapes special characters that may be in POST data values

<?phpinclude ("connection.php");

mysqli_query($con,"INSERT INTO lab_03 (name, fname, sid, email) VALUES ('".mysqli_real_escape_string($con, $_POST['name'])."', '".mysqli_real_escape_string($con, $_POST['fn'])."', '".mysqli_real_escape_string($con, $_POST['sid'])."', '".mysqli_real_escape_string($con, $_POST['email'])."'");
?>

Post a Comment for "Insert Data To Database Via Html Form In The Same Page"