5

Inserting data into the SQL table from the HTML form

 2 years ago
source link: https://www.codesd.com/item/inserting-data-into-the-sql-table-from-the-html-form.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Inserting data into the SQL table from the HTML form

advertisements

A HTML form has been created that should (when filled) send the data it's holding to a database inserting a new row so it can be used later on. However, I can't seem to get it to work, I'm getting the following error:

Notice: Use of undefined constant con - assumed 'con' in C:\xampp\htdocs\form\insert.php on line 4

Warning: mysql_query() expects parameter 1 to be string, object given in C:\xampp\htdocs\form\insert.php on line 17
Data not inserted


HTML Code

<!DOCTYPE html>
<html>
    <head>
        <title>Form linked to database</title>
    </head>
    <body>
        <form action="insert.php" method="post">
            Name: <input type="text" name="username">
            <br>
            Email: <input type="text" name="email">
            <br>
            <input type="submit" value="insert">
        </form>
    </body>
</html>


PHP Code

<?php
$con = mysqli_connect('localhost','[retracted]','[retracted]');

if(!con) {
    echo 'Not connected to server!';
}

if(!mysqli_select_db($con,'tutorial')) {
    echo 'Database not selected!';
}

$Name = $_POST['username'];
$Email = $_POST['email'];

$sql = "INSERT INTO person (Name,Email) VALUES ('$Name','$Email')";
if(!mysql_query($con,$sql)) {
    echo 'Data not inserted';
} else {
    echo 'Data inserted';
}
//header("refresh:2; url=form.html");
?>


I'm new to PHP and followed the following YouTube tutorial.

I'm also using XAMPP for this, on a localhost. Any help is appreciated. Thank you.


You should change:

if(!con){
    echo 'Not connected to server!';
}

if(!$con){
    echo 'Not connected to server!';
}

as you're missing a dollar sign there.

Additionally, you're using a mysql_ function here, on the mysqli_ object $con:

if(!mysql_query($con,$sql))

Change this to

if(!mysqli_query($con,$sql))

SQL injection

As your query is vulnerable to SQL injection, then I'd like to recommend you take a look at using prepared statements, or using mysqli_real_escape_string()-- though, this comes with a few gotcha's: https://stackoverflow.com/a/12118602/7374549


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK