echoashu
echoashu

Reputation: 912

How to use logical operators in MYSQLI - PHP

I am writig a simple select statement, and since the connection object is mysqli, i cant use AND , && , OR like operators as it giving error

function getdata($value1,$value2)
{
global $conn;
$query = "SELECT id, name from users WHERE id!=$value1 && email==$value2 ";
$result = $conn->query($query);
}

This dosen't work :-(

Error: trying to get property of non object .. bla bla ..
Which means there something wrong with my sql statement, as when i try without logical operators it works, but of no use ofcourse .

Using prepare statement & bind parameters I referred to This thread SELECT in MYSQLI and tried with prepare statements.. but i'm doing something wrong i guess

$query=$conn->prepare("SELECT id, name from users WHERE id!=? && email==?");
    $query->bindParam("ss", $value1,$value2); // line 20 error points here
    $query->execute();

Error:

Call to a member function bindParam() on a non-object in /mydir/file.php line 20

P.S. var_dump($query); returns bool(false)

Upvotes: 0

Views: 3903

Answers (3)

jherran
jherran

Reputation: 3367

SELECT id, name FROM users WHERE id <> $value1 AND email = '$value2'"

<> and != is the same. AND and && is the same. You probably see AND and <> because is the standard in SQL. The issue was the equal operator is = instead of ==.

In the second part of your question, ss is wrong. d is for type double, s is for strings.

$query=$conn->prepare("SELECT id, name from users WHERE id != ? && email = ?");
$query->bind_param('ds', $value1, $value2);
$query->execute();

You can check types on php bind_param function help.

Upvotes: 1

Robb Harris
Robb Harris

Reputation: 1

replace && With AND,

replace == with "="

its returning false, but its because you have a mysql syntax error, you could also try turn on error reporting to see the exception

Upvotes: 0

fortune
fortune

Reputation: 3372

You have multiple problems in your query.

  1. Use ' = ' instead of ' == ' for assignments.
  2. In the first part You have assigned the query to variable $query, and running the query with variable $sql (wrong)

A modified code will look like this:

$query = "SELECT id, name from users WHERE id!='$value1' AND email='$value2'";
$result = $conn->query($query);

Upvotes: 1

Related Questions