0

I am trying to create PHP form data insert in SQL but getting error. Even when I write code same to same but I'm still getting an error.

<?php

    $un = $_POST['uname'];
    $em = $_POST['email1'];

//with or what out these bellow variables
    $host = "localhost";
   $username = "admin";
   $password = "admin";
   $database = "test1";

    $db = mysqli_connect('$host','$username','$password','$database');
    $query = "INSERT INTO users ('username','password') VALUES ('$un','$em')";
    $rs = mysqli_query($db,$query);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form Registration</title>
</head>
<body>
    <form action="server1.php" method="post">
        <label>Name</label>
        <input type="text" name="uname" required="required">
        <label>Email</label>
        <input type="email" name="email1" required="required">
        <input type="submit" name="submit" value="submit">
    </form>

</body>
</html>
  • 2
    What is the error you are getting? – LordBaconPants May 22 '18 at 00:02
  • What is "same to same"? – James Z May 22 '18 at 07:11
  • Data is not interring in database when i click on submit. – Noob Developer May 22 '18 at 08:07
  • 1
    Your code is vulnerable to [SQL injection](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use [mysqli](https://secure.php.net/manual/en/mysqli.prepare.php) or [PDO](https://secure.php.net/manual/en/pdo.prepared-statements.php) prepared statements with bound parameters as described in [this post](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). –  May 22 '18 at 08:25
  • can you re-write my codes. – Noob Developer May 22 '18 at 08:34

2 Answers2

1

The error was "" just inverted comma's, now its works perfectly.

     <?php
        $un = $_POST['uname'];
        $em = $_POST['email1'];

        $host = "localhost";
        $username = "admin";
        $password = "admin";
        $database = "test1";

            $con = mysqli_connect ("$host","$username","$password","$database");
            $query = "insert into users (username,email) values ('$un','$em')";
            $run = mysqli_query ($con,$query);

            if ($run=TRUE){
                echo 'Data Submitted Successfuly';
            }
            else {
                echo 'Error';
            }

    ?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form Registration</title>
</head>
<body>
    <form action="server1.php" method="post">
        <label>Name</label>
        <input type="text" name="uname" required="required">
        <label>Email</label>
        <input type="email" name="email1" required="required">
        <input type="submit" name="submit" value="submit">
    </form>

</body>
</html>
0

You can try this way.

$db = mysqli_connect($host, $username, $password) or die ('Unable to connect');
mysqli_select_db($db, $database) or die('Unable to select DB');