-2

I am trying to create a subscribe entry in the mysql database. Every time I submit the form a new entry is created while the email address or the input value is not appearing in the data base. Please locate what is wrong.

<?php
include 'dbh.php';
$subs=$_POST['$sub_email']:
$sql="INSERT INTO subscribe(sub) VALUES('$subs')";
$result=mysqli_query($conect,$sql);
header("Location:index.html");
?>

<form class="form" method="post" action="subscribe.php" style="margin-top: 20px">
    <div class="input-group">
        <div class="input-group-addon">@</div>
        <input type="email" class="form-control" name="subs_email" id="inlineFormInputGroup" placeholder="Your Email">
    </div>
    <button  type="submit" class="btn btn-success btn-lg" style="margin-top:5px " >Submit</button>
</form>
Pathik Vejani
  • 4,263
  • 8
  • 57
  • 98
  • 1
    **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` or `$_GET` data directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman Jan 27 '17 at 04:07

2 Answers2

1

Please note that your HTML input has the attribute name="subs_email"

So, your $_POST array index should be subs_email instead of $subs_email

$subs=$_POST['subs_email']:
Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32
0

Try the following code insert if email id not exist:

<?php
include 'dbh.php';
if(isset($_POST['subs_email'])) {
    $subs = mysqli_real_escape_string($conect, $_POST['subs_email']);   //escape variables for security
        // insert if email id not exist
    $result = mysqli_query($conect,"SELECT `sub` FROM `subscribe` WHERE  `sub` = '".$subs."' LIMIT 1");
    if (mysqli_num_rows($result) <= 0) { {
        $sql = "INSERT INTO subscribe (sub) VALUES('".$subs."')";
        $result = mysqli_query($conect,$sql);
    }
    header("Location:index.html");
}
?>

<form class="form" method="post" action="subscribe.php" style="margin-top: 20px">
    <div class="input-group">
        <div class="input-group-addon">@</div>
        <input type="email" class="form-control" name="subs_email" id="inlineFormInputGroup" placeholder="Your Email">
    </div>
    <button  type="submit" class="btn btn-success btn-lg" style="margin-top:5px " >Submit</button>
</form> **strong text**
Pathik Vejani
  • 4,263
  • 8
  • 57
  • 98
mith
  • 1,680
  • 1
  • 10
  • 12