Syntax error or access violation: 1064 ' brandname - php

I'm getting this error in my Magento script:
Product not added exception: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 's Secret'' at
line 1'
Some background info:
I have a PHP script running on a cron job to add and update products. It runs a while now, but I got just now this error. I think it's because the manufacturers name got an apostrophe in it. But I have no clue how to fix it.
Changing the manufacturer's name is not a option.
function addManufacture($pid,$men){
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$query = "SELECT manufacturers_id FROM p1_manufacturers WHERE m_name='".$men."'";
$lastid = $readConnection->fetchOne($query);
$write = Mage::getSingleton("core/resource")->getConnection("core_write");
if($lastid){}else{
$url = createUrl($men);
$query = "insert into p1_manufacturers (m_name,identifier,status) values ('".$men."','".$url."',1)";
$write->query($query);
$lastid = $write->lastInsertId();
}
$query1 = "insert into p1_manufacturers_products (manufacturers_id,product_id) values ('".$lastid."','".$pid."')";
$write->query($query1);
$query3 = "SELECT manufacturers_id FROM p1_manufacturers_store WHERE manufacturers_id='".$lastid."'";
$mid = $readConnection->fetchOne($query3);
if($mid){} else {
$query2 = "insert into p1_manufacturers_store (manufacturers_id,store_id) values ('".$lastid."',0)";
$write->query($query2);
}
}

Here is the problem:
$query = "SELECT manufacturers_id FROM p1_manufacturers WHERE m_name='".$men."'";
Replace that with:
$menEscaped = mysql_real_escape_string($men);
$query = "SELECT manufacturers_id FROM p1_manufacturers WHERE m_name='".$menEscaped."'";
For readability, I might be inclined to reformat it thus:
$menEscaped = mysql_real_escape_string($men);
$query = "
SELECT
manufacturers_id
FROM
p1_manufacturers
WHERE
m_name='{$menEscaped}'
";
The problem is you are not escaping your input variables, and if this comes from user input, you may find people injecting SQL of their own choice into your database. And that's generally not good!
Addendum: the above may work, but I've just spotted you are using a library called Mage. This being the case, you will need to find out how to escape strings using that library - it will be something like $write->escapeString($men).
As has been noted in the comments, it is even better if you can switch to paramerisation. You'll need to check if your library supports that.

Your problem is being caused by an unescaped single-quote appearing in your data, and creating a syntax error in the queries you are submitting to your database.
Unfortunately, your database access code is hidden in some class, so it's not immediately obvious what changes are required. However...
As an absolute minimum you should escape any user data before applying it to the database. For this function this means
$men = mysql_real_escape_string($men);
$pid = mysql_real_escape_string($pid);
added at the top of the function. I have assume you are using 'mysql()` in this code.
Watch the line $url = createUrl($men); as this will be affected by this change. You may need further modifications here, and createUrl() may need to be changed too.
You will need to make similar changes in every function that accesses your database.
If you are using mysqli() more work will be required as the arguments are different and this 'easy' fix won't work.
Ultimately you should look to rewrite your code to use prepared statements.
Your code is seriously vulnerable to attack. There is a lot of work here. Get to it!
Edit
Thanks to #halfer for spotting the use of Mage. Magento uses the Zend framework which in turn uses PDO objects. Delving into the code you can rewrite the functions to use prepared statements which will deal with your problem effectively. This answer has a fuller description. This is a better fix than I suggested above, but you still have a great deal of work to do.

Related

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

