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

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

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

Dynamic table name setting with PDO [duplicate]

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 7 years ago.
So I am quite new to using PDO and although I have to it to work using static settings I would like to be able to change the table name in a statement.
I had a look at this question here. and saw the highly up voted answer. So I attempted to recreate a simple version which would just dump all the information within a column.
Question: Why is my edited version of that persons example not work and return this error below.
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 '' at line 1' in
C:\xampp\htdocs\ *****\database.php:84 Stack trace: #0
C:\xampp\htdocs\ *****\database.php(84): PDOStatement->execute() #1
C:\xampp\htdocs\ *****\database.php(88): buildQuery(1) #2 {main}
thrown in C:\xampp\htdocs\ *****\database.php on line 84
The code from the example linked with my small alterations.
function buildQuery( $get_var )
{
switch($get_var)
{
case 1:
$tbl = `r16.7`;
break;
}
global $db;
$sql = "SELECT * FROM $tbl";
$stmt = $db->prepare($sql);
$stmt->execute();
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 1);
var_dump($result);
}
buildQuery(1);
Do not confuse PHP and SQL.
You just used SQL quotes in PHP. While you have to use SQL quotes in SQL.
Linked answer is now fixed, so, I am closing this as a duplicate.

PDO Find a needle in a haystack SQL statement

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 ! ? ! ?

Prepare synatax error SQLSTATE[42000] [duplicate]

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 9 years ago.
$tconn = new PDO('mysql:host='.WW_HST.';dbname='.WW_DB, WW_USR, WW_PS);
$res = $tconn->prepare('SELECT * FROM :tbl');
$res->execute(array(':tbl'=>"ugb"));
When I use this code to draw data from the 'ugb' table, I get the following error:
'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 ''ugb'' at line 1'
So it's correctly substituting :tbl for 'ugb' but whether I do a bind or just execute with an array, I always get an error. It works fine if I just do SELECT * FROM ugb though.
How can I correct this problem?
PDO does not allow you to set variables in FROM.
You only could add table name in query string.
I usually do by this way:
$allowedTables = array('first', 'second', 'third');
if(in_array($tblName, $allowedTables)) {
$$res = $tconn->prepare("SELECT * FROM $tblName");
}
I don't think that PDO will allow you to bind a parameter to the FROM statement. You could try manualy escaping the table name parameter and after that adding it to the query like this:
$table = "ugb";
$tconn = new PDO('mysql:host='.WW_HST.';dbname='.WW_DB, WW_USR, WW_PS);
$res = $tconn->prepare('SELECT * FROM '. $tconn->quote($table));
$res->execute();
Hope this helps.

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