Shikhar Shah Shikhar Shah - 1 month ago 6
PHP Question

Blank rows are being inserted after every time i add values in row in my DATABASE

I have following codes and it runes successfully and says that data successfully entered but when i check the database table, every time i insert data (Despite of that successful operation) i get one blank row.
Inshort no data is being inserted although the code says operation successful

CODE:
dbconnect.php

<?php
$host= "host";
$user = "user";
$password = "pass";
$db = "db";

$con = mysqli_connect($host,$user,$password,$db);
if (!$con)
{ echo "Failed to Connect"; }
else
{ echo "Connection successful";}
?>


CODE:addInfo.php

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require "dbconnect.php";
$username = $_POST["username"];
$email = $_POST["email"];
$mobile = $_POST["mobile"];
$flag = false;
$sql = "insert into userInfo values('".$username."','".$email."','".$mobile."');";
$flag=mysqli_query($con,$sql);
if($flag!==false)
{
echo "Data inserted successfully!";
}
else
{
echo "Error in insertion" . mysqli_error($con);
}
?>


CODE:index.php

<!DOCTYPE html>
<html>
<head>
<title>Add Information</title>
</head>
<body>
<form method="POST" action="addinfo.php">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="username"/></td>
<td>Email:</td>
<td><input type="text" name="email"/></td>
<td>Mobile:</td>
<td><input type="text" name="mobile"/></td>
</tr>
</table>
<input type ="submit" value="Submit" />
</form>
</body>
</html>


Any type of help you guys can do,please proceed,

Answer

I) Changes

  • Change $username = $_POST["username"]; to $username = $_POST["name"];
  • Add method="POST" in <form>
  • Use mysqli prepared statement to avoid security vulnerability.

II) Updated Code

dbconnect.php

<?php
$host= "host";
$user = "user";
$password = "pass";
$db = "db";

$con = new mysqli($host, $user, $password, $db);
if ($con->connect_errno) {
  echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
}
?>

addInfo.php

<?php
require "dbconnect.php";

$stmt = $mysqli->prepare("INSERT INTO userInfo (`username`,`email`,`mobile`) VALUES (?, ?, ?)");
$stmt->bind_param('sss', $_POST["name"], $_POST["email"], $_POST["mobile"]);

if($stmt->execute()) {
  echo "Data inserted successfully!";
} else {
  echo "Error in insertion" . $con->errno;
}
?>

index.php

<!DOCTYPE html>
<html>
  <head>
    <title>Add Information</title>
  </head>
  <body>
    <form action="addinfo.php" method="POST">
      <table>
        <tr>
          <td>Name:</td>
          <td><input type="text" name="name"/></td>
          <td>Email:</td>
          <td><input type="text" name="email"/></td>
          <td>Mobile:</td>
          <td><input type="text" name="mobile"/></td>
        </tr>
      </table>
      <input type ="submit" value="Submit" />
    </form>
  </body>
</html>

III) Quick Start

IV) Have A Look

Comments