0

I've been trying to get this fixed for the past two days with no luck. I'm switching to prepared statements for security reasons and I'm trying to display reviews. In the recent past, with prepared statements, I could only show one review, although there were many. After trying to figure it out, I switched to the old way (unsafe way) and it worked as it should. This is the code that worked (unsafe way):

$sql = "SELECT rate, title, date, review, recommend, helpful, username FROM rating INNER JOIN users ON rating.user_id = users.id";
$query = mysqli_query($db, $sql);
$statusnumrows = mysqli_num_rows($query);

// Gather data about parent pm's
if($statusnumrows > 0){
    while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
        $rate = $row["rate"];
        $title = $row["title"];
   }
}

//Info is displayed :) 
 $table1 .= '
            <li>
                <span style="display: inline-flex;" class="stars">'.$rate.'</span><span id="review_title">'.$title.'</span>
            </li>

I like having the variables assigned to the row, so I can echo the variables where needed.

Now, trying to get the same result in the prepared statements...that's another story. Here's one of the many attempts that don't work:

$sql = "SELECT rate, title, date, review, recommend, helpful, username FROM rating INNER JOIN users ON rating.user_id = users.id";
$stmt = $db->stmt_init();
if($stmt = $db->prepare($sql)){
    if($stmt->execute()){
        $result = $stmt->get_result();
        $a = $result->fetch_array(MYSQLI_ASSOC);
        echo $a;
    }else{
        echo "Didn't work.";
    }

   $table1 .= '
        <li>
            <span style="display: inline-flex;" class="stars">'.$rate.'</span><span id="review_title">'.$title.'</span>
        </li>

Does anyone know how I can show all of the reviews (as with the mysqli_fetch_array), but safer with the prepared statements?

Dominique
  • 1,080
  • 14
  • 29
Millica
  • 168
  • 12
  • You're taking a very strange approach to doing this. Why are you using `stmt_init`, then throwing that away? Just prepare, execute, and iterate as you would before. If you have `mysqli` exceptions turned on you won't need to be as paranoid about every operation. – tadman Dec 14 '16 at 18:52
  • That's because you're fetching only one row from the result set, see here: `$a = $result->fetch_array(MYSQLI_ASSOC);`. Loop through the result set to display all reviews. – Rajdeep Paul Dec 14 '16 at 18:54

1 Answers1

0

I use this way

$stmt = $db->prepare("SELECT name, xp FROM users");
if($stmt->execute()){
    $stmt->bind_result($name, $xp);
    while($stmt->fetch()){
        echo $name . ' has ' . $xp . ' xp.';
    }
}else{
    echo "Didn't work.";
}
Ec_
  • 66
  • 5