PDO 准备语句如何从数据库中 Select Where Id = Value or Tell = Value

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

我想 Select 使用学生 ID 或学生电话 table 命名为 'sms_students' 的一条记录

这是我的代码

    $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();

由于您调用了 execute 两次,因此它执行了两次,两次都使用了一组不完整的参数。不过这很容易解决:

$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();

尝试摆脱 single-use 变量,它们几乎总是不必要的,并且尝试引导名称精确匹配。看到 st_telstd_tell 在一起是不对劲的迹象。让您的代码就名称达成一致并坚持使用它们。