0

I now already create a table called' factory. In his table, there are two columns which is Fac_ID (Primary Key, Varchar) and Fac_Name (Varchar). Let say if I want to add a new factory. E.g F09, then the Fac_ID and Fac_Name also insert with F09.

I just only key in F09 at Fac_Name and after I click button 'add', it will save F09 at Fac_ID and Fac_Name. Below is my current PHP code

<?php
//including the database connection file
include_once("config.php");

if(isset($_POST['Submit'])) {   
$Fac_Name = $_POST['Fac_Name'];
$Fac_ID = $_POST['Fac_Name'];

// checking empty fields
if(empty($Fac_ID)) {

    if(empty($Fac_ID)) {
        echo "<font color='red'>Name field is empty.</font> 
   <br/>";
    }
    //link to the previous page
    echo "<br/><a href='javascript:self.history.back();'>Go 
   Back</a>";
} else { 
    // if all the fields are filled (not empty) 

    //insert data to database       
    $sql = "INSERT INTO users(Fac_Name, Fac_ID) VALUES(:Fac_Name, :Fac_Name)";
    $query = $conn->prepare($sql);

    $query->bindparam(':Fac_Name', $Fac_Name);
    $query->bindparam(':Fac_Name', $Fac_ID);
    $query->execute();


    //display success message
    echo "<font color='green'>Data added successfully.";
    echo "<br/><a href='index.php'>View Result</a>";
  }
 }
?>
Wan Dila
  • 1
  • 1
  • 8
  • 1
    Use different placeholders in your SQL statement: `$sql = "INSERT INTO users(Fac_Name, Fac_ID) VALUES(:Fac_Name, :Fac_ID)` – Zhorov Aug 15 '19 at 06:53

1 Answers1

-1

You cannot use the same bind parameter twice, so would suggest to do the following:

$sql = "INSERT INTO users(Fac_Name, Fac_ID) VALUES(:Fac_Name, :Fac_Id)";
    $query = $conn->prepare($sql);

    $query->bindparam(':Fac_Name', $Fac_Name);
    $query->bindparam(':Fac_Id', $Fac_ID);
    $query->execute();

It also makes more sense as the variable you put in is also called $Fac_ID.

Paul
  • 329
  • 1
  • 8