Question

What i want is to write this code with prepared statement:

if (mysqli_num_rows(mysqli_query($link,"select name from accounts where name='$username'"))==1)
        {
            // some actions
        }

Well, how to do that?

I know how to make a prepared "INSERT INTO" statement because I don't need to get the mysqli_query result into a php variable, but how to save a "SELECT" prepare statement to run mysqli_num_rows($result) right after?

EDIT: What I want to do is to execute a mysqli_query() with prepared statements while saving the result into a php $result variable. how to do that?

Was it helpful?

Solution

should never EVER chain database operations like that. You are assuming that the query will always succeed. This is BAD practice. Never assume success. Always assume the operations will fail, and treat success as a pleasant surprise.

Since you're daisy-chaining the DB calls like that, you never actually capture the result handle that mysqli_query() will return, so in effect you're running the query and then throwing away its results.

You should have something more like

$result = mysqli_query($link, "....") or die(mysqli_error());
if (mysqli_num_rows($result)) == 1) {
    $row = mysqli_fetch_assoc($result);
    $anem = $row['name'];
}

And unless you've taken steps not shown in this code, you are vulnerable to SQL injection attacks.

As for the prepared statement stuff:

$stmt = mysqli_prepare($link, 'SELECT ... WHERE name=?');
mysqli_stmt_bind_param($stmt, 's', $name);
mysqli_stmt_execute($stmt);

$rows = mysqli_stmt_num_rows($stmt);

mysqli_stmt_bind_result($stmt, $fetched_name);

mysqli_stmt_fetch($stmt); // $fetched_name now contains the name from the DB
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top