I am trying to run a prepared statement inside a prepared statement but got no success. Here is my code:
if ($stmt = $mysqli->prepare("SELECT author_id FROM posts")) {
$stmt->execute();
$stmt->bind_result($author_id);
while ($stmt->fetch()) {
if ($stmt2 = $mysqli->prepare("SELECT username FROM users WHERE id=? LIMIT 1")) {
$stmt2->bind_param("s", $author_id);
$stmt2->execute();
$stmt2->bind_result($username);
$stmt2->fetch();
$stmt2->close();
//showing username
echo $username;
}
}
$stmt->close();
}
I am getting author id
from a table and then from author id
I'm trying to get author's name from another table.
Can you please tell me any way to do this or any modification in this script can get it done.
Sometimes PHP section of this site makes my eyes aching. Not only question lacks very basic knowledge in every aspect of programming, but also answers promote terrible practices.
$conn->error
or by setting mysqli in exception mode. store_result()
And so whole code become
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$sql = "SELECT username FROM posts p, users u WHERE u.id=author_id";
$res = $mysqli->query($sql);
while ($row = mysqli_fetch_row()) {
echo $row[0];
}
Use another mysqli object for inner loop.
$mysqli = new mysqli(host, user, password, dbname);
$mysqli2 = new mysqli(host, user, password, dbname);
if ($stmt = $mysqli->prepare("SELECT author_id FROM posts")) {
$stmt->execute();
$stmt->bind_result($author_id);
while ($stmt->fetch()) {
if ($stmt2 = $mysqli2->prepare("SELECT username FROM users WHERE id=? LIMIT 1")) {
$stmt2->bind_param("s", $author_id);
$stmt2->execute();
$stmt2->bind_result($username);
$stmt2->fetch();
$stmt2->close();
//showing username
echo $username;
}
}
$stmt->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.