-1

I don't think there is too much to explain here. The codes are self explanatory.

I have written this function

function checkDuplicate($table, $field, $value){
  global $pdo;
  $stmt = $pdo->prepare("SELECT COUNT(*) as cnt FROM :table WHERE :field = :value");
  $stmt-> bindValue(':table', $table);
  $stmt-> bindValue(':field', $field);
  $stmt-> bindValue(':value', $value);
  $stmt-> execute();
  $f = $stmt->fetch();

  if($f['cnt'] > 0){
    return 1;
  }else{
    return 0;
  }
}

I call it this way

if(checkDuplicate("members", "mem_uname", $uname) == 1){
  echo alert_danger("An account with this username already exists.");
  exit();
}

Calling returns this error

Warning: PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''members' WHERE 'mem_uname' = 'shrey'' at line 1 in E:\xampp\htdocs\buxhost\includes\functions.php on line 35

What is my mistake here? Why am I getting that error? As far as I have checked multiple times, I did not find anything visibly wrong in my codes.

1 Answers1

0

You can't set the table name as a parameter. You will have to pass it in the prepare statement.

function checkDuplicate($table, $field, $value){
  global $pdo;
  $stmt = $pdo->prepare("SELECT COUNT(*) as cnt FROM `$table` WHERE `$field`= :value");
  $stmt->bindValue(':value', $value);
  $stmt->execute();
  $f = $stmt->fetch();

  if($f['cnt'] > 0){
    return 1;
  }else{
    return 0;
  }
}

Edit: Cannot set field name as parameter.

kks21199
  • 1,116
  • 2
  • 10
  • 29