-3

I have below Query in my Php, it outputs result but at the same time giving an error mysqli::query() expects parameter 1 to be string what is wrong in below code

 $con = @mysqli_connect("localhost","$dbname","$dbpass","$dbuser");

 if (!$con)
 {
    die('Connect Error: ' . mysqli_connect_error());
 }

 $sql_uid=$con->prepare("SELECT id From $dtUsi Where mobile_number='$umobile' and user_type='$user_type'");

 $stmti = $con->query($sql_uid);

 while($rowi = $stmti->fetch_assoc()) {
 $ur_id= $rowi['id'];
 }
 echo $ur_id;
Mithu
  • 665
  • 1
  • 8
  • 38
  • You have already prepared the SQL (although not effectively as you still substitute all of the values in the SQL), you then need to `execute()` and not run `query()` – Nigel Ren Mar 29 '20 at 09:09

1 Answers1

1

You can't use prepare and query at the same time. You are giving $sql_uid to query function like it's a query string while it isn't. Use one the these approaches.

Either

$con = @mysqli_connect("localhost","$dbname","$dbpass","$dbuser");

 if (!$con)
 {
    die('Connect Error: ' . mysqli_connect_error());
 }

 $stmti=$con->query("SELECT id From $dtUsi Where mobile_number='$umobile' and user_type='$user_type'");

 while($rowi = $stmti->fetch_assoc()) {
 $ur_id= $rowi['id'];
 }
 echo $ur_id;

or

$con = @mysqli_connect("localhost","$dbname","$dbpass","$dbuser");

 if (!$con)
 {
    die('Connect Error: ' . mysqli_connect_error());
 }

 $stmti=$con->prepare("SELECT id From $dtUsi Where mobile_number='?' and user_type='?'");
 $stmt->bind_param("ss", $umobile, $user_type);

 $stmt->execute();
 while($rowi = $stmti->fetch_assoc()) {
 $ur_id= $rowi['id'];
 }
 echo $ur_id;

These links might be helpful:

PHP MySQL Prepared Statements

Select Data With MySQLi

  • 2
    Although it's useful to post both methods as it explains how `query()` should be used. It's always worth highlighting that using prepared statements properly is the way to do it (although you can't bind the table name in a prepared statement - https://stackoverflow.com/questions/11312737/can-i-parameterize-the-table-name-in-a-prepared-statement). – Nigel Ren Mar 29 '20 at 09:16
  • Yes you're right, thanks for comment I edited the table name. Of course yes. – Kamyar Mirzavaziri Mar 29 '20 at 09:27