Search code examples
phpmysqlpdoprepared-statement

PDO Prepared Statements How to Select From Database Where Id = Value or Tell = Value


I want to Select one record from a table Named 'sms_students' by using Student Id or Student Telephone

Here is My Code

    $student_rand_id=$_GET['std_rand'];
    $std_tell=$_GET['std_tell'];

    $view_student = $config->prepare("SELECT * FROM sms_students WHERE st_rand = :random_id || st_tel =: st_tel");
    $view_student->execute(['random_id' => $student_rand_id]); 
    $view_student->execute(['st_tel' => $std_tell]);

    $row = $view_student->fetch();

Solution

  • Since you call execute twice, this executes twice, both times with an incomplete set of arguments. It's an easy fix though:

    $view_student = $config->prepare("SELECT * FROM sms_students WHERE st_rand = :random_id OR st_tel = :st_tel");
    $view_student->execute(['random_id' => $_GET['std_rand'], 'st_tel' => $_GET['std_tell'] ]); 
    
    $row = $view_student->fetch();
    

    Try and get rid of single-use variables, they're almost always unnecessary, and do try and steer towards having names that match precisely. Seeing st_tel and std_tell together is a sign something's not quite right. Get your code to agree on names and stick with them.