$q = "INSERT INTO subjects (menu_name, position, visible) VALUES ('{$mname}', {$pos}, {$vis}) ";
if(mysql_query($q)) {
header("Location: content.php");
}
else {
echo mysql_error();
}
Here, $mname is a string. $pos and $vis are integers.
Where is the mistake?
try to use only single quote to query variable rather pseudo(i think pseudo variable needs to be also quoted for query) like
$q= "INSERT INTO subjects (menu_name, position, visible) VALUES ('$mname', '$pos', '$vis')";
If you're going to use braces to try and prevent the greedy nature of variable expansion, you should use them properly.
The string "{$pos}", when $pos is 42, will give you "{42}", which is clearly not a valid integer in terms of your SQL statement. What you're looking for is instead:
${pos}
In this case, of course, you don't actually need the braces since the characters following the variable name cannot be part of a variable name - they are, respectively, ', , and ).
You only need to use braces when the following character could be part of a variable name. For example, consider:
$var = "pax";
$vara = "diablo";
In that case, $vara will give you diablo while ${var}a will give you paxa.
And I give you the same advice I seem to give weekly here :-) If you have a query that's not working, print it out! You'll find that the problem will usually become immediately obvious once you see the query in the final form you're passing to the DBMS.
And, as per best practices, I'll advise against using this method of creating queries. Anyone that's investigated SQL injection attacks (google for sql injection or, my favourite, little bobby tables) soon learns that they should use parameterised queries to prevent such attacks.
you are missing ' sign as the error says.
$q = "INSERT INTO subjects (menu_name, position, visible) VALUES ('$mname', '$pos', '$vis') ";
The value will be stored to table. Just make datatype to int in mysql table if you want it to be integer and make validation not to enter string while inserting.
You cannot name a column name whenever you run something through MySQL. One way to check is to run the query within HeidiSQL. MySQL functions will be highlighted blue, so you know if the column name becomes blue to not use it. Also; Here's a quick run of PDO to make things a little bit better; I'd suggest looking further into it as well.
public function MakeMenu() {
$q = <<<SQL
INSERT INTO subjects (menu_name,_position,visible)
VALUES(":menu_name","_position","visible")
SQL;
$resource = $this->db->prepare( $query );
$resource->execute( array (
'menu_name' => $_POST['menu_name'],
'_position' => $_POST['position'],
'visible' => $_POST['visible'],
));
}
To make things easy enough you can just make a call.php page as well. Make the calls.php page require your class page and add a hidden input to your form. IE
<input type=hidden" id="process" value="make_menu">
Then within the calls.php page add
if ( isset($_POST['process']) )
{
switch ($_POST['process'])
{
case 'make_menu':
$class->MakeMenu();
break;
I know this isn't just a quick answer, but I'm hoping you'll look further into what's happening here and move away from mysql functions. I have seen posts from people running IIS servers and not having any luck with any of the deprecated functions. Not sure how long it will be until Apache follows suite, but don't waste your time with something that's being deprecated as we speak.

php sql update issues

I am trying to update an SQL table with PHP.
I have a form that is submitted to the database - this is working fine.
I have retrieved the entries from the database and this is also working fine.
The problem I am having is when I try to update the database with additional information into the comment field (a 'cell' that already has information in).
Here is my SQL code. Can you please point me where the problem is?
There error I am getting is:
Error: 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 '= 36tWHERE id = 0' at line 1
My code is below :
$commy = $_POST['comment'];
$ident = $_POST['id'];
$sql = "UPDATE issuelog".
"SET comment = $commy".
"WHERE id = $ident";
I know there are security issues here but this is only for localhost use at the moment and only by my self as an example.
You don't need to concatenate and you should put quotes around values.
$sql = "UPDATE issuelog
SET comment = '$commy'
WHERE id = '$ident';";
Update: As others pointed out you need spaces, but this is the reason you don't need to concatenate. By closing each line and concatenating, you are removing spaces between them. Be sure you use prepared statements, because as you said, this is subject to injections.
$sql = "UPDATE issuelog".
" SET comment = $commy".
" WHERE id = $ident";
You need spaces - try echoing out your $sql - you will see SET and WHERE are merged with the previous words.

Simple PHP/MySQL Syntax error, told to "check manual?"

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 's website.
mysql_query("UPDATE Scholarships2 SET Requirements2 = '$requirements2'
WHERE scholarshipID = '$sID'")
or die("Insert Error1: ".mysql_error());
I read other Stackoverflow questions/answers on this subject but cannot find the reserved word I am using.
$sID is just an int while, $requirements2 is
$regex = '/<h4>Requirements<\/h4>([\n\n\n]|.)*?<\/table>/';
preg_match_all($regex,$data,$match);
$requirements2 = $match[0][0];
for the right syntax to use near 's website
This means it's complaining about the bit of your query that is 's website. "Where is that bit in your query?", I hear you ask.
Well, one of those variables in there contains something like Bob's website and the fact that you're blindly injecting that into your query will give you something like:
UPDATE Scholarships2 SET Requirements2 = 'Bob's website' ...
This particular query will not go down well with the SQL parser :-)
Other possibilities that don't immediately choke the parser will also not go down well with your customer base when little Bobby Tables steals or deletes your credit card database.
See this link for a fuller explanation and strategies for avoidance. In your case, that's probably going to involve mysql-real-escape-string.
In other words, you'll need something like:
mysql_query(
"UPDATE Scholarships2 SET Requirements2 = '" .
mysql_real_escape_string($requirements2) .
"' WHERE scholarshipID = '" .
mysql_real_escape_string($sID) .
"'"
) or die("Insert Error1: ".mysql_error());
As an aside, if $sID is just an integer (and not subject to injection attacks), you could probably remove the quotes from around it. I don't think it matters with MySQL (due to its "everything is a string" nature) but your query won't be portable to other DBMS'.
It depends on the values you have in your variables
Depending on the data type here is what you can do
$requirements2 = mysql_real_escape_string($requirements2); // escape string
$sID = (int)$sID; // force integer
the problem is if you have a string in your $requirement and it contains a single quote ' it will break your sql statement.
Here is something i often do to organize my code.
$sql = "UPDATE Scholarships2 SET Requirements2 = '%s'
WHERE scholarshipID =%d";
$sql = sprintf($sql,
mysql_real_escape_string($requirements2),
(int)$sID
);
Are you just taking form fields in from a POST or AJAX query? It sounds like you have a string containing 's website.
Make sure you run your code though mysqli_escape_string.
You need to escape whatever input you are getting in $requirements2
You can do this by
$req2=mysql_real_escape_string($requirements2);
mysql_query("UPDATE Scholarships2 SET Requirements2 = '$req2'
WHERE scholarshipID = '$sID'")
or die("Insert Error1: ".mysql_error());
This will escape any special characters like the apostrophe found in $requirements2
The problem is that your $requirements2 variable contains a single quote (the error message shows it when it says near 's website - presumably you're inserting something like welcome to Sal's website). When MySQL encounters this character, it's interpreting it as the termination of the entire string.
For example, if you substituted the phrase Welcome to Sal's website into your query where $requirements2 currently is, your query would look like this:
UPDATE Scholarships2 SET Requirements2 = 'Welcome to Sal's website'
As you can see, this results in a quoted string Welcome to Sal with the rest of the string hanging off the end not a part of anything. That's the part that the error is complaining about.
You really need to switch to PDO and prepared statements, otherwise you're leaving yourself wide open to these types of errors, including SQL injection which is a Very Bad Thing.
Prepared statements allow you to specify queries with placeholders where dynamic data can be placed. This extra data is then passed to PDO in a separate function where PDO/the database can determine the best way to sanitize it so that it doesn't get misinterpreted as part of the query structure itself.

$sql and $result - Reason for using both?

Just trying to improve the efficiency of my code so a simply question:
I see quite often people declare their SQL query using one var ($sql) and then putting the result into another ($result). Is there any reason people do this apart from keeping things slightly tidier? I presume it's slightler better just to put the SQL query straight into mysql_query(). But there may be some other reason people are hiding.
It normally to make debugging easier as you go: if something is wrong with the SQL query for any reason, you can simply print the contents of the $sql variable.
Also, the contents of SQL queries can get pretty long and it looks rather unreadable to have it inside a function call past a certain length.
Well it leads to cleaner coding if there is an error.
If you have an error on line 151 and 151 is:
mysql_fetch_array(mysql_query("SELECT * FROM something")); //where is the error
That is much harder to read then:
Error on line 150 and lines 149 - 151 are:
$sql = "SELECT * FROM something";
$result = mysql_query($sql); // ahh the error is here
mysql_fetch_array($result);
There isn't anything magical about it. Putting your SQL into a variable has a lot of upsides and very few downsides; the same cannot be said for passing your SQL query straight to the mysql_query function.
For starters... you're using mysql_query directly? Most developers are going to have wrapped such functions into some kind of database object/controller, or they're going to use PDO or the like. In any event, putting the SQL into a variable allows you to easily swap out the thing you're passing the SQL to. When I update code to switch database access methodology, it makes it easier if I am changing a line like mysql_query($sql) rather than mysql_query('SELECT .... SUPER LONG QUERY ...').
When debugging, one can simply echo($sql). If one wants to do a count query separate from the data query:
$sql = ' FROM table_name WHERE `some_field` = 1';
$count = db::getField('SELECT COUNT(`id`) '.$sql);
$page_worth = db::getRows('SELECT `id`, `name` '.$sql.' LIMIT '.$page.', '.$per_page);
And so on, and so on. It really does boil down to preference, but I find this approach much more flexible and rapidly adaptable/debuggable.

Error in MySQL update command. (in php)

Good Morning everyone,
I am using an update command in php to update data in mysql. This is my code:
$sql=mysql_query("UPDATE blpublication SET JournalName = '$_POST[journal]', AcceptanceDate = '$_POST[acceptancedate]', PublishedDate = '$_POST[publisheddate]', Comment = '$_POST[comment]'
WHERE JobNo = '$_POST[jobno]'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "record Updated";
It does updates the field but, it gives me the following error. And i can not figure it out why am i getting this error.
"Error: 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 '1' at line 1"
Can you help me in this
Best
Zeeshan
Can you tell us what the exactly output of $sql is? By the way, BIG security hole there. You should always escape query inputs namely:
$journal = mysql_real_escape_string($_POST['journal']);
$acceptance_date = mysql_real_escape_string($_POST['acceptancedate']);
$publish_date = mysql_real_escape_string($_POST['publisheddate']);
$comment = mysql_real_escape_string($_POST['comment']);
$job_no = intval($_POST['jobno']); // assuming jobNo is a number
$sql = <<<END
UPDATE blpublication
SET JournalName = '$journal',
AcceptanceDate = '$acceptance_date',
PublishedDate = '$publish_date',
Comment = '$comment'
WHERE JobNo = $jobno
END;
mysql_query($sql);
if (mysql_error()) {
die("Error executing query '$sql': " . mysql_error());
}
echo "record Updated";
I would sanitize your input first. This could lead to some very nasty errors such as what you are experincing and malicious attacks. Look up SQL Injection.
I think the problem is that you're running mysql_query twice. The first time it works and returns 1 (true), which you assign to $sql. Then you call mysql_query again, passing $sql (which equals 1). Of course "1" is not a valid SQL query, so you get the syntax error.
I wholeheartedly agree that you must sanitize those inputs!
Similar to the following post, i believe when you have any object or array syntax, you need to put in braces.
SET JournalName = '${_POST[journal]}'
edit: and yes, as others pointed out you are risking sql injection.
First of all, your code is prone to SQL injection, escape your POST values:
$journal = mysql_real_escape_string($_POST['journal']);
And to actually debug your query, we need the query itself. Add an echo() statement before the actual execution of the query and post the result, the POST values possibly contain some unexpected value.
Your general UPDATE syntax looks ok, except for the obvious injection possibilities, but you need to output $sql. One of your variables probably has a quote in it or some other issue like that....
Looking at the SQL UPDATE statement in your code, one thing leaps out at me. The table name is blpublication, are you maybe missing a 't', i.e. tblpublication?
Also you should really sanitise your input, otherwise you're going to be a victim of a SQL injection attack.
Try concatenating the $_POST values. Im not sure if including them without quoting the key is possible?
$sql= mysql_real_escape_string("UPDATE blpublication SET JournalName = '".$_POST['journal']."', AcceptanceDate = '".$_POST['acceptancedate']."', PublishedDate = '".$_POST['publisheddate']."', Comment = '".$_POST['comment']."'
WHERE JobNo = '".$_POST['jobno']."'");
$result = mysql_query($sql);
Note: mysql_* commands are depreciated. You should switch over to mysqli_*.

Categories