PHP Json to MySql (opencart) [duplicate] - php

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 6 years ago.
I have small script that reeds cell from Database and anfter write to it. But it cause Error 1064.
It looks like this:
public function update($cart_id, $quantity) {
$this->db->query("UPDATE " . DB_PREFIX . "cart SET quantity = '" . (int)$quantity . "' WHERE cart_id = '" . (int)$cart_id . "' AND customer_id = '" . (int)$this->customer->getId() . "' AND session_id = '" . $this->db->escape($this->session->getId()) . "'");
//starts here
$cart_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "cart WHERE cart_id = '" . (int)$cart_id. "' AND session_id = '" . $this->db->escape($this->session->getId()) . "'");
$option= ($cart_query->row['option']);//success
$this->db->query("UPDATE " . DB_PREFIX . "cart SET option = '" . (string)$option . "' WHERE cart_id = '" . (int)$cart_id . "' AND customer_id = '" . (int)$this->customer->getId() . "' AND session_id = '" . $this->db->escape($this->session->getId()) . "'");//error
}
Thats What i see in log
2016-09-18 20:43:06 - PHP Notice: 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 'option = '{"options":{"product_id":"176","colors":["000000"],"print":{"colors":{' at line 1<br />Error No: 1064<br />UPDATE oc_cart SET option = '{"options":{"product_id":"176","colors":["000000"],"print":{"colors":{"front":["FF0000"]},"elements":{"front":[{"width":"52.9375","height":"25.0938","type":"text"}]}},"attributes":{"sizememos":"0"},"attribute":[["0","0"]],"print_type":"screen","quantity":"0","design":{"vectors":{"front":[{"type":"text","width":"54.9375px","height":"27.0938px","top":"151px","left":"86px","zIndex":"1","svg":"<svg width="54.9375" height="27.09375" viewBox="0 0 54.9375 27.09375" xmlns="http:\/\/www.w3.org\/2000\/svg" xmlns:xlink="http:\/\/www.w3.org\/1999\/xlink"><g id="0.15760551612925844"><text fill="#FF0000" stroke="none" stroke-width="0" stroke-linecap="round" stroke-linejoin="round" x="" y="" text-anchor="start" font-size="24px" font-family="arial" data-textcurve="1" data-itemzoom="1 1" data-textspacing="0"><textPath xmlns:xlink="http:\/\/www.w3.org\/1999\/xlink" xlink:href="http:\/\/138.68.62.219\/Buy-Hanes-T-shirt-PC61LS#textPath-item-0"><tspan dy="0">Hello<\/tspan><\/textPath><\/text><\/g><defs><path id="textPath-item-0" d="M 0.125 22.117808976867764 A 3093.9720937064453 3093.9720937064453 0 0 1 54.124314613414626 22.117808976867764"><\/path><\/defs><\/svg>","rotate":"0","text":"Hello","color":"#FF0000","fontFamily":"arial","align":"center","outlineC":"none","outlineW":"0"}]},"images":{"front":"cart-designes\/2016\/09\/\/cart-front-1474230421.png","back":"cart-designes\/2016\/09\/\/cart-back-1474230421.png"}},"fonts":""}}' WHERE cart_id = '387' AND customer_id = '0' AND session_id = 'kkfj9svfssdnsph8pf8i5atjn3' in /var/www/html/system/library/db/mysqli.php on line 41
What the reason? i'm just saving data that already in this cell.
option column is UTF-8 , LongText

Error 1064 points to a Syntax error on your MySQL query, It seems there are some quotations not well escaped on your JSON string, to prove that try to fix a value of option to some short value and call your function again.
The best practice is to use parameterized queries, these will save you from all the escaping tasks and most importantly offer some protection from SQL injection
This is just an example of how your query will look like:
$sql="UPDATE table SET opton=:option WHERE cart_id=:id AND customer_id=:customer_id and session_id=:session_id";
$parameters = array(
'option'=>$option,
'cart_id'=>$cart_id,
'customer_id'=>$customer_id,
'session_id'=>$session_id
);
$sql = $this->db->prepare($sql);
$sql->execute($parameters);
You can find more details on the official php documentation
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/manual/en/pdo.prepared-statements.php
Happy Coding friend:)

It doesn't work becouse of OPTION coz it's part of MySql syntaxis. This is work
$customer_id=(int)$this->customer->getId();
$session_id=$this->db->escape($this->session->getId());
$this->db->query("UPDATE " . DB_PREFIX . "cart SET `option` = '" . (int)$quantity . "' WHERE cart_id = '" . (int)$cart_id . "' AND customer_id = '" . $customer_id . "' AND session_id = '" . $session_id . "'");

Related

Changing Opencart Affiliate Variable Name from Tracking to Ref?

I'm working on an opencart website, and I was asked if it was possible to change the current affiliate link from reading mywebsite.com/currentproduct?tracking=tracking-code-here
to mywebsite.com/currentproduct?ref=tracking-code-here.
So pretty much the variable named to read ?ref=tracking-code instead of ?tracking=tracking-code-here
My guess is I would just change the the GET varible name from tracking to ref. However, Im not sure exactly where that is.
I found this code in the admin/model/customer/customer.php and was wondering if the part that reads tracking = '" . $this->db->escape($data['tracking']) . "', could just be changed to ref without breaking something important.
if ($data['affiliate']) {
$this->db->query("REPLACE INTO " . DB_PREFIX . "customer_affiliate SET customer_id = '" . (int)$customer_id . "', company = '" . $this->db->escape($data['company']) . "', website = '" . $this->db->escape($data['website']) . "', tracking = '" . $this->db->escape($data['tracking']) . "', commission = '" . (float)$data['commission'] . "', tax = '" . $this->db->escape($data['tax']) . "', payment = '" . $this->db->escape($data['payment']) . "', cheque = '" . $this->db->escape($data['cheque']) . "', paypal = '" . $this->db->escape($data['paypal']) . "', bank_name = '" . $this->db->escape($data['bank_name']) . "', bank_branch_number = '" . $this->db->escape($data['bank_branch_number']) . "', bank_swift_code = '" . $this->db->escape($data['bank_swift_code']) . "', bank_account_name = '" . $this->db->escape($data['bank_account_name']) . "', bank_account_number = '" . $this->db->escape($data['bank_account_number']) . "', status = '" . (int)$data['affiliate'] . "', date_added = NOW()");
}
}
I haven't coded in opencart for almost 5 years, and it's, unfortunately, starting to show. Any answer to this would be greatly appreciated! Thanks!
If you're looking to edit this in the OC code, you can look at the file /catalog/controller/startup/startup.php
Around line 126:
// Tracking Code
if (isset($this->request->get['tracking'])) {
setcookie('tracking', $this->request->get['tracking'], time() + 3600 * 24 * 1000, '/');
$this->db->query("UPDATE `" . DB_PREFIX . "marketing` SET clicks = (clicks + 1) WHERE code = '" . $this->db->escape($this->request->get['tracking']) . "'");
}
You can see that it's looking for the value set by the GET parameter tracking which seems to be what you're looking to change.
Fortunately it seems like OC relies on the cookie thereafter so you shouldn't have to worry about it anywhere else but testing will determine whether that is the case or not
I recommend to use .htaccess rewrite rule to rename URL parameter. here is the best solution for this
htaccess change url parameter

How to use the result of one query in another query (PHP/MySQL)

I have 2 tables (artist, cd) and I'm trying to use the result of the first query which returns an artID and make it equal to the artID in the 2nd table(cd) where artID is a foreign key but I'm not sure how to do it. Any help would be appreciated.
$strqueryID="SELECT artID FROM artist WHERE artName= '" . $_POST["category"] . "' ";
$resultsID=mysql_query ($strqueryID) or die(mysql_error());
$strqueryCD="INSERT INTO cd SET cdTitle='" . $_POST['title'] . "', artID='" . ??? . "' cdPrice='" . $_POST['price'] . "', cdGenre='" . $_POST['genre'] . "', cdNumTracks='" . $_POST['tracks'] . "'";
$resultsCD=mysql_query ($strqueryCD) or die(mysql_error());
You can use one single query, like this:
$strqueryCD="
INSERT INTO cd (cdTitle, artID, cdPrice, cdGenre, cdNumTracks)
VALUES(
'" . $_POST['title'] . "',
(SELECT artID FROM artist WHERE artName= '" . $_POST["category"] . "'),
'" . $_POST['price'] . "',
'" . $_POST['genre'] . "',
'" . $_POST['tracks'] . "')
";
also, google 'sqlinjection' before you continue
So, first thing's first - you shouldn't be using mysql_* functions now in 2017. I mean, really - they're actually even removed in later versions of PHP (7.0+). Refer to this StackOverflow post for more information.
Now, for your question at hand. Given the fact that you've searched for (and found) a given artID, you'll first have to get the actual "rows" from the $resultsID variable. In this example, we'll do it in a typical while loop:
while ($row = mysql_fetch_assoc($resultsID)) {
$strqueryCD="INSERT INTO cd SET cdTitle='" . $_POST['title'] . "', artID='" . $row['artID'] . "' cdPrice='" . $_POST['price'] . "', cdGenre='" . $_POST['genre'] . "', cdNumTracks='" . $_POST['tracks'] . "'";
$resultsCD=mysql_query ($strqueryCD) or die(mysql_error());
}
That should now loop over the artIDs that you've found in your first query and use them in the subsequent insert(s).
--
Disclaimer: I've disregarded the fact that user input is being passed straight into the query itself, as it's just too much "out of scope" for this post.

Updating Mysql table data with PHP

$updateSeats = mysql_query("UPDATE FORM_dateAndSeating SET NumberOfSeats = " . $removeSeatingNumber . " WHERE DATE = " . $revertToStandardDate);
In the code above I am trying to update the value within the MYSQL table.
When I echo the variables they show the data I am expecting, however the database is not being updated.
There is no error being returned either.
What are other possibilities for the sql not to update properly??
This will work:
$updateSeats = mysql_query("UPDATE FORM_dateAndSeating
SET NumberOfSeats = '" . $removeSeatingNumber . "'
WHERE DATE = '" . $revertToStandardDate . "'");
Long form:
$updateSeats = mysql_query("UPDATE FORM_dateAndSeating SET NumberOfSeats = '" . $removeSeatingNumber . "' WHERE DATE = '" . $revertToStandardDate . "'");
The variables need to be inside double quotes including single quotes
I.e.: '" . $removeSeatingNumber . "' WHERE DATE = '" . $revertToStandardDate . "'
-------^ --------------------------------------------^ -----------------------^ ----------------------------------------------^
Add apostrophes around your column values.

hacking an INSERT query to become a mysql UPDATE query

I am a MySQL noob and basically hacking an insert query to become an update query instead. So I am sure it's something simple with the grammar. But what's wrong with this?
// Save data
$mySQLQuery = 'update `'. $fl['mysql_table']. '` SET '. $fl['mysql_query']. "' WHERE speres = '" . mysql_real_escape_string($_POST['speres']);
$rs = #mysql_query($mySQLQuery);
the original INSERT query (working) was
// Save data
$mySQLQuery = 'INSERT INTO `'. $fl['mysql_table']. '` SET '. $fl['mysql_query'];
$rs = #mysql_query($mySQLQuery);
The data is generated here:
$fl['mysql_query'] = "menrecin = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_17'])) . "', menrecvej = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_18'])) . "', menrecser = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_19'])) . "', menrecud = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_20'])) . "', menresmor = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_22'])) . "', menresfro = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_23'])) . "', menresmid = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_24'])) . "', menresres = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_25'])) . "', menrumind = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_28'])) . "', menrumren = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_29'])) . "', menrumved = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_30'])) . "', tekip = '" . $_SERVER['REMOTE_ADDR'] . "', tekbro = '" . $_SERVER['HTTP_USER_AGENT'] . "', tektid = NOW()";
I have an entry with speres = 100525 in the database, so please try:
http://www.konferencer.nu/form/index.php?speres=100525
Good practices of troubleshooting dynamic SQL:
Look at the SQL, not the code that builds the SQL. In other words, echo out $mySQLQuery to see the final SQL, and most of the time you can see the error right away.
Don't suppress errors. Error-checking is helpful and necessary in any code.
It looks to me like your query ends up being:
update `tablename` SET ..., tektid = NOW()' WHERE speres = '...;
So you have a spurious quote after the NOW() and a missing quote at the end.
If you had checked for errors, you'd get something like this:
ERROR 1064 (42000): 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 speres = '...' at line 1
The quoting around the start of the WHERE clause looks odd:
UPDATE `...some table...` SET ...some query... 'WHERE speres = ' ... some criterion ...
Note the single quote placement. Maybe you want to remove the single quotes from inside the double quotes?
you query should look like
$mySQLQuery = 'update'. $fl['mysql_table'].'SET'. $fl['mysql_query'].'= <some value>' ' WHERE speres = '.mysql_real_escape_string($_POST['speres']);
$rs = #mysql_query($mySQLQuery);

UPDATE two rows - MySQL

I'm trying to update two rows in my database using a query (which is going to be run from a PHP script) and there is just one Condition (WHERE). What I've tried is:
$sql = 'UPDATE ' . CANNED_MESSAGES . "
SET canned_message_content = '" . $db->sql_escape($content) . "',
canned_message_title = '" . $db->sql_escape($title) . "'
WHERE id = '" . intval($id) . "'" ;
$db->sql_query($sql);
Can you tell me whats wrong with my query? :)
This may be due to Quotes mismatch. Please use this
$sql = "UPDATE '" . CANNED_MESSAGES ."'
SET canned_message_content = '" . $db->sql_escape($content) . "',
canned_message_title = '" . $db->sql_escape($title) . "'
WHERE id = '" . intval($id) . "' " ;
I highly doubt that two rows can have the same id column. Do they? If not, how could you update 2 rows by specifying a condition on a column with such a constraint?

Categories