douyingzhan5905
douyingzhan5905
2013-08-28 21:42

sql准备语句获取结果到php变量[关闭]

已采纳

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongshuo9350 dongshuo9350 8年前

    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
    
    点赞 评论 复制链接分享

相关推荐