I am writing a PHP+PDO function to check if the usernames and email addresses are already stored in the database. The SQL code returns an error(see bottom of post).
Similar posts recommend that I should change "reserved keywords", which I have checked and I have not used any from what I can see (SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO).
I tested the SQL string on phpMyAdmin and it works. the string looks as follows:
SELECT COUNT(Email) FROM `contactdetails` WHERE 'Email' = 'example@example.com'
PHP code:
<?php
function CheckAvailability($ValueToCheck, $FieldToCheck, $TableToCheck){
//Database connection.
$dbservername = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "db";
$db= new PDO("mysql:host=$dbservername; dbname=$dbname", $dbusername, $dbpassword);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//assigned 1 for value to be false
$count=1;
//SQL String
$result = $db->prepare("SELECT COUNT(:Field) FROM :Table WHERE :Field = :Value");
//Binding of parameters to SQL string
$result->bindParam(":Table", $TableToCheck, \PDO::PARAM_STR);
$result->bindParam(":Field", $FieldToCheck, \PDO::PARAM_STR);
$result->bindParam(":Value", $ValueToCheck, \PDO::PARAM_STR);
//String execution and data fetching
$result->execute();
$count = $result->fetchColumn();
//If the result of the string returns 0 return true if 1 or more return false.
if($count==0){return true;}else{return false;}
}?>
Result is as follows:
ERROR: 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 ''ContactDetails' WHERE 'Email' = 'example@gmail.com'' at line 1.
What am I doing wrong? Can I fix it? Is there a better way of doing this?