How to use logical operators in MYSQLI - PHP - 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)

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.

You have multiple problems in your query.
Use ' = ' instead of ' == ' for assignments.
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);

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

Related

How to concatenate equal sign and a variable such that result is usable in a mysql query of the type shown below?

I am running a mysql query based on several variables being posted from a bootstrap 4 form. I am struck at how to concatenate one of the posted variable 'prof' so as to use it for the query in two different scenarios: (1) When the user makes no choice and a NULL value is posted (2) When the user selects a particular profession and a specific value is posted. I need to concatenate the variable in a manner that I get the result of the type: = 'P01' and not just = P01 as it won't work in the mysql query: I am posting part of the code to show how I am handling the posted variable and the query itself. The query also includes some of the variables that i have been able to use successfully.
if(isset($_POST['prof_match']) && ($_POST['prof_match']) != 'NULL') {
$choice_prof = "= " . ($_POST['prof_match']); // Example P01 is Accountant
}else {
$choice_prof = 'IN(SELECT prof FROM profiles)';
}
// The query is as follows:
SELECT *
FROM profiles
WHERE age $choice_age
AND height $choice_ht
AND edn $choice_edn
AND prof $choice_prof;
The resulting string I get from the $choice_prof is quote = A01 unquote while what i need is quote = 'P01' unquote.
English not being my first language please ignore the syntax and grammatical mistakes. Thanks in anticipation.
As a means to kill 2 birds (solving your problem and sanitising your inputs) with one stone (using a prepared statement). You can do:
$parameters = [ $age, $height, $edn ]; //Actual values here, not values with condition
$sql = 'SELECT * FROM profiles WHERE age = ? AND height = ? AND edn = ? AND prof';
if(isset($_POST['prof_match']) && ($_POST['prof_match']) != 'NULL') {
$parameters[] = $_POST['prof_match'];
$sql .= '= ?';
}else {
$sql .= ' IN(SELECT prof FROM profiles)';
}
You can then execute this as a prepared statement.
PDO example:
$statement = $pdoObject->prepare($sql);
$result = $statement->execute($parameters);
It is similar in MySQLi as well.
Its very straight forward to use php variable and generate an sql string.
If you need quotation marks around your variable yo put them in your sql string like so:
$sql = "select * from table where some_column = '$variable'";
In your case, just put them in your string like this:
if ( !empty($_POST['prof_match']) ) {
$choice_prof = " = ' " . $_POST['prof_match'] . "'";
} else {
$choice_prof = 'IN(SELECT prof FROM profiles)';
}
SELECT *
FROM profiles
WHERE
age $choice_age AND
height $choice_ht AND
edn $choice_edn AND
prof $choice_prof;
For the empty() function refer to docs

Why can't I use COUNT (*) now?

