Im trying to query my db of of MySQL on localhost. All i want to do is to see if the $name of a user is equal to any of the values from the 'userName' column in my db . If yes to say yes else no .
My code :
try
{
$conn = new PDO("mysql:host=$servername;dbname=datab", $username, $pass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully";
$sql = 'SELECT passWord FROM datab WHERE userName = '$name'';
$res = $conn->query($sql)
if($res>0)
{
echo "user found";
}
else
{
echo "not in db";
}
}
If you're using PDO, then it's also smart to use prepared statements so you avoid potential injections or unwanted errors.
Refer to the code:
try
{
$conn = new PDO("mysql:host=$servername;dbname=datab", $username, $pass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully";
$sql = 'SELECT passWord FROM datab WHERE userName = :name';
$stmt = $conn->prepare($sql); // Prepare
$stmt->bindValue(':name', $name);
$stmt->execute();
$result = $stmt->fetchAll();
if(count($result))
{
echo 'User found';
}
else
{
echo 'User not found';
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
i got it !! the error was that the dbname = datab but when writing the select clause it should have been
$sql = 'SELECT passWord FROM datab_a WHERE userName = :name';
since you access the table name datab_a not the database name datab ! Thanks anyways