Search code examples
phpmysqlpostinsert-query

Why the data is not getting inserted into a MYSQL table?


I've created a form, database table, etc. on my local machine but the data is not getting inserted. If I run print the sql query and pasted it in PHP myadmin then it's inserting the values. Can anyone guide me in identifying the issue in not inserting the values into the databas? Following is my code:

Don't look the values of POST. They are coming fine. The issue must be in a PHP code that's what I think.

$hlr2RegQty=$_POST['txtHLR2Reg'];
$hlr2MicroQty=$_POST['txtHLR2Micro'];
$hlr2NanoQty=$_POST['txtHLR2Nano'];

$hlr3RegQty=$_POST['txtHLR3Reg'];
$hlr3MicroQty=$_POST['txtHLR3Micro'];
$hlr3NanoQty=$_POST['txtHLR3Nano'];
$count= $hlr1RegQty+$hlr2RegQty+$hlr3RegQty+$hlr1MicroQty+$hlr2MicroQty+$hlr3MicroQty+$hlr1NanoQty+$hlr2NanoQty+$hlr3NanoQty;

$conn=mysql_connect('localhost','root','');

mysql_select_db('prime_comm', $conn);

$query="INSERT INTO `prime_comm`.`newsim`(`Invoice No`, `HLR-1`, `HLR-2`, `HLR-3`, `HLR-4`, `MICRO-1`, `MICRO-2`, `MICRO-3`, `NANO-1`, `NANO-2`, `NANO-3`, `Total Count`, `Amount`, `VAT`) 
            VALUES( $invoiceNo, $hlr1RegQty,$hlr2RegQty,$hlr3RegQty,0,$hlr1MicroQty,$hlr2MicroQty,$hlr3MicroQty,$hlr1NanoQty,$hlr2NanoQty,$hlr3NanoQty,$count, 0,0)";
$flag = mysql_query($query);
?>

Solution

  • try putting single quotes around the variables;

    $query="INSERT INTO `prime_comm`.`newsim`(`Invoice No`, `HLR-1`, `HLR-2`, `HLR-3`, `HLR-4`, `MICRO-1`, `MICRO-2`, `MICRO-3`, `NANO-1`, `NANO-2`, `NANO-3`, `Total Count`, `Amount`, `VAT`) 
                VALUES( '$invoiceNo', '$hlr1RegQty', '$hlr2RegQty', '$hlr3RegQty', 0, '$hlr1MicroQty', '$hlr2MicroQty', '$hlr3MicroQty', '$hlr1NanoQty', '$hlr2NanoQty', '$hlr3NanoQty', '$count', 0,0)";
    

    Also, never assume post data is what you expect it to be, or clean/safe, as this is wide open to sql injection. I also recommend using mysqli_* functions over mysql_* functions, which are deprecated in the newer versions of PHP. Hope this helps :)