user3723240
user3723240

Reputation: 393

MySQLI prepared statement giving me strange results

I just found out about mysqli prepared statements and I tried to do one myself and I am getting some strange results:

<?php

    $mysqli = new mysqli("localhost", "root", "password", "database");
    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: " . $mysqli->connect_error;
    }

    $stmt = $mysqli->prepare("SELECT * FROM `media`");

    $stmt->execute();

    while ($row = $stmt->fetch()) {
        print_r($row);
    }

?>

this returns 111111111111 I am expecting data from the database, I did a print_r on $stmt and it returns this: mysqli_stmt Object ( [affected_rows] => -1 [insert_id] => 0 [num_rows] => 0 [param_count] => 0 [field_count] => 8 [errno] => 0 [error] => [sqlstate] => 00000 [id] => 1 )

Please help, how do I get data from my database instead of ton of 1s?

UPDATE

I tried the following:

<?php
$mysqli = new mysqli("localhost", "losanihomesweb", "8tsy2esk", "losanihomesweb");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($stmt = $mysqli->prepare("SELECT * FROM `in-the-press`")) {
    $stmt->execute();

    $stmt->bind_result($col1, $col2);

    while ($stmt->fetch()) {
        printf("%s %s\n", $col1, $col2);
    }

    $stmt->close();
}
$mysqli->close();

?>

I just get a blank white screen :( I do not understand how bind_results work, does it popular those variables on the fly?

Upvotes: 2

Views: 129

Answers (1)

sjagr
sjagr

Reputation: 16502

You're using the mysqli_stmt::fetch function incorrectly. Here's the approach you should take:

$stmt->execute();

$result = $stmt->get_result();

while ($row = $result->fetch_array()) {
    print_r($row);
}

Upvotes: 2

Related Questions