简体   繁体   中英

Convert "where in (query)" query to prepared statement in mysqli

I would like to know how to convert this query into a prepared statement. Do I have to convert both into a prepared statement (best case would be if you know the object oriented style, but the other one is okay, too...)? I have absolutely no clue on how to do that cause usually you fetch arrays immediatly in prepared statements so you can close them, don't you?

If there is no way to do so, do you have any approaches?

php:

$queryinquery = "SELECT `followed` FROM `follows` WHERE `follower` = '$username'";
$query1 = mysqli_query($db, "
SELECT * FROM `whatever` WHERE `id` IN ($queryinquery) ORDER BY `id` DESC LIMIT 10;
");

Try this one.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// prepare and bind
$stmt = $conn->prepare("SELECT * FROM `whatever` WHERE `id` IN (SELECT `followed` FROM `follows` WHERE `follower` = ?) ORDER BY `id` DESC LIMIT 10");
$stmt->bind_param("s", $username);

// set parameters and execute
$username= "John";
$stmt->execute();

// fetch your data code here

$stmt->close();
$conn->close();
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM