-3

I'm trying to convert mysqli to PDO but I'm getting one string empty, all the rest is fine.

My code mysqli:

$sql="SELECT uid FROM userprofile WHERE `name` = '$_POST[name]'";
$result=mysqli_query($con,$sql);
if($result&&mysqli_num_rows($result)>0){
$dwID = mysqli_fetch_array($result);
$time=time().'000';
$time1=time();
switch($_POST['t3']){
case ''.$mail_9.'':{
$b=bin2hex($_POST['type1'].','.$_POST['ts1'].','.$_POST['ts2']);
$b1=($_POST['type1'].','.$_POST['ts1'].','.$_POST['ts2']);
mysqli_query($con,"INSERT INTO mail (uid, toUser, title, contents, rewardId, itemIdFlag, status, type, rewardStatus, saveFlag, createTime, reply) VALUES (md5($time), '$dwID[0]','$_POST[titlegift]','$_POST[titlegift]', 0x$b,'1','0','13','0','0','$time','0')")or die('2');

And now I'm trying to converto to PDO like this:

$sql = "SELECT * from userprofile where `uid`='$_POST[name]'";
$query = $dbh2 -> prepare($sql);
$query->execute();
$result=$query->fetch(PDO::FETCH_OBJ);
$cnt=1; 

$uid = $query->$result;
$time = time().'000';
$gifttitle = $_POST['gifttitle'];
$b = bin2hex($_POST['type1'].','.$_POST['itemid'].','.$_POST['quantity']);

$sql1 = "INSERT INTO mail (uid, toUser, title, contents, rewardId, itemIdFlag, `status`, `type`, rewardStatus, saveFlag, creatTime, reply) VALUES (md5($time), '$uid', '$_POST[gifttitle]', '$_POST[gifttitle]', 0x$b, '1', '0', '13', '0', '0', '$time', '0')";
$query = $dbh2 -> prepare($sql1);
$query -> execute();

But when I run var_dump (SQL) it add all the fields and only $uid is empty.

Sorry for the code mysqli I know it is a messy.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • Don't try to develop a homebrew replacement to prepared statements and bound parameters. Just use the real thing. – Álvaro González Jul 01 '20 at 15:02
  • Does this answer your question? [How to include a PHP variable inside a MySQL statement](https://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-statement) – Dharman Jul 01 '20 at 15:04
  • If `$uid` is empty in `$sql1`, it must be empty in `$uid`. What does `var_dump($uid)` show? – Barmar Jul 01 '20 at 15:31

1 Answers1

0

This is wrong:

$uid = $query->$result;

$result is an object containing the row that was fetched from the table. It's not the name of a property of the $query object.

That should be:

$uid = $result->uid;

You should also use a prepared statement rather than substituting variables into the SQL string.

$sql1 = "INSERT INTO mail (uid, toUser, title, contents, rewardId, itemIdFlag, `status`, 
            `type`, rewardStatus, saveFlag, creatTime, reply) 
        VALUES (md5(:time), :uid, :gifttitle, :gifttitle, UNHEX(:rewardid), '1', '0', 
            '13', '0', '0', :time, '0')";
$query = $dbh2 -> prepare($sql1);
$query->bindParam(':time', $time);
$query->bindParam(':uid', $uid);
$query->bindParam(':rewardid', $b);
$query->bindParam(':gifttitle', $_POST['gifttitle']);
$query->execute();
Barmar
  • 741,623
  • 53
  • 500
  • 612