1

I am trying to insert html form data in database through php. I am unable to insert html form data into database , i donot know , what i am doing wrong in my code?

Here is my code:

<?php
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'mydb';
$con=mysqli_connect($host, $username, $password,$dbname);
if (!$con) 
{
    echo "connection failed";
}

if(isset($_POST['submit']))
{
 $name = $_POST['username'];
 $pass = $_POST['password'];
$sql="insert into mytable1 (name,password) VALUES ('$name', '$pass')";
    if(mysqli_query($con,$sql))
    {
        echo "DATA IS INSERTED INTO DATABASE";
    }
}
?>
<!DOCTYPE HTML>
<html>
    <head>
        <title>SignUpform.com</title>

    </head>
    <body>

        <div id="div1">
            <div id="div2">
                <h1>Sign up Form</h1>
            </div>
           <form action="" method="post">
            <fieldset>
                <legend>Signup form ceredentials</legend>
                 <p id="p1">Name:</p>    
                <input id="text1" type="text" placeholder="Enter username" name="username">
                 <p id="p2">Password:</p>
                <input id="pass1" type="password" placeholder="Enter Password" name="password">
                <p id="email">Email:</p>
                <input id="emailtextfld" type="text" placeholder="Enter Email" name="email">
                <p id="company">Company Name:</p>
                <input id="companytextfld" type="text" placeholder="Company name" name="company">
                <input id="donebtn" type="submit" value="submit" name="submit">

            </fieldset>
           </form> 
        </div>
    </body>
</html>

And here is my database enter image description here

The structure of my database table: enter image description here

Mcolo
  • 149
  • 2
  • 10
  • 1
    Do you get `DATA IS INSERTED INTO DATABASE`? You are open to SQL injections, parameterize your queries. Your passwords should be hashed. – chris85 Sep 07 '17 at 04:04
  • no i am not getting this message "Data is inserted into database" @chris85 – Mcolo Sep 07 '17 at 04:11
  • So what does happen, nothing is displayed? Can you put `else`s on your conditional to see if either are failing? – chris85 Sep 07 '17 at 04:13
  • yeah you are right , nothing is displayed when i press "submit button" and when i put else block i got this error message "Parse error: syntax error, unexpected '}', expecting ',' or ';' in C:\wamp64\www\html\phpfile.php on line 22 " @chris85 – Mcolo Sep 07 '17 at 04:18
  • sorry i forgot to put ";" at the end of the else block message so that is why i was getting that error message.After putting else block i got message "Data is not inserted into database"@chris85 – Mcolo Sep 07 '17 at 04:22
  • Try putting `echo mysqli_error($con)` in the `else` block to see what the error is. – Joel H. Sep 07 '17 at 04:26
  • Note: The object-oriented interface to `mysqli` is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete `mysql_query` interface. Before you get too invested in the procedural style it’s worth switching over. Example: `$db = new mysqli(…)` and `$db->prepare("…”)` The procedural interface is an artifact from the PHP 4 era when `mysqli` API was introduced and should not be used in new code. – tadman Sep 07 '17 at 04:39
  • **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 Sep 07 '17 at 04:39
  • **WARNING**: Writing your own access control layer is not easy and there are many opportunities to get it severely wrong. Please, do not write your own authentication system when any modern [development framework](http://codegeekz.com/best-php-frameworks-for-developers/) like [Laravel](http://laravel.com/) comes with a robust [authentication system](https://laravel.com/docs/5.4/authentication) built-in. At the absolute least follow [recommended security best practices](http://www.phptherightway.com/#security) and **never store passwords as plain-text**. – tadman Sep 07 '17 at 04:40
  • 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. – tadman Sep 07 '17 at 04:41
  • after using `echo mysqli_error($con)` in the `else` block i got this message `You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''mytable1' ('name','password') VALUES ([], [])' at line 1` @JoelH. – Mcolo Sep 07 '17 at 04:45
  • Are you using the same query that's posted in the question? That error appears to be because of the single quotes. Try using the original query: `$sql="insert into mytable1 (name,password) VALUES ('$name', '$pass')";`. – Joel H. Sep 07 '17 at 04:52
  • The error message is not formatted like the query you provided here. Are you quoting the tables/columns? Why are the values arrays? – chris85 Sep 07 '17 at 04:55
  • when i try this query `$sql="insert into mytable1 (name,password) VALUES ('$name', '$pass')"; ` it says `mytable1 is read only` @Joel H. – Mcolo Sep 07 '17 at 05:00
  • `(name,password)` these are the table columns @chris85 – Mcolo Sep 07 '17 at 05:04
  • If you run it in phpmyadmin is it read only as well? Are you using the same user? – chris85 Sep 07 '17 at 05:05
  • yeah i am using the same user "root" @chris85 – Mcolo Sep 07 '17 at 05:11
  • and the behavior differs? – chris85 Sep 07 '17 at 05:12
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/153833/discussion-between-mcolo-and-chris85). – Mcolo Sep 07 '17 at 05:12

3 Answers3

2
if(isset($_POST['submit']))
{
$name = $_POST['username'];
$pass = $_POST['password'];
$sql="insert into mytable1 (name,password) VALUES ('$name', '$pass')";

$query = mysqli_query($con, $sql);
if($query)
{
echo "<h4 style='color:green'>Inserted Successfully.</h4>";
    }
    else
    {
        echo "<h4 style='color:red'>Faild.</h4>";
    }
}
?>

Try this solution.

Prakhar Sood
  • 159
  • 1
  • 10
  • I have tried this but it says "failed" @Prakhar Sood – Mcolo Sep 07 '17 at 04:27
  • So there is something wrong with your insert query. Try to echo the values of username and password, check whether you are even getting the values through the form or not. – Prakhar Sood Sep 07 '17 at 04:29
  • Yes i have echo the values of username and password and it's getting the values through html form @Prakhar Sood – Mcolo Sep 07 '17 at 04:34
2

You should change your storage engine of your database from:

ENGINE=MRG_MyISAM DEFAULT CHARSET=utf8mb4;

to

ENGINE=innoDB DEFAULT CHARSET=utf8;

From my point of view it's happening just because of "Engine error".So after changing your storage engine of your database , i hope it will work for you inshallah.

Shahab Khan
  • 542
  • 2
  • 10
  • After changing storage engine of my database , it's working fine now and the problem of insertion of data in database is solved now.@Shahab Khan – Mcolo Sep 07 '17 at 06:59
1

You need to give form action like this

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">

add this to check connection

if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
Shibon
  • 1,552
  • 2
  • 9
  • 20