mysqli prepared statement without bind_param

前端 未结 3 1489
予麋鹿
予麋鹿 2021-01-27 03:09

I have this code for selecting fname from the latest record on the user table.

$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$sdt=$mysqli-&g         


        
相关标签:
3条回答
  • 2021-01-27 03:40

    The answer ticked is open to SQL injection. What is the point of using a prepared statement and not correctly preparing the data. You should never just put a string in the query line. The point of a prepared statement is that it is prepared. Here is one example

    $query = "SELECT `Customer_ID`,`CompanyName` FROM `customers` WHERE `Customer_ID`=?";
    $stmt = $db->prepare($query);
    $stmt->bind_param('i',$_POST['ID']);
    $stmt->execute();
    $stmt->bind_result($id,$CompanyName);
    

    In Raffi's code you should do this

    $bla = $_POST['something'];
    $mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
    $stmt = $mysqli->prepare("SELECT `fname` FROM `user` WHERE `bla` = ? ORDER BY `id` DESC LIMIT 1");
    $stmt->bind_param('s',$_POST['something']);
    $stmt->execute();
    $stmt->bind_result($code);
    $stmt->fetch();
    echo $code;
    

    Please be aware I don't know if your post data is a string or an integer. If it was an integer you would put

    $stmt->bind_param('i',$_POST['something']);
    

    instead. I know you were saying without bind param, but trust me that is really really bad if you are taking in input from a page, and not preparing it correctly first.

    0 讨论(0)
  • 2021-01-27 03:50

    Actually, if i correct your script, it'll be like this:

    $mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
    $sdt = $mysqli->prepare('SELECT fname FROM user ORDER BY id DESC LIMIT 1');
    $sdt->execute();
    $sdt->bind_result($code);
    $sdt->fetch();
    echo $code;
    

    So, without bind_param, usually this works for me:

    $bla = $_POST['something'];
    $mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
    $stmt = $mysqli->prepare("SELECT fname FROM user WHERE bla = " . $bla . " ORDER BY id DESC LIMIT 1");
    $stmt->execute();
    $stmt->bind_result($code);
    $stmt->fetch();
    echo $code;
    

    That might help.

    0 讨论(0)
  • 2021-01-27 03:51

    If you want to execute it without bind, just use query

    $mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
    $res = $mysqli->query('SELECT fname FROM user ORDER BY id DESC LIMIT 1');
    echo current($res->fetch_row());
    
    0 讨论(0)
提交回复
热议问题