Henry Gathigira Henry Gathigira - 3 months ago 8
MySQL Question

How to escape mysql blank and duplicate data using php

I am using this code to send data to mysql database and its functioning well though users are sending blank data and duplicating too.

<?php
require "conn.php";
$lostidno = $_POST ["lostidno"];
$phonenol = $_POST ["phonenol"];

$mysql_qry = "INSERT INTO lostdb.lost (lostidno, phonenol) VALUES ('$lostidno', '$phonenol')";

if ($conn->query($mysql_qry) === TRUE)
{
echo "Information Recieved!";
}
else
echo "Sorry! An Error Occured:" . $mysql_qry . "br" . $conn->error;

$conn->close();

?>


How do I prevent this?

Answer

You can use trim function to remove spaces at the beginning and the ending of a string. After that you are able to check if the two parameters aren't empty:

<?php 
require "conn.php";
$lostidno = trim($_POST["lostidno"]);
$phonenol = trim($_POST["phonenol"]);

if(!empty($lostidno) && !empty($phonenol))
{
    $mysql_qry = "INSERT INTO lostdb.lost (lostidno, phonenol) VALUES ('$lostidno', '$phonenol')";  

    if ($conn->query($mysql_qry) === TRUE) {
        echo "Information Recieved!";
    }
    else {
        echo "Sorry! An Error Occured:" . $mysql_qry . "br" . $conn->error;
    }

    $conn->close();
}
?>

You should also have a look at this to prevent SQL injections.