简体   繁体   中英

mysqli_query() expects parameter 2 to be string

I am getting the error

Warning: mysqli_query() expects parameter 2 to be string, object given in C:\\Program Files (x86)\\EasyPHP-DevServer-13.1VC9\\data\\localweb\\login.php on line 10 Error:

On executing the query

<?php
$con=mysqli_connect("127.0.0.1","root","","forms");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  
  $sql=mysqli_query($con,"SELECT * FROM register Where username='$_POST[username]' AND password='$_POST[password]'");
  
  if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "login success";

mysqli_close($con);
?>

if(!mysqli_query($con,$sql)) isn't good as $sql is an object, not a string

$sql is an object as mysql_query

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

So you have not to do another mysqli_query , just modify your if in the following way

if(!$sql)
{
  //do something
}

This will work if you need to check query failures, otherwise it could return a mysqli_result even your query have returned 0 rows, so please pay attetion.

Replace :

if (!mysqli_query($con,$sql))

with

if($sql === FALSE)

By checking $sql is FALSE to prove the query is failed or not.

See : mysqli_query()

Try

  <?php
      $con=mysqli_connect("127.0.0.1","root","","forms");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  $sql="SELECT * FROM register Where username='$_POST[username]' AND password='$_POST[password]'";

  if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "login success";

mysqli_close($con);
?>

Because you can execute a query ,It should be a string. But in your code

$sql=mysqli_query()

Returns an object to $sql

Try this code:

  $sql="SELECT * FROM register Where username='".$_POST[username]."' AND password='."$_POST[password]."'";

  if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }

In your code you have already use the mysqli_query and you are passing the object of that in mysqli_query again.

$sql = 'SELECT * FROM register Where username=\'' . $_POST[username]. '\' AND password=\''. $_POST[password].'\' ';
$response=mysqli_query($con, $sql);
if (empty( $response ))
{
    die('Error: ' . mysqli_error($con));
}

Try this.

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