简体   繁体   中英

mysqli prepared statement without bind_param

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

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

I used prepared statement with bind_param earlier, but for now in the above code for first time I want to use prepared statement without binding parameters and I do not know how to select from table without using bind_param() . How to do that?

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());

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.

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.

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