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

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()

Related

How do I use a variable in the WHERE condition of a MySQL query using a php variable? [duplicate]

This question already has answers here:
How to insert values in a PHP array to a MySQL table?
(2 answers)
Closed 5 years ago.
I'm using PHP session variable to track character ID's between two tables, characters and character_data_store.
The session ID definitely has the correct ID as I have had to print its value before it goes into the mySQL query.
For testing I selected a user I knew had a rapsheet and used
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.`key` = 'RapSheet'
AND character_data_store.character_id = '216'";
Obviously I can't use this for all users as I need to confirm the right one has been selected so thats where the session variable comes in.
I've tried using:
$correctPlayer = $_SESSION['selpid'];
echo $correctPlayer; #confirm it's the right id and then remove
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.'key' = 'RapSheet'
AND character_data_store.character_id = '$correctPlayer'";
I did some searching on SO and I found that int's need to have double quotes around them not single quotes, I tried that and had no luck but someone else suggested putting the session ID in exactly which I tried next:
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.'key' = 'RapSheet'
AND character_data_store.character_id = {$_SESSION['selpid']}";
Each time I do this I get mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given which SO tells me is because this operation results to false, I assume because it's not accepting the playerID from selpid or $correctPlayer?
It definitely works with the testing user where the playerID is inserted directly into the query. But I can't think of a way to do that since I need to match the playerID from table "characters" where the search is done against their first and last name and then pull the rapsheet data against the same playerID in table "character_data_store".
How do I use a variable in the WHERE condition of a MySQL query using a php variable?
You have obvious error in your code. You are missing quotes in {$_SESSION['selpid']} and you are using quotes in column name. Your query should be
$usersql = "SELECT * FROM character_data_store WHERE character_data_store.`key` = 'RapSheet' AND character_data_store.character_id = '{$_SESSION['selpid']}'";
You should not use quotes in column name, instead use backquotes(`) if you really need. I recommend prepared statements.
There are multiple ways to do this. A naive way to do this would be-
$usersql = "SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ".$correctPlayer;
But to avoid sql injections I would recommend you use bindparam function to bind paramaters in a statement.
$sql="SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ?";
if($stmt = $dbh->prepare($sql)){
$stmt->bindParam(1, $correctPlayer, PDO::PARAM_STR);
$ql = $stmt->execute() or die("ERROR: " . implode(":", $dbh->errorInfo()));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$result['data'] = $row;

How to use a Select with OR in PHP - odbc_prepare Issue

I'm using Microsoft SQL Server for this
function novogetListagemClientes($conn, $User){
$stmt = odbc_prepare($conn, 'SELECT * FROM users WHERE id IN ( SELECT idCliente FROM ligacoes WHERE ligacoes.idGest = ? OR idSocioG = ? OR idFunc = ? OR idColab = ? OR idSub = ? )');
$success = odbc_execute($stmt, array($User));
while($myRow = odbc_fetch_array($stmt))
{
$rows = $myRow;
}
if(empty($rows))
{
return array();
}
return utf8_converter($rows);
}
That's my PHP Function and I want that all the '?' have the same number, how should I fill that array ?
Right now when I use this query in my page it returns nothing, but in Navicat using query builder, returns what I expect.
Error I get: Warning: odbc_execute(): SQL error: [Microsoft][ODBC SQL Server Driver]Syntax error or access violation, SQL state 37000 in SQLDescribeParameter
If switch the '?' by a number that exists, I get the true value.
Update:If I switch the ? by '.$User.' and take of the array part it works
This answer is a summary of interactions in comments on the original question.
Having checked that the ODBC connection was fine (data is returned when the relevant parameter was "hardcoded"), I surmised that the problem was that the ODBC connection wasn't coping with the "Prepare" statement. This will likely have been because the parameters to be passed were not in the outermost WHERE clause and so prior to executing the query the connection couldn't work out the overall shape of the resulting data.
To get around this, we refactored the SQL code to remove the subquery and so put the parameter in the outermost WHERE clause.
The SQL therefore changed from
SELECT *
FROM users
WHERE id IN ( SELECT idCliente
FROM ligacoes
WHERE ? in (ligacoes.idGest, idSocioG, idFunc, idColab, idSub))
to
SELECT DISTINCT u.*
FROM users u
JOIN ligacoes l ON
u.id = l.idCliente
WHERE ? in (l.idGest, l.idSocioG, l.idFunc, l.idColab, l.idSub)
And with that change the code ran without complaint.

Write "Like" wildcard with ? keyword in Prepare Statement in MySQL, PHP [duplicate]

This does not work
$sql = 'SELECT * FROM `users` WHERE username LIKE \'%{?}%\' ';
Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in /home/rgero/public_html/php/searchadmins.php on line 1
This one doesn't work either
$sql = 'SELECT * FROM `users` WHERE username LIKE %{?}% ';
Fatal error: Wrong SQL: SELECT * FROM users WHERE username LIKE %{?}% Error: 0 in /home/rgero/public_html/php/searchadmins.php on line 1
How would I go about this? I'm trying to make a search for players function that updates the results as you're typing in the form, something like how google already shows answers while you're typing. I need for the username Admin , if you type dm, to show it already among other usernames that contain "dm". It should also be case insensitive
Try this
$likeVar = "%" . $yourParam . "%";
$stmt = $mysqli->prepare("SELECT * FROM REGISTRY where name LIKE ?");
$stmt->bind_param("s", $likeVar);
$stmt->execute();
you need to prepare the query using simply ? then you bind the param using bind_param.

Getting undefined index while fetching column value from mysql

I have the following code :
$sql = 'select count(*) from match as count where match_status != :status';
$query = $con->prepare($sql);
$query->bindValue(':status',LOST,PDO::PARAM_INT);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
if(!empty($row))
$row_count = $row['count'];
else
$row_count = 0;
I am getting Notice: Undefined index: count
What's the mistake?
You created the alias for the wrong thing. This should work:
SELECT count(*) as count FROM `match` WHERE match_status != :status
//^^^^^ Alias for 'count(*)' NOT for your table name
Also you have to put ` around keywords/Mysql reserved words e.g. match: http://dev.mysql.com/doc/refman/5.6/en/reserved-words.html
And if you turn on error mode then you also get an error for this, just put it right after your connection:
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'select count(*) from match as count where match_status != :status';
In this query, the as count won't do a thing, because you don't know what column you want to rename.
You need to place it directly after the original column name, so the database knows what column-name it needs to hide:
$sql = 'select count(*) as count from `match` where `match_status` != :status';
Because of this $row['count'] won't work, because you don't have a count-column, only a count(*) column.
N.B.: You're using a MySQL reserved word, being match and requires special attention in MySQL. Either rename it to something else, or use ticks around it, in order to escape it properly.

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!

Categories