用PHP中的bind_param()准备的状态

时间:2019-05-31 20:50:43

标签: php mysqli

有什么方法可以使用准备好的语句来编写此代码?

$sql = "SELECT * 
    FROM exercises 
    WHERE exercise_id IN (
        SELECT DISTINCT e.exercise_id 
        FROM users u,users_subjects us, exercises e 
        WHERE u.username='".$_SESSION['username']."' AND us.user_id_fk=u.id AND e.subjects=us.subject_id_fk
    );";
$result = $conn->query($sql);

我正在尝试这种方式,但是对于百分号“ IN”,我不确定该怎么做:

$stmt = $mysqli->prepare("SELECT * FROM exercises where exercise_id in (select distinct e.exercise_id from users u,users_subjects us, exercises e where u.username='".$_SESSION['username']."' and us.user_id_fk=u.id and e.subjects=us.subject_id_fk");
$stmt->bind_param("" );
$stmt->execute();
$stmt->close();

1 个答案:

答案 0 :(得分:0)

$username = $_SESSION['username'];

// use ?'s in prepare
$stmt = $mysqli->prepare("SELECT * FROM exercises where exercise_id in (select distinct e.exercise_id from users u,users_subjects us, exercises e where u.username=? and us.user_id_fk=u.id and e.subjects=us.subject_id_fk");

// then pass $username to bind_param()
$stmt->bind_param("s", $username);

然后其余的代码应该工作。我还建议您测试您的stmt命令以进行错误处理。它们都返回布尔值。

// use ?'s in prepare
$stmt = $mysqli->prepare("SELECT * FROM exercises where exercise_id in (select distinct e.exercise_id from users u,users_subjects us, exercises e where u.username='?' and us.user_id_fk=u.id and e.subjects=us.subject_id_fk");

if(!$stmt) echo "prepare failed: " . mysqli_error($conn);

bind_param()和execute()可以做同样的事情。