简体   繁体   中英

Value is not getting fetched from database using mysqli bind_result

I am trying to fetch the int that is found in my database table using mysqli. I then bind the result using bind_result() . However, when I try to use the value I simply get a 0. How can I deal with this?

My code is looking like this:

$sql = <<<EOF
        SELECT
        project_salary_amount
        FROM projects_set_salary
        WHERE project_id = ? ORDER BY project_salary_id DESC LIMIT 1
EOF;
    $stmt = $mysqli->prepare($sql) or die ("Feil i database<br>" . $sql . "<br><b>Feilmelding:</b> " . $mysqli->error);
    $stmt->bind_param("i", $project_id);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($dbb_salary_amount);
    $db_salary_amount = $dbb_salary_amount;
    $num_salary_results = $stmt->num_rows;
    $stmt->free_result();
    $stmt->close();

    if($num_salary_results == 0){
        $sql = <<<EOF
        INSERT INTO
        projects_set_salary (project_id)
        VALUES ($project_id)
EOF;
        $stmt = $mysqli->prepare($sql) or die ("Feil i database<br>" . $sql . "<br><b>Feilmelding:</b> " . $mysqli->error);
        $stmt->execute();
        $stmt->close();
        $db_salary_amount = 10;
        $html_set_salary = "";
        $html_set_salary .= "<form id=\"form_send_salary\"method=\"post\" action=\"create_set_salary.php\">\n";
        $html_set_salary .= "<input type=\"number\" name=\"set_salary\" value=\"$db_salary_amount\">";
    }
    else{
        $html_set_salary = "";
        $html_set_salary .= "<form id=\"form_send_salary\"method=\"post\" action=\"create_set_salary.php\">\n";
        $html_set_salary .= "<input type=\"number\" name=\"set_salary\" value=\"$db_salary_amount\">";
    }

Now, it does not display 10 inside the input box. Which means it does not execute the if statement. However, why am I not getting any results from $db_salary_amount ? I know I probably didn't have to change the variable from $db_salary_amount to $db_salary_amount . I was just trying to find out where the problem was.

You are missing a ->fetch() after bind_result()

$stmt->execute();
$stmt->store_result();
$stmt->bind_result($dbb_salary_amount);
$stmt->fetch(); // <--- missing this ->fetch()
$db_salary_amount = $dbb_salary_amount;

from the docs for ->bind_result() -> When mysqli_stmt_fetch() is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables var1, ....

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