PDO param is reading as a string and not an int [duplicate] - php

This question already has answers here:
How to apply bindValue method in LIMIT clause?
(11 answers)
Closed 5 years ago.
I want to pass a GET var into the query to set the OFFSET.
try {
$sql_offset = isset($_GET['offset']) ? $_GET['offset'] : 0;
$main_query = "SELECT * FROM Orders
LIMIT 150 OFFSET :offset";
$result = $db->prepare($main_query);
$result->bindParam(':offset', $sql_offset, PDO::PARAM_INT);
$result->execute();
} catch (Exception $e) {
$error = $e->getMessage();
echo "<h2>".$error."</h2>";
die();
}
The query fails and the error message received is:
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 ''450'' at line 2
Note: If I place 450 directly into the query it works fine.
It seems to me that the problem is that it is reading the param as a string '450' and not an int 450. I tried solving that with the PDO::PARAM_INT - didn't help. I parsed the value with (int)$sql_offset and int_val($sql_offset) and didn't help. Meaning, I was still receiving the same error message.
Question: am I right? Is the problem that it is seeing as a string? If so, how can I fix?
Or is there a different problem here?

Try to parse value in int then check:
$sql_offset = (int)(isset($_GET['offset']) ? $_GET['offset'] : 0);

Related

how to search a name that include apostrophe in SQL [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 4 years ago.
i want to search a title that include apostrophe in it.
i call the title from variable.
for example:
$mytitle = "Daddy's Home";
then i try to search it.
$apostrophe = $val;
$replacementsapostrophe = [
"'" => "''",
];
$newval = strtr($apostrophe, $replacementsapostrophe);
$query2 = $db->prepare ("SELECT category, id_master_post, master_post_name FROM `master_post` WHERE master_post_name = '$newval'");
$query2->execute();
$value2 = $query2->fetch();
Error given
Fatal error: Uncaught PDOException: 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 's Home 2'' at line 1 in
C:\xampp\htdocs\piratefiles\list.php:31 Stack trace: #0
C:\xampp\htdocs\piratefiles\list.php(31): PDOStatement->execute() #1
{main} thrown in C:\xampp\htdocs\piratefiles\list.php on line 31
im already try '%''%' still not working.
You should use prepared statements to avoid sql injection but to answer your question . An example;
try{
$db=new PDO(DSN,USER,PASS);
}catch(PDOException $e){
echo "couldn't connect cos of $e";
}
$sqlQuery = "SELECT category, id_master_post, master_post_name FROM `master_post` WHERE master_post_name = ? "
$prepared= $db->prepare($sqlQuery);
$prepared->execute($myTitle);
$resultObject = $prepared->fetchObject() ;

update query throws error in mysql [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 7 years ago.
I have a table named 'mostread' with 2 columns open_id(int) and read(int). Now the problem is if 'open_id' is already present in the table then i need to update the 'read' for every click else i need to insert a new row with 'open_id' retrieved from the controller and read=1. I am using the below code in my model which inserts a new row properly but the second time i click it throws an error as follows.
A Database Error Occurred
Error Number: 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 'read = read+1 WHERE open_id = '193'' at line 1
UPDATE mostread SET read = read+1 WHERE open_id = '193'
Filename: D:/Xampp/htdocs/opunletter/opunletter/application/models/Select.php
Line Number: 52
public function click($id)
{
$query = $this->db->query("SELECT * FROM mostread WHERE open_id='$id'");
$count= $query->num_rows();
if($count > 0) {
$this->db->set('read', 'read+1', FALSE);
$this->db->where('open_id', $id);
$this->db->update('mostread');
$data = array(
'open_id' => $id,
'read' => '1'
);
$this->db->insert('mostread', $data);
return TRUE;
}else{
return FALSE;
}
}
Try adding backticks arround read its a reserved keyword in mysql
$this->db->set('`read`', '`read` + 1', FALSE);

fatal error in php and mysql

i am having a problem with my script in php/mysql. here is the error displayed by the server:
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 'if exists (select * from notificacoes where uid in () order by id desc' at line 1' in C:\wamp\www\bigui\classes\Notificacoes.class.php on line 57
and here is my php code:
static function listar(){
$strIdAmigos = Amizade::$strIdAmigos;
$query = self::getConn()->query('select * from notificacoes where uid in ('.$strIdAmigos.') order by id desc');
return $query->fetchAll(PDO::FETCH_ASSOC);
}
my table in the mysql is empty, with no values. when i insert a value in it, the error goes away and everything is fine. any help?
If $strIdAmigos is empty, it causes syntax errors.
Before you execute this query, you should check the $strIdAmigos value whether it's empty or not to avoid this issue. Not to forget to escape the values if needed.
When you run your query with nothing in the variable $strIdAmigos, it will error out.
Try initializing and/or checking your variable, $strIdAmigos, before running your query:
$strIdAmigos = "";
if (empty($strIdAmigos)) {
/* Uh oh, throw an error */
} else {
$query = self::getConn()->query('select * from notificacoes where uid in ('.$strIdAmigos.') order by id desc');
}
Note that if $strIdAmigos = "0" , the empty($strIdAmigos) will still evaluate to true and, hence, will NOT run the query.

Erreur : SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;

when i try to execute an update statement i got the following error :
Erreur : 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 'Issy-les-Moulineaux ' where ssiphone_idstation=46' at line 1
my update statement is :
$bdd->exec("update ssiphone_stationdeservice set $cle='$element' where ssiphone_idstation=$id");
this is in a php code, THX in advance for your help :)
$cle and $element are in array, my code is :
foreach($table1 as $cle => $element)
{
$bdd->exec("update ssiphone_stationdeservice set $cle='$element' where ssiphone_idstation=$id");
}
now table1 is an array which contain the columns name of my table and its values :
$table1=array();
$table1['ssiphone_etatstation']=$etat;
$table1['ssiphone_commerce']=$commerce;
$table1['ssiphone_stationdelavage']=$lavage;
$table1['ssiphone_typescarburants']=$lescarburants;
$table1['ssiphone_joursdelasemaine']=$jourssemaines;
$table1['ssiphone_horaires ']=$this->horaires;
$table1['ssiphone_telephone ']=$telephone;
$table1['ssiphone_sensdecirculation ']=$this->sensDeCirculation;
$table1['ssiphone_adresse ']=$this->adresse;
$table1['ssiphone_ville']=$this->ville;
$table1['ssiphone_departement']=$this->departement;
$table1['ssiphone_nomstation ']=$this->nomStation;
Most likely your $cle variable isn't set, making the query look like:
... set ='Issy-les-moulineaux ' where ...
comment followup:
Change your code to look like this, then:
$query = "update ssiphone_stationdeservice set $cle='$element' where ssiphone_idstation=$id";
$result = $bdd->exec($query);
if ($result === FALSE) {
print_r($bdd->errorInfo());
die("Query: " . $query);
}
This way you have the complete query string in a variable you can inspect (e.g. by echoing out). Obviously there's something wrong with the query - but the mysql error string doesn't show the entire query, so you have to take measures to capture it.

PDO error message? [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
Here is a snippet of my code:
$qry = '
INSERT INTO non-existant-table (id, score)
SELECT id, 40
FROM another-non-existant-table
WHERE description LIKE "%:search_string%"
AND available = "yes"
ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
$sth->execute($data);
print_r($this->pdo->errorInfo());
This should give me an error because the tables don't even exist. All I get however is this:
Array ( [0] => 00000 )
How can I get a better description of the error so I can debug the issue?
Try this instead:
print_r($sth->errorInfo());
Add this before your prepare:
$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
This will change the PDO error reporting type and cause it to emit a warning whenever there is a PDO error. It should help you track it down, although your errorInfo should have bet set.
Old thread, but maybe my answer will help someone. I resolved by executing the query first, then setting an errors variable, then checking if that errors variable array is empty. see simplified example:
$field1 = 'foo';
$field2 = 'bar';
$insert_QUERY = $db->prepare("INSERT INTO table bogus(field1, field2) VALUES (:field1, :field2)");
$insert_QUERY->bindParam(':field1', $field1);
$insert_QUERY->bindParam(':field2', $field2);
$insert_QUERY->execute();
$databaseErrors = $insert_QUERY->errorInfo();
if( !empty($databaseErrors) ){
$errorInfo = print_r($databaseErrors, true); # true flag returns val rather than print
$errorLogMsg = "error info: $errorInfo"; # do what you wish with this var, write to log file etc...
/*
$errorLogMsg will return something like:
error info:
Array(
[0] => 42000
[1] => 1064
[2] => 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 'table bogus(field1, field2) VALUES ('bar', NULL)' at line 1
)
*/
} else {
# no SQL errors.
}
Maybe this post is too old but it may help as a suggestion for someone looking around on this :
Instead of using:
print_r($this->pdo->errorInfo());
Use PHP implode() function:
echo 'Error occurred:'.implode(":",$this->pdo->errorInfo());
This should print the error code, detailed error information etc. that you would usually get if you were using some SQL User interface.
Hope it helps
From the manual:
If the database server successfully
prepares the statement, PDO::prepare()
returns a PDOStatement object. If the
database server cannot successfully
prepare the statement, PDO::prepare()
returns FALSE or emits PDOException
(depending on error handling).
The prepare statement likely caused an error because the db would be unable to prepare the statement. Try testing for an error immediately after you prepare your query and before you execute it.
$qry = '
INSERT INTO non-existant-table (id, score)
SELECT id, 40
FROM another-non-existant-table
WHERE description LIKE "%:search_string%"
AND available = "yes"
ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
print_r($this->pdo->errorInfo());

Categories