Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (6.1k points)
closed by

Using terminal, I created users table in MySQL and I created a simple task:

Inserting values from the form. This is my dbConfig file

<?php

$mysqli = new mysqli("localhost", "root", "pass", "testDB");

/* check connection */

if (mysqli_connect_errno()) {

    printf("Connect failed: %s\n", mysqli_connect_error());

    exit();

}

?>

 

and This is my Index.php .

<!doctype html>

<html>

 <head>

    <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <meta name="description" content="$1">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" type="text/css" href="style.css">

    <title>test</title>

    <?php

    include_once 'dbConfig.php';

    ?>

</head>

<body>

     <?php

    if(isset($_POST['save'])){

        $sql = "INSERT INTO users (username, password, email)

        VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

    }

    ?>

    <form method="post"> 

    <label id="first"> First name:</label><br/>

    <input type="text" name="username"><br/>

    <label id="first">Password</label><br/>

    <input type="password" name="password"><br/>

    <label id="first">Email</label><br/>

    <input type="text" name="email"><br/>

    <button type="submit" name="save">save</button>

    <button type="submit" name="get">get</button>

    </form>

</body>

</html>

When I pressed the save button, nothing happened, the database was not updated. I tried echoing the INSERT query and it takes all values from the form as it is supposed to. After I try to check whether it worked from a terminal or not, I login into my SQL try to return all data from user's table and it returns an empty set.

closed

4 Answers

0 votes
by (7.8k points)
 
Best answer
Based on the code you provided, it seems that you're missing the actual execution of the SQL query to insert the values into the database. You have defined the query but haven't executed it. To fix this, you need to add the following line after defining the SQL query:

$mysqli->query($sql);

This line will execute the SQL query using the `$mysqli` object, which represents the database connection.

Here's the modified code for your `Index.php` file:

<!doctype html>

<html>

<head>

    <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <meta name="description" content="$1">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" type="text/css" href="style.css">

    <title>test</title>

    <?php

    include_once 'dbConfig.php';

    ?>

</head>

<body>

    <?php

    if(isset($_POST['save'])){

        $sql = "INSERT INTO users (username, password, email)

                VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

        $mysqli->query($sql); // Execute the SQL query

    }

    ?>

    <form method="post">

        <label id="first">First name:</label><br/>

        <input type="text" name="username"><br/>

        <label id="first">Password</label><br/>

        <input type="password" name="password"><br/>

        <label id="first">Email</label><br/>

        <input type="text" name="email"><br/>

        <button type="submit" name="save">Save</button>

        <button type="submit" name="get">Get</button>

    </form>

</body>

</html>

With this modification, the SQL query should be executed when the "Save" button is pressed, and the values should be inserted into the `users` table in your MySQL database.
0 votes
by (11.7k points)

Ans: 

The code mentioned below just declares a string variable that contains a MySQL query:

$sql = "INSERT INTO users (username, password, email)

    VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

Query is not executed by this. Please understand this concept:

NEVER TRUST USER INPUT: Do not append user input like form input from $_GET or $_POST) directly to your query. Anyone can manipulate the input which can cause great damage to your database which is called SQL Injection.

If you want to protect your script from such an attack you must use Prepared Statements.

Include prepared statements to your code like this:

$sql = "INSERT INTO users (username, password, email)

    VALUES (?,?,?)";

Prepare your statement using mysqli_prepare:

$stmt = mysqli_prepare($sql);

Now start binding the input variables to the prepared statement:

$stmt->bind_param("sss", $_POST['username'], $_POST['email'], $_POST['password']);

And finally, execute the prepared statements. (This is where the actual insertion takes place)

$stmt->execute();

If you want to get more insights into SQL, checkout this SQL Course from Intellipaat.

0 votes
by (13k points)

Based on the code you provided, it seems that you're missing the actual execution of the SQL query to insert the values into the database. After constructing the query, you need to execute it using the `mysqli_query()` function. Here's an updated version of your code that includes the execution of the query:

<!doctype html>

<html>

<head>

    <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <meta name="description" content="$1">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" type="text/css" href="style.css">

    <title>test</title>

    <?php

    include_once 'dbConfig.php';

    ?>

</head>

<body>

    <?php

    if(isset($_POST['save'])){

        $sql = "INSERT INTO users (username, password, email)

        VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

        

        // Execute the query

        $result = mysqli_query($mysqli, $sql);

        if ($result) {

            echo "Data inserted successfully!";

        } else {

            echo "Error inserting data: " . mysqli_error($mysqli);

        }

    }

    ?>

    <form method="post"> 

        <label id="first">First name:</label><br/>

        <input type="text" name="username"><br/>

        <label id="first">Password</label><br/>

        <input type="password" name="password"><br/>

        <label id="first">Email</label><br/>

        <input type="text" name="email"><br/>

        <button type="submit" name="save">Save</button>

        <button type="submit" name="get">Get</button>

    </form>

</body>

</html>

In this updated version, after constructing the `INSERT` query, it is executed using `mysqli_query($mysqli, $sql)`. The result of the query execution is stored in the `$result` variable. If the query is successful, it will display a success message. Otherwise, it will display an error message along with the specific error generated by MySQL.

Make sure to replace "pass" in the `dbConfig.php` file with the actual password for your MySQL root user. Additionally, ensure that the table name and column names in the `INSERT` query match your database schema correctly.

0 votes
by (11.4k points)
Based on the code you provided, it appears that you have correctly written the code to insert values into the `users` table in your MySQL database. However, you are missing the actual execution of the SQL query.

To fix this issue, you need to add the following line of code after defining the SQL query inside the `if(isset($_POST['save']))` block:

$mysqli->query($sql);

This line executes the SQL query using the `mysqli` object and performs the insertion into the database.

Here's the modified code for the `if(isset($_POST['save']))` block:

if(isset($_POST['save'])){

    $sql = "INSERT INTO users (username, password, email) VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

    $mysqli->query($sql);

}

By adding this line, the SQL query will be executed, and the values from the form will be inserted into the `users` table in your MySQL database.

Make sure to also check if there are any errors in your database connection or SQL query execution. You can add error handling to the code to help you debug any potential issues.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
4 answers
asked Feb 25, 2021 in SQL by RohitSingh (2.6k points)

Browse Categories

...