I want to count everything in a Table to make Sites, I'm using this exact code a few times in my php file but now all the sudden is simply doesnt work anymore.. I'm driving crazy
$stmt = $mysqli->query("SELECT COUNT (*) AS Anzahl FROM '$tablename'");
$anzahl = $stmt->fetch_array();
$eintraege = $anzahl["Anzahl"];
$stmt->close();
$max_eintraege = 2;
if($eintraege <=2){
$seiten = 1;
}else{
$seiten = $eintraege / $max_eintraege;
$seiten +=1;
}
$start = $_GET["site"] * $max_eintraege - $max_eintraege;
if(!isset($_GET["site"])){
$start = 0;
}
All I get is:
Fatal error: Call to a member function fetch_array() on a non-object in /home/u144584875/public_html/index.php on line 2377
I just can't find out whats the problem, it works like 5 times in my Script but not now.
Everything is Set and right, whats the problem?
You should add some error handling, but the problem is this:
$stmt = $mysqli->query("SELECT COUNT (*) AS Anzahl FROM '$tablename'");
You are quoting your table name, it should be:
$stmt = $mysqli->query("SELECT COUNT (*) AS Anzahl FROM $tablename");
or
$stmt = $mysqli->query("SELECT COUNT (*) AS Anzahl FROM `$tablename`");
in case the table name is a reserved word in mysql, starts with a number, etc.
Edit: If you add this before you open your database connection (or anywhere above your current code...), mysqli will throw errors and tell you exactly what is wrong:
mysqli_report(MYSQLI_REPORT_STRICT);
// ...
$stmt = $mysqli->query("SELECT COUNT (*) AS Anzahl FROM `$tablename`");
// ...
Your SQL syntax is wrong. Table names should not be wrapped in single-quotes ('). Use backticks to escape them instead.
Update your SQL query as follows:
SELECT COUNT (*) AS Anzahl FROM `$tablename`
The documentation of mysqli::query says:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object.
Obviously, you have an error, and it returns FALSE. Use mysqli::$error to find out what it is.

unknown column in where clause, but I've already verified

I'm struggling with this simple line of SQL...
Running it keeps giving me the error: Error: Unknown column 'comics' in 'where clause'.
This would normally be an easy fix... just go check to make sure "comics" exists as an entry in column "table_name". But I've already checked that...
I don't see anything wrong with my SQL:
$sql = "SELECT ip FROM votes WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND table_name = $table AND imgid = $imgid";
EDIT:
Btw, I've already tried it with quotes:
$sql = "SELECT ip FROM votes WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND table_name = '$table' AND imgid = $imgid";
But that throws the error:
Fatal error: Call to undefined method mysqli_result::num_rows() in C:\wamp\www\HTwS\scripts\likecounter.php on line 40
Can anyone help?
Thanks!
The value of table_name is a string, and must therefore be single-quoted in the query. Failing to quote it as a string value, MySQL assumes that the supplied unquoted $table is a column identifier.
$sql = "SELECT ip FROM votes WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND table_name = '$table' AND imgid = $imgid";
//------------------------------------------------------------------------------------^^^^^^^^^
If $imgid is also a non-numeric value you'll need to quote that one as well.
We assume it has already been properly filtered against SQL injection, if it is the result of user input. I'll note, since the update includes MySQLi-specific code, that you really ought to be doing this as a prepared statement rather than a constructed string call to mysqli::query().
// Recommended to do this with a prepared statement.
$stmt = $mysqli->prepare("SELECT ip FROM votes WHERE ip = ? AND table_name = ? AND imgid = ?");
if ($stmt) {
$stmt->bind_param('ssi', $_SERVER['REMOTE_ADDR'], $table, $imgid);
$stmt->execute();
// Bind results, fetch, etc...
}
Edit after question update and comment:
Call to undefined method mysqli_result::num_rows()
The error message implies that you have attempted to access the MySQLi result property num_rows as a method call with () rather than a property. You should be using:
$result->num_rows
... instead of
$result->num_rows()

PHP PDO doesn't select data

When I get data without "prepare" and "execute", code is working fine. Example:
$this->db->query("select {$val} from {$table_name} where username={$username}")->fetch();
But this code always return False:
$this->db->prepare("select :val from :table_name where username = :username")
->execute(array(':username'=>$username,':val'=>$val,':table_name'=>$this->table_name));
HELP!:(
Thank you for your answers. Now my code is looking here:
$q=$this->db->prepare("select pass from nm_users where username = :username");
return $q->execute(array('username'=>$username));
Return value is True, but I can't get data from DB.
Don't try to use PDO as a fluent interface. You can't do this:
$db->prepare()->execute();
The reason is that fluent interfaces work only if the function is guaranteed to return an object that has in this case an execute method.
But prepare() returns false on error. The value false isn't an object, and doesn't have an execute() method.
You need to check for false after every prepare() and after every execute():
$stmt = $this->db->prepare("select :val from :table_name where username = :username");
if ($stmt === false) {
$err = $this->db->errorInfo();
error_log($err[2]);
}
$result = $stmt->execute(array(':username'=>$username,':val'=>$val,':table_name'=>$this->table_name));
if ($result === false) {
$err = $stmt->errorInfo();
error_log($err[2]);
}
If you do this, you'll find that an error was reported on your prepare():
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''user' where username = 'bill'' at line 1
The reason is that query parameters are only for constant values. You can't use them for table names, column names, SQL keywords, expressions, lists of values, etc.
I'm inferring that :val is also meant to be a dynamic column name, and that's not allowed either. But in that case, it won't result in an error, it'll just substitute a literal string with the value of $val for every row returned.
In other words, substituting the table name with a parameter is wrong because you can't do a query like SELECT * FROM 'user' (literal string, not table name), and that's how the parameter will act. It's simply invalid SQL.
But the dynamic column name will do a query like SELECT 'val' FROM ... and that's legal, but won't select from the column named val, it'll select the literal string constant 'val'.
Parameters cannot be set for table-names etc. and have to be set in the array without the colon:
$dbSelect=$db->prepare("select aField from aTable where username = :username")
$dbSelect->execute(array('username' => $username));
Replace aField and aTable with standard str_replace or sth similar.
The table name must be contained inside the query when you 'prepare' it, it cannot be added dynamically as the rest of the arguments. Therefore you have to use a combination of two strategies to finalize your query:
$stmnt=sprintf('select %1$s from %2$s where username=:username',
$val, $this->table_name);
if (FALSE===($query=$this->db->prepare($stmnt)))
exit('Buggy statement: '.$stmnt);
$query->execute(array(':username'=>$username));
Unfortunately this also means you have to take care that $this->table_name is escaped correctly!

PHP PDO Prepared Statement MySQL Count of Select where X LIKE

Using PHP v. 5.2.14 and PDO-MySQL extension.
I am new to prepared statements. Need to create a search form (so user input) and a working query of the "Select all X where X likeā€¦" variety.
Code and Results:
$sql = 'SELECT COUNT(*) as num_books from t_books where title LIKE :search_term';
// Later access as num_books
$prep = $dbh->prepare($sql);
$num = $prep->execute(array(':search_term' => '%'.$search_term. '%'));
$total=$num->fetchColumn();
Var dump of $prep:
object(PDOStatement)#2 (1) { ["queryString"]=> string(58) "SELECT COUNT(*) from t_books where title LIKE :search_term" }
Fatal error: Call to a member function fetchColumn() on a non-object
If $prep is an object, then $num should be an object. But it is boolean (true). What happened here?
But more importantly, how can I do a count?
I read Row count with PDO -. Suggestions there do not work for me because I need a Prepared Statement. Will have user input.
Thanks for your help.
PDOStatement::execute() only returns a boolean indicating success or failure, so your variable $num is not what you want to fetch from. By assigning the result to $num, you are not assigning the object $prep, but rather only the return value of the method call to execute() (TRUE).
Instead, fetchColumn() from $prep, your PDOStatement object.
$num = $prep->execute(array(':search_term' => '%'.$search_term. '%'));
if ($num) {
$total = $prep->fetchColumn();
}
Beyond that, your SQL should execute correctly and the one column it returns should contain the count you need.
In this case (especially since you are calling fetchColumn() with no argument) it doesn't matter, but for future readers, it is advisable to name the COUNT() aggregate with an alias that can then be used in an associative or object fetch:
$sql = 'SELECT COUNT(*) AS num_books from t_books where title LIKE :search_term';
// Later access as num_books

Categories