PDO fetch statement issues - php

I have the below PHP for my book keeping application. It uses PDO.
if (isset($_POST['lesson'])AND isset($_POST['page']))
{
try {
$options_pdo[PDO::ATTR_ERRMODE]=PDO::ERRMODE_EXCEPTION ;
$DB= new PDO('mysql:host=localhost;dbname=mydb','jamie','admin',$options_pdo);
$statement=$DB->query("SELECT data FROM teach_books where lesson=".$_POST['lesson']."AND page=".$_POST['page'] );
while($results = $statement->fetch()){
$results['data'];
echo "<br>";
}
} catch(Exception $e) {
die ('ERROR: '.$e->getMessage());
exit;
}
}
However when I run the code it displays the below error:
ERROR: 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 'page=dsas' at line 1
Could anybody help please?

A couple of things:
1) DO NOT INSERT RAW QUERY STRINGS:
This code is extremely suseptable to SQL Injection. PDO has a feature called 'prepared statements'. This is waht you should be using for you SQL queries. Do not just inject some POST parameters into the query string as the result will be a security hole. The quotes you have accidentally inserted into the query may well have come from a malicious user trying a SQL attack.
2) MISSING SPACE:
You have a missing space right before the AND. The parser does not know what to make of the term 2AND and so produces the error. The SQL by iteslf expands to something like.
SELECT data FROM teach_books where lesson=2AND page=24;
3) MISSING QUOTE MARKS:
If you were to use something like the above you will need to add some closing quote marks at the end of the query. You also need quotes around the string params that you give inside the select.
4) ECHO DATA:
You are not actually printing out anything in the loop. Simply having a statement sitting inside PHP will not print it out. You need echo command.
echo $results['data'];
5) ITERATE OVER OBJECT:
You do not need to keep calling fetch(), you could use fetchAll() and then iterate over that result set.
Really you should not call any "fetch" method unless you just need the rows in an array.
The result set object is iterable and can be looped over.
$statement->execute();
foreach ($statement as $row) {
...
}
6) TRY-CATCH:
You could probably remove the 'try-catch' code because what you are doing inside there is what the exception would do anyway.
Additionally I hope 'admin' is not your actual password.
Sorry to have kept adding to my answer. Just wanted to post the 6 points by themselves and then expand on them.
Hope that helps

Your SQL are wrong, try it:
$statement=$DB->query("SELECT data FROM teach_books where lesson='".$_POST['lesson']."'AND page='".$_POST['page']."'" );
You'r comparing string values, so you need to use '' on sql query.

ERROR: 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 'page=dsas' at line 1
The problem is probably becaus you didn't add quotes for the value:
".... page='".$_POST['page']."'"
Strings ALWAYS need quotes around them.

Related

Proper mySQL command for adding URLs

