PDO Find a needle in a haystack SQL statement - php

I am using PDO, and am thrown an error when using the following code:
$stmt = $pdo->prepare("SELECT username FROM users WHERE
WHERE INSTR(`games`, '{$gameid}') > 0
");
$gameid = $gamedata['id'];
$stmt->execute(array(
':gameid'=>$gameid
));
$players = $stmt->fetch(PDO::FETCH_ASSOC);
Through looking at past answers this is supposed to work, however I am met with the following error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax
error or access violation: 1064 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 'WHERE
INSTR(`games`, 'crysis') > 0' at line 2' in C:\xampp\htdocs\gs\gamepage.php:19 Stack
trace: #0 C:\xampp\htdocs\gs\gamepage.php(19): PDOStatement->execute(Array) #1 {main}
thrown in C:\xampp\htdocs\gs\gamepage.php on line 19
It also appears it's grabbing 'games' as a literal and not the column
What am I doing wrong?

You have a double WHERE:
SELECT username FROM users WHERE
WHERE
You're also doing some funny things with $gameid, namely setting the variable after substitution, and binding an unused :gameid parameter. You also have a SQL injection vulnerability and should really use a parameter to pass $gameid instead of creating dynamic SQL.

You have the word games encased in "back quotes" and not "single quotes" like the {$gameid} variable is using. They are probably making the db engine assume it is a column name instead of text.

$stmt = $pdo->prepare('SELECT `username` FROM `users`
WHERE INSTR(`games`, :gameid) > 0;');
And you should use $stmt->bindValue() or $stmt->bindParameter() before executing the query.
This won't work if gameid is an ... INTEGER ! ? ! ?

Related

PHP Search MySQL database Fatal error [duplicate]

This question already has answers here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 4 years ago.
I wrote the query system with android studio and PHP.
My PHP code is as follows.Opened with a web browser but an error occurred.The error message is as follows
Notice: Undefined index: searchQuery in C:\xampp\htdocs\client\beetle_search.php on line 5
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near 'table 1 where
MATCH(name,scientific_name) AGAINST(NULL)' at line 1' in
C:\xampp\htdocs\client\beetle_search.php:9 Stack trace: #0
C:\xampp\htdocs\client\beetle_search.php(9): PDOStatement->execute()
1 {main} thrown in C:\xampp\htdocs\client\beetle_search.php on line 9
require_once('config.inc.php');
$search_query=$_POST['searchQuery'];
$sql = 'SELECT * from table 1 where MATCH(name,scientific_name) AGAINST(:search_query)';
$statement = $connection->prepare($sql);
$statement->bindParam(':search_query', $search_query, PDO::PARAM_STR);
$statement->execute();
if($statement->rowCount())
{
$row_all = $statement->fetchall(PDO::FETCH_ASSOC);
header('Content-type: application/json');
echo json_encode($row_all);
}
elseif(!$statement->rowCount())
{
echo "no rows";
}
Where did you write it wrong? thanks
You should add a table name in your query. Update your query
from
$sql = 'SELECT * from table 1 where MATCH(name,scientific_name) AGAINST(:search_query)';
to
$sql = 'SELECT * from table_name where MATCH(name,scientific_name) AGAINST(:search_query)';
Also, in order to use MATCH function, you must have the full text index on the column. Otherwise, you will get an error Can't find FULLTEXT index matching the column list'. The solution of this problem is given below...
Assuming you are using MyISAM engine, Execute:
ALTER TABLE table_name ADD FULLTEXT(name);
ALTER TABLE table_name ADD FULLTEXT(scientific_name);

SQL throwing Syntax Error when using LIKE with Parameters [duplicate]

This question already has answers here:
How do I create a PDO parameterized query with a LIKE statement?
(9 answers)
Closed 6 years ago.
I am using PDO with PHP to submit queries to my SQL server. I need to use the LIKE clause to check a username to ensure that it is allowed (eg; it does not contain any banned words), so I am using this SQL query...
SELECT * FROM `table` WHERE (`name` LIKE %?%);
I am then inserting the paramater with PDO later like this...
$statement->bindParam(1, $username)
When I try to run this, I get this error...
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%'dibdibs'%)' at line 1' in C:\xampp\htdocs\scripts\sql.php:57 Stack trace: #0 C:\xampp\htdocs\scripts\sql.php(57): PDOStatement->execute() #1 C:\xampp\htdocs\api\users.php(30): dibdibs\pdo->query('SELECT * FROM `...', Array) #2 {main} thrown in C:\xampp\htdocs\scripts\sql.php on line 5
The PDO code works fine for other queries, when I am using = instead of LIKE, but is is throwing the above error when I try to use the LIKE clause.
I have put my full code on Pastebin, if you need to check it. I am using GET to get data, as I am using this with AJAX (which is also working fine), but the username I have tried is 'dibdibs', which works fine in other queries.
Use This
U can use any of these two
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->execute(array('%value%'));
while ($results = $query->fetch())
{
echo $results['column'];
}
// without loop
$query = "SELECT * FROM tbl WHERE address LIKE ?";
$params = array("%$var1%");
$stmt = $handle->prepare($query);
$stmt->execute($params);

PDO Suggest refine results different than wildcard symbol

I am trying to make a PDO query to be searchable not only by the whole string but also by first letter or last letter anything like this. My question is what approach I have to take to achieve this goal.
My original idea was to use wildcard symbol and something like the following:
SELECT * FROM idname WHERE field LIKE CONCAT('%', :field , '%')
but this option for me is not working since I am getting an error:
Warning: Division by zero in**
Warning: Division by zero in E:\xampp\htdocs\search-contact.php on line 111
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 'LIMIT 0, 30' at line 1' in E:\xampp\htdocs\dolche\admin\class\pagination.php:451 Stack trace: #0 E:\xampp\htdocs\dolche\admin\class\pagination.php(451): PDOStatement->execute() #1 E:\xampp\htdocs\search-contact.php(125): pagination->execute() #2 {main} thrown in E:\xampp\htdocs\class\pagination.php on line 451
My code ad the moment is the following:
try
{
$paginate = new pagination($page, 'SELECT * FROM idname WHERE field LIKE :field', $options);
}
catch(paginationException $e)
{
echo $e;
exit();
}
$paginate->bindValue(':field', $_POST['field'] , PDO::PARAM_STR);
$paginate->execute();
Any suggestions are welcome ?
When using PDO you have to put the wildcards in the parameter, so it would look like:
$paginate->bindValue(':field', '%'.$_POST['field'].'%' , PDO::PARAM_STR);

using LEAST in SQL query when using PHP PDO Prepared statements

i am trying to use this PHP PDO prepared statement to run an SQL Query:
$stmt = $pdo_conn->prepare("SELECT *, LEAST(:col_list) as num FROM callplandata WHERE number LIKE :number HAVING num != 0 ");
$stmt->execute(array(':col_list' => implode(',',$column_list), ':number' => '%'.$_POST["prefix"].'%'));
but its showing this error message:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1582 Incorrect parameter count in the call to native function 'LEAST'' in /home/integra/public_html/included_pages/call_tarrif_search.php:62 Stack trace: #0 /home/integra/public_html/included_pages/call_tarrif_search.php(62): PDOStatement->execute(Array) #1 /home/integra/public_html/index.php(119): include('/home/integra/p...') #2 {main} thrown in /home/integra/public_html/included_pages/call_tarrif_search.php on line 62
what am i doing wrong?
LEAST accepts 2 or more values and returns the least one.
You're passing a single value, that is the roots of the error.
PS: and as soon as you haven't explained the original issue - there is nothing to add here. Please don't ask "how to fix it" because we have no idea what you're trying to achieve.

Why isn't PHP PDO protecting my query from injection?

I'm still in the progress of learning PDO fully, but I was kind of surprised when I checked this evening if it worked to SQL Inject the URL parameter, and to my surprise, it did work. So I started thinking; the posted values are supposed to be sanitized automatically using PDO - prepared statements, which means there must be something wrong with my SQL query, am I right?
I'm having a page that needs a GET variable in order to gather corresponding data from my database with that ID. I have created a function that includes preparing the query, and as well as executing it to simplify the coding process. The code I have written now looks like:
$request = $_GET['movie'];
$sql = "SELECT * FROM `movies` WHERE `url` = '$request'";
$db = new database;
$db->setDBC();
$process = $db->executeQuery($sql);
$cmd = $process->fetch(PDO::FETCH_NUM);
$title = $cmd[1];
And the PDO Exception I get is:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 ''21-31282 ''' at line 1' in C:\xampp\htdocs\filmvote\include\databaseClass.php:33 Stack trace: #0 C:\xampp\htdocs\filmvote\include\databaseClass.php(33): PDOStatement->execute() #1 C:\xampp\htdocs\filmvote\recension.php(9): databaseManagement->executeQuery('SELECT * FROM `...') #2 {main} thrown in C:\xampp\htdocs\filmvote\include\databaseClass.php on line 33
You get this kind of error when adding ' or 1-1 to the URL. What can I do about this? Really grateful for help.
the posted values are supposed to be sanitized automatically using PDO
Nope. Only if you use actual prepared statements like so:
$stmt = $dbh->prepare("SELECT * FROM `movies` WHERE `url` = ?");
if ($stmt->execute(array($_GET['movie']))) // <-- This sanitizes the value
{
// do stuff
}
will your the values you insert be automatically sanitized, and your query protected from SQL injection.
Otherwise, your SQL query will be executed like any old mysql_query(), and is vulnerable. PDO can not take a query and then automatically sanitize the vulnerable parts. That's not possible.
Try prepared statements:
$query = $db->prepare("SELECT * FROM `movies` WHERE url = ?");
$query->execute(array($request));
$result = $query->fetch(PDO::FETCH_ASSOC);

Categories