0

I have been getting an error with this code.

$Database = new Database('localhost','root','password','Db');    

$Statement = $Database->prepare("INSERT INTO User VALUES(:ID,:FirstName,:MiddleName:LastName,:RegisteredDate")

$Array_Bind = array(
'ID'=>$ID,
'FirstName'=>$FirstName,
'MIddeName'=>$MiddleName,
'LastName'=>$LastName
'RegisteredDate'=>$Date
)

foreach($Array_Bind AS $Key=>$value){
$Statement->bindParam(':' .$Key, $value)

}

if($Statement->execute()){
echo 'Successfully inserted into the database';


}else{
echo 'could not insert into database';
};

The following have been noted IF the $ID (PrimaryKey) is NOT by DEFAULT an AUTO-INCREMENTING value in the MySQL Database.

  1. ALL Fields except DATETIME Fields gets the value of the last element in the array when inserted into the database. i.e.

    ID = $LastName FirstName = $LastName MiddleName = $LastName LastName = $LastName RegisteredDate = $RegisteredDate

  2. The same error is outputted when bindValue is used.

So I ended up using

if($Statement->execute($Array_Bind)){
echo 'Successfully inserted into the database';


}else{
echo 'could not insert into database';
};

QUESTIONS

  1. It is recommended to use execute($array_Bind) assuming all data have been sanitize as against using bindParam or bindValue in this scenario?

  2. If Not is there a way to use bindParam or bindValue and arrays?

  3. Is this a bug or wrong coding architecture.

Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
Koofah
  • 79
  • 1
  • 7

2 Answers2

-1

I noticed you had a typo in the placeholder name. Don't know if this will sort the problem

$Statement = $Database->prepare("INSERT INTO User VALUES(:ID,:FirstName,:MiddleName:LastName,:RegisteredDate")

$Array_Bind = array(
'ID'=>$ID,
'FirstName'=>$FirstName,
'MIddeName'=>$MiddleName,
'LastName'=>$LastName
'RegisteredDate'=>$Date
)

You use a placeholder MIddeName but in your query you use MiddleName

Change this

'MIddeName'=>$MiddleName,

to this

'MiddleName'=>$MiddleName,
AdRock
  • 2,959
  • 10
  • 66
  • 106
-2

You need to check your premises. Then double check. Then check documentation.

  • with bindParam it is not a bug but essential feature.
  • with bindValue it never happen
  • of course passing array into execute() is preferred, due to overall sanity and amount of code compared to other methods.
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345