I'm having a problem when trying to add a URL to a mySQL database.
The string is a URL:
http://pbs.twimg.com/profile_images/1708867059/405000_10150426314376065_707061064_8645107_703731598_n_normal.jpg
The error I get is:
Error description: 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 '://pbs.twimg.com/profile_images/1708867059/405000_10150426314376065_707061064_86' at line 1
It seems as though it won't allow me to add a URL, I presume there is something wrong with some of the characters but I don't know what?
My SQL is:
INSERT INTO accounts (name,consumerkey,consumersecret,pic_url) VALUES ($twitterID,$consumerkey,$consumersecret,$picture_url)"
You cannot truly solve this kind of problem by adding a few characters (like ' or ") to your bespoke sql string!
Instead, get to know the real way to write sql in php (it's like a very badly kept secret), which is to use PDO statements. This will allow you to use placehoders like (:twitterID, :consumerKey, :consumerSecret, :pictureUrl) which will accept complex variables such as urls and any of the crap users send in much more gracefully.
In the long run, this will save you a lot of trouble and time.
You need to quote string values and any other character that SQL will complain about, in this case it's the colon; see further down below.
($twitterID,$consumerkey,$consumersecret,'$picture_url')
or
('".$twitterID."','".$consumerkey."','".$consumersecret."','".$picture_url."')
if you wish to quote all the values.
Sidenote: You can remove the quotes around the variables that are integers.
I.e.:
This based on, and without seeing how the rest of your code looks like:
$picture_url = "http://pbs.twimg.com/profile_images/1708867059/405000_10150426314376065_707061064_8645107_703731598_n_normal.jpg";
The error states that it is near : - near being just that, the colon.
...right syntax to use near '://pbs.twimg.com
^ right there
You can also use:
VALUES ($twitterID, $consumerkey, $consumersecret, '" .$dbcon->real_escape_string($picture_url) . "')";
$dbcon is an example of a DB connection variable and based on mysqli_ syntax.
Something you haven't stated as to which MySQL API you are using.
Plus, your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements.

Mysqli LIKE statement not working

I'm getting these weird errors, and I've been up and down the code, commenting and rewriting, and googling all the things.
Perhaps you guys will see what I'm not seeing:
$mysqli = new mysqli('host','login','passwd','db');
if($mysqli->connect_errno > 0){ die('Cannot connect: '. $mysqli->connect_error); }
// See if there is one term or multiple terms
if (count($search) == 1) {
// If one term, search for that
$like = $search[0];
$stmt = "SELECT
gsa_committees.id,
gsa_committees.committee,
gsa_committees.appointer,
gsa_committees.representatives,
gsa_committees.contact,
gsa_committees.category,
gsa_committees.attachments,
gsa_committees.labels,
gsa_committee_reports.committee,
gsa_committee_reports.title,
gsa_committee_reports.author,
gsa_committee_reports.link,
gsa_funds.id,
gsa_funds.fund,
gsa_funds.attachments,
gsa_funds.labels,
gsa_meeting_minutes.title,
gsa_meeting_minutes.link,
gsa_officers.office,
gsa_officers.dept,
gsa_officers.name,
gsa_representatives.program_dept,
gsa_representatives.representatives,
gsa_representatives.alternate
FROM
gsa_committees,
gsa_committee_reports,
gsa_funds,
gsa_meeting_minutes,
gsa_officers,
gsa_representatives
WHERE
(gsa_committees.committee LIKE $like) AND
gsa_committees.committee IS NOT NULL";
}
if(!$result = $mysqli->query($stmt)){ die('Bad query: '. $mysqli->error); }
This gives me this error message:
Bad query: 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 '%ARCHAC%) AND gsa_committees.committee IS NOT NULL' at line 34
Which I know isn't true. If I change that las part to just this:
WHERE gsa_committees.committee LIKE $like";
I get this error message:
Bad query: 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 '%ARCHAC%' at line 34
Everywhere I've looked, the string "%".search."%" seems to be the correct method, but my server doesn't seem to like it here.
Interesting side note: I have a different LIKE statement working on another page on the same server, this just won't work for some reason.
Thanks!
Try putting single quotes around your search term ($like variable).
for example: (gsa_committees.committee LIKE '$like')
You need to wrap the variable in quotes for like to work:
WHERE gsa_committees.committee LIKE '$like';
See reference documentation on String Comparison Function.
it looks like missing quotes:
"WHERE gsa_committees.committee LIKE '$like' ";
Ok, I got it. The answer on this post solved my issue:
MYSQLI SQL query over multiple tables fail
As soon as I assigned the tables t1,t2,etc and did INNER JOIN, the results came in as expected, with %$search% or $search.
Thanks all!

SQL error when deleting from MySQL

I am coming across a problem when deleting data from my SQL data. I have tried various versions of my statement but to no avail. Below is the error I am presented with and the statement I am using.
$sql = "DELETE FROM `saved_holidays` WHERE (subscriberID= $user AND title= $check_value)";
//connect to database then execute the SQL statement.
$db->exec($sql);
and the error message 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 '#xml119.com AND
title= Luxurious Jamaican holidays | 40% Discount On Accommodati' at
line 1
I can see that the correct data is being passed but the syntax is wrong. Can anyone help?
$check_value is a string, so you have to enclose it in ' in your query like this:
title = '$check_value'
For security purposes, you should also use mysql_real_escape_string on all string parameters you have. Or even better, use prepared statements: http://php.net/manual/en/pdo.prepared-statements.php
You need to put quotations around your variables. It doesn't like spaces.
Depending on the server you are using (MySQL or MSSQL) you have to use backticks, single quotes, or double quotes:
DELETE FROM saved_holidays WHERE (subscriberID="$user" AND title="$check_value")
Also, if you are using PDOs, you should consider using prepared statements:
$statment = $conn->prepare("DELETE FORM saved_holidays WHERE (subscriberID=? AND title=?)"); //$conn has to be your connection ceated by doing new PDO(...connection string...)
$statment->execute(array($user, $check_value));
Amit is correct your statement should look like this;
$sql = "DELETE FROM `saved_holidays` WHERE (subscriberID= '$user' AND title= '$check_value')";
the variable is a string so must be enclosed in single quotes.
This should then work for you.

update query problem

hi all i have a field "ammount" in mysql database which have "varchar(50)" type. When i insert data into that field e.g ammount= 4 kg its ok but when i update that field it gives me the following error.
Error in query: UPDATE ingredients SET ingredient_name='test recipe',ammount=4 gm where ingredient_id='59'. 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 'gm where ingredient_id='59'' at line 1
and my query is
$query="UPDATE ingredients SET ingredient_name='$ingredient',ammount=$ammount where ingredient_id='$ingredient_id'";
1) The correct spelling is "amount".
2) You should not be using variable interpolation like this for an SQL query. It is very unsafe. Use a prepared statement.
3) You didn't put quotes around $amount when defining $query, so they don't end up in the final substituted query string. Look closely at the error message: it shows you the query that SQL tried to process. Notice how it says ammount=4 gm? It can't handle that, because there are no quotes.
If you use prepared statements like you are supposed to, the quoting takes care of itself.
Your query has:
...,ammount=4 gm where...
which is incorrect. You need quotes around 4 gm.
Change
,ammount=$ammount where
to
,ammount='$ammount' where

PHP PDO prepared query refuses to execute properly - escaping problem?

I'm having a problem with a query prepared in PHP with PDO. The code:
$link = new PDO("mysql:dbname=$dbname;host=127.0.0.1",$username,$password);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $link->prepare("SELECT locality_name FROM :passedday GROUP BY locality_name ORDER BY locality_name DESC");
$query->bindParam(":passedday",$day); //Where day is, well, a day passed to the script elsewhere
$query->execute();
$result = $query->fetchAll();
$link = null;
//Do things with the $result.
The error message I am getting 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 ''05_26_09' GROUP BY locality_name ORDER BY locality_name DESC' at line 1
When I execute the query on the server directly, it returns the appropriate result set without any problem. Any ideas what I'm doing wrong?
TIA.
Edit:
$day is passed as a GET argument. So, http://127.0.0.1/day.php?day=05_26_09 leads to $day = $_GET['day'];.
If 05_26_09 is supposed to bet the table's name, then I guess you've an escaping problem. Is your local operating system different from the live server?
I don't think you can use bindValue()/bindParam() for something else than values (eg. table name, field name). So I'm a bit suprised, that it works on your local system.
PDO uses mysql's C-API for prepared statements.
http://dev.mysql.com/doc/refman/5.0/en/mysql-stmt-prepare.html says:The markers are legal only in certain places in SQL statements. [...] However, they are not allowed for identifiers (such as table or column names)As a rule of thumb I use: "if you can't wrap it in single-quotes in an ad-hoc query string you can't parametrize it in a prepared statement"

Categories