Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP mysqli oop fetch data from table error

i wanna fetch just one row from my table using PHP mysqli. it uses prepared statement, but i can't do that and my code shows nothing. what should i do?

<?php
require_once 'inc/db.inc.php';

$post_id = $_GET['id'];

$q = "SELECT post_id, post_name, post_title, post_content, post_author, post_short_des, post_tag, post_date FROM posts WHERE post_id=? LIMIT 1";
$stmt = $conn->prepare($q);
$stmt->bind_param('i', $post_id);
$stmt->execute();
$stmt->bind_result($post_id, $post_name, $post_title, $post_content, $post_author, $post_short_des, $post_tag, $post_date);
$stmt->fetch();

print_r($stmt);
like image 342
Amir Meimari Avatar asked Sep 08 '26 14:09

Amir Meimari


1 Answers

You need to bind the results, then fetch them. Since you have LIMIT 1, there's no need to loop anything, as you will only fetch one row anyways.

Note that instead of SELECT *, we now select one column, in this example we select from the column content (change this as it appears in your database table). It's important that the number of selected columns matches the variables you bind in mysqli_stmt_bind_result(). You can select more than one column, just separate by commas.

$post_id = $_GET['id'];

$q = "SELECT content FROM posts WHERE post_id=? LIMIT 1";
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt, 'i', $post_id);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $content);
mysqli_stmt_fetch($stmt);

if (mysqli_stmt_num_rows($stmt)) {
    echo $content;
} else {
    echo "No data";
}
  • http://php.net/mysqli-stmt.bind-result
  • http://php.net/mysqli-stmt.fetch

I wrote this from my phone, so there might be some mistakes. The documentation shows good examples though.

like image 189
Qirel Avatar answered Sep 10 '26 08:09

Qirel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!