Prestashop - change product order in category fails - prestashop-1.6

In prestashop 1.6.1.4 I cannot change the order of products in category,
when I change in the admin (Products Catalog > Filter by category) it doesn't save to the DB.
After reload of the admin page the position numbers have wrong values, instead of 1...N it shows 0,0,0,3,4,5...

In classes/Product.php, change updatePosition to:
public function updatePosition($way, $position)
{
$sql = '
SELECT cp.`id_product`, cp.`position`, cp.`id_category`
FROM `' . _DB_PREFIX_ . 'category_product` cp
WHERE cp.`id_category` = ' . (int)Tools::getValue('id_category', 1) . '
ORDER BY cp.`position` ASC';
if (!$res = Db::getInstance()->executeS($sql
)) {
return false;
}
$loop_position = -1;
foreach ($res as $product) {
$loop_position++;
$product['position'] = $loop_position;
$sql3 = '
UPDATE `' . _DB_PREFIX_ . 'category_product`
SET `position` = ' . (int)$loop_position . '
WHERE `id_product` = ' . (int)$product['id_product'] . '
AND `id_category`=' . (int)$product['id_category'];
Db::getInstance()->execute($sql3);
$loop_position = $product['position'];
if ((int)$product['id_product'] == (int)$this->id) {
$moved_product = $product;
}
}
if (!isset($moved_product) || !isset($position))
return false;
// < and > statements rather than BETWEEN operator
// since BETWEEN is treated differently according to databases
$sql2 = '
UPDATE `' . _DB_PREFIX_ . 'category_product`
SET `position`= `position` ' . ($way ? '- 1' : '+ 1') . '
WHERE `position`
' . ($way
? '> ' . (int)$moved_product['position'] . ' AND `position` <= ' . (int)$position
: '< ' . (int)$moved_product['position'] . ' AND `position` >= ' . (int)$position) . '
AND `id_category`=' . (int)$moved_product['id_category'];
$sql3 = '
UPDATE `' . _DB_PREFIX_ . 'category_product`
SET `position` = ' . (int)$position . '
WHERE `id_product` = ' . (int)$moved_product['id_product'] . '
AND `id_category`=' . (int)$moved_product['id_category'];
return (Db::getInstance()->execute($sql2)
&& Db::getInstance()->execute($sql3));
}

Related

Lua script, Retrieve data form last month only

My current script collects data form the complete history but I would like to retrieve the total daily data over the last month only. Hopefully someone can help me to change my current script.
This is my current script:
--[[ -- sqliteDump.lua
Dumps daily data as csv file
requires sqlite3
install command on linux: sudo apt install sqlite3
install command on openwrt: opkg install sqlite3-cli
install command on synology: opt/bin/opkg install sqlite3-cli
History:
20191231 first public release
20200102 Add sudo chmod to make csvfile readable for all
20201023 Add option to use MultiMeter
]]--
return
{
on =
{
timer =
{
'at 09:33',
-- 'every month',
-- 'day=1',
-- 'at 00:00 on day=1, every month',
},
devices =
{
'sqlDump', -- test trigger can be ignored
},
},
logging =
{
level = domoticz.LOG_DEBUG, -- set to domoticz.LOG_ERROR when all is OK
marker = 'sqliteDump',
},
execute = function(dz)
-- ======================= enter you settings below this line ==================
local path = '/opt/domoticz/userdata/' -- full qualified path to your domoticz directory
local database = 'domoticz.db' -- database filename + extension
local sqlite = '/usr/bin/sqlite3' -- location of your sqlite3 tool; check with 'which sqlite3'
local csvFile = '/opt/domoticz/userdata/sqlite-csv/TEMPERATUREdomoticz2excel.csv'
-- set to '' for the types you don't need
local allTemperatures = '105' -- comma separated list of Temperature sensors to export
-- ======================= No modification needed below this line ==================
--local csvFile = csvFile .. "_" .. os.date("%Y-%m-%d",os.time()-24*60*60) .. ".csv"
local copy = 'safeCopy.db'
local baseCommand = sqlite .. ' -header -column ' .. copy
local closure = ' >> ' .. csvFile
local collects = {}
collects.Temperatures = 'SELECT a.Name Name, b.Date Date, b.Temp_Min min, b.Temp_Max max ' ..
' FROM DeviceStatus a , Temperature_Calendar b WHERE a.ID = b.DeviceRowID AND a.ID IN (' .. allTemperatures .. ') ORDER BY a.ID;'
local function osCommand(cmd)
dz.log('Executing Command: ' .. cmd,dz.LOG_DEBUG)
local fileHandle = assert(io.popen(cmd .. ' 2>&1 || echo ::ERROR::', 'r'))
local commandOutput = assert(fileHandle:read('*a'))
local returnTable = {fileHandle:close()}
if commandOutput:find '::ERROR::' then -- something went wrong
dz.log('Error ==>> ' .. tostring(commandOutput:match('^(.*)%s+::ERROR::') or ' ... but no error message ' ) ,dz.LOG_DEBUG)
else -- all is fine!!
dz.log('ReturnCode: ' .. returnTable[3] .. '\ncommandOutput:\n' .. commandOutput, dz.LOG_DEBUG)
end
return commandOutput,returnTable[3] -- rc[3] contains returnCode
end
local function sqliteDump()
local result, rc
if dz.utils.fileExists(path .. database) then
if dz.utils.fileExists(sqlite) then
result, rc = osCommand('cp ' .. path .. database .. ' ' .. copy)
if rc ~= 0 then return rc, result end
result, rc = osCommand('rm -f ' .. csvFile)
if rc ~= 0 then return rc, result end
for _, sql in pairs (collects) do
result, rc = osCommand(baseCommand .. ' "' .. sql .. '" ' .. closure)
if rc ~= 0 then return rc, result end
end
result, rc = osCommand('rm -f ' .. copy)
if rc ~= 0 then return rc, result end
result, rc = osCommand('chmod 777 ' .. csvFile)
if rc ~= 0 then return rc, result end
else
return -1,'sqlite3 not installed / not found'
end
else
return -1,'wrong path to database'
end
return 0, commandOutput
end
-- main program
local rc, result = sqliteDump()
if rc ~= 0 then dz.log(result,dz.LOG_ERROR) end
end
}
Many thanks for all the help!
I've tried adding the following (in bold), but to no avail:
collects.Temperatures = 'SELECT a.Name Name, b.Date Date, b.Temp_Min min, b.Temp_Max max ' .. 'FROM DeviceStatus a , Temperature_Calendar b WHERE a.ID = b.DeviceRowID AND a.ID IN (' .. allTemperatures .. ') ORDER BY a.ID' AND closed_at BETWEEN datetime(now, localtime, startofmonth, month=-1) AND datetime(now, localtime, startofmonth);'
'

RubyonRails MySQL select row column

please a need a little help. I'm using a simple query in rails. But I would like to selecting the query in HAML, something like in PHP. Is this possible in rails?
Thanks for help.
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
result_obj = ActiveRecord::Base.connection.execute("select * from kiosk ")
#rows = []
index = 0
result_obj.each do |row|
#rows[index] = row
index += 1
HAML:
##rows

Using dynamic table name in db2

Currently in my project development need of generating the record count based on certain criteria where the table names are stored in separate table.For instance say xx table stores the table name under the column name is tableInfo.
I've written the stored procedure in such a way that
DECLARE FGCURSOR CURSOR FOR SELECT tableInfo FROM xx WHERE col1='PO';
OPEN FGCURSOR;
FETCH FROM FGCURSOR INTO FILEGROUPMEM;
WHILE SQLCODE <> 100
DO
SET COUNTVal = 'SELECT COUNT(*) FROM ' || FILEGROUPMEM || ' WHERE ICLS= ' || CLASS || ' AND IVEN= ' || VENDOR || ' AND ISTY= ' || STYLE || ' AND ICLR= ' || COLOR || ' AND ISIZ= ' || SIZE ;
IF(COUNTVal >= 1) THEN
RETURN 1;
END IF;
FETCH FROM FGCURSOR INTO FILEGROUPMEM;
END WHILE;
CLOSE FGCURSOR;
Getting the exception on executing the procedure saying that
Message: [SQL0420] Character in CAST argument not valid. Cause . . . .
. : A character in the argument for the CAST function was not
correct. Recovery . . . : Change the result data type to one that
recognizes the characters in the CAST argument, or change the argument
to contain a valid representation of a value for the result data type.
Try the request again.
This line is not correct:
SET COUNTVal = 'SELECT COUNT(*) FROM ' || FILEGROUPMEM || ' WHERE ICLS= ' || CLASS || ' AND IVEN= ' || VENDOR || ' AND ISTY= ' || STYLE || ' AND ICLR= ' || COLOR || ' AND ISIZ= ' || SIZE ;
To use it the way you are trying, you'd have to use a static SQL statement like so
exec sql SELECT COUNT(*) INTO :COUNTVal
FROM MYTBL
WHERE ICLS= :CLASS AND IVEN= :VENDOR AND ISTY= :STYLE
AND ICLR= :COLOR AND ISIZ= :SIZE;
However, while a static statement can use variables, the table name in the FROM clause can not be variable.
Thus you have to prepare and use a dynamic statement. Unfortunately, SELECT INTO can not be used in a dynamic statement. VALUES INTO can be used dynamically.
set wSqlStmt = 'VALUES ( SELECT COUNT(*) FROM ' || FILEGROUPMEM
|| ' WHERE ICLS= ' || CLASS || ' AND IVEN= '
|| VENDOR || ' AND ISTY= ' || STYLE || ' AND ICLR= '
|| COLOR || ' AND ISIZ= ' || SIZE ||') INTO ?';
exec sql PREPARE S1 FROM :wSqlStmt;
exec sql EXECUTE S1 USING COUNTVal;
WARNING the above code could be subject to SQL Injection attacks. To protect against SQL injection, dynamic SQL should use parameter markers instead of concatenating input directly to a statement. While you can't use a parameter marker for the table name, you can for the rest of the variables like so:
set wSqlStmt = 'VALUES ( SELECT COUNT(*) FROM ' || FILEGROUPMEM
|| ' WHERE ICLS= ? AND IVEN= ? '
|| ' AND ISTY= ? AND ICLR= ?'
|| ' AND ISIZ= ?) INTO ?';
exec SQL PREPARE S1 FROM :wSqlStmt;
exec SQL EXECUTE S1 USING :CLASS, :VENDOR, :STYLE, :COLOR, :SIZE, :COUNTVal;

ZF2: How can i use brackets to group in mysql where in DB\SQL?

I have the following code:
$select = new Select();
$select->from($this->table);
$select->columns(array('id', 'refNumberOrder', 'dateOrder', 'kontragent', 'airOperator', 'aircraft', 'status'));
...
if ($object->customer != '') {
$select->where->like('library_kontragent.short_name', $object->customer . '%');
}
if ($object->airOperator != '') {
$select->where->like('library_air_operator.short_name', $object->airOperator . '%');
}
if ($object->aircraft != '') {
$select->where->like('library_aircraft_type.name', $object->aircraft . '%');
}
$select->order('dateOrder ' . Select::ORDER_DESCENDING);
//\Zend\Debug\Debug::dump($select->getSqlString());
$resultSet = $this->selectWith($select);
$resultSet->buffer();
This makes the next line:
// MySQL result
WHERE "library_kontragent"."short_name" LIKE 'test%'
AND "library_air_operator"."short_name" LIKE 'test%'
AND "library_aircraft_type"."name" LIKE 'test%'
ORDER BY "dateOrder" DESC"
How I can get next a string?
// MySQL result
WHERE ("library_kontragent"."short_name" LIKE 'test%' OR "library_kontragent"."long_name" LIKE 'test%')
AND "library_air_operator"."short_name" LIKE 'test%'
AND "library_aircraft_type"."name" LIKE 'test%'
ORDER BY "dateOrder" DESC"
Check this example by Ralph Schindler. There's a NEST and UNNEST "operator" within Zend\Db\Sql\Where

"Error: attempt to index local 'self' (a nil value)" in string.split function

Quick facts, I got this function from http://lua-users.org/wiki/SplitJoin at the very bottom, and am attempting to use it in the Corona SDK, though I doubt that's important.
function string:split(sSeparator, nMax, bRegexp)
assert(sSeparator ~= '')
assert(nMax == nil or nMax >= 1)
local aRecord = {}
if self:len() > 0 then
local bPlain = not bRegexp
nMax = nMax or -1
local nField=1 nStart=1
local nFirst,nLast = self:find(sSeparator, nStart, bPlain)
while nFirst and nMax ~= 0 do
aRecord[nField] = self:sub(nStart, nFirst-1)
nField = nField+1
nStart = nLast+1
nFirst,nLast = self:find(sSeparator, nStart, bPlain)
nMax = nMax-1
end
aRecord[nField] = self:sub(nStart)
end
return aRecord
end
The input: "1316982303 Searching server"
msglist = string.split(msg, ' ')
Gives me the error in the title. Any ideas? I'm fairly certain it's just the function is out of date.
Edit: lots more code
Here's some more from the main.lua file:
multiplayer = pubnub.new({
publish_key = "demo",
subscribe_key = "demo",
secret_key = nil,
ssl = nil, -- ENABLE SSL?
origin = "pubsub.pubnub.com" -- PUBNUB CLOUD ORIGIN
})
multiplayer:subscribe({
channel = "MBPocketChange",
callback = function(msg)
-- MESSAGE RECEIVED!!!
print (msg)
msglist = string.split(msg, ' ')
local recipient = msglist[0] --Get the value
table.remove(msglist, 0) --Remove the value from the table.
local cmdarg = msglist[0]
table.remove(msglist, 0)
arglist = string.split(cmdarg, ',')
local command = arglist[0]
table.remove(arglist, 0)
argCount = 1
while #arglist > 0 do
argname = "arg" .. argCount
_G[argname] = arglist[0]
table.remove(arglist, 0)
argCount = argCount + 1
end
Server.py:
This is the multiplayer server that sends the necessary info to clients.
import sys
import tornado
import os
from Pubnub import Pubnub
## Initiat Class
pubnub = Pubnub( 'demo', 'demo', None, False )
## Subscribe Example
def receive(message) :
test = str(message)
msglist = test.split()
recipient = msglist.pop(0)
msg = msglist.pop(0)
id = msglist.pop(0)
if id != "server":
print id
print msg
commandHandler(msg,id)
return True
def commandHandler(cmd,id):
global needOp
needOp = False
global matchListing
if server is True:
cmdArgList = cmd.split(',')
cmd = cmdArgList.pop(0)
while len(cmdArgList) > 0:
argument = 1
locals()["arg" + str(argument)] = cmdArgList.pop(0)
argument += 1
if cmd == "Seeking":
if needOp != False and needOp != id:
needOp = str(needOp)
id = str(id)
pubnub.publish({
'channel' : 'MBPocketChange',
#Message order is, and should remain:
#----------Recipient, Command,Arguments, Sender
'message' : needOp + " FoundOp," + id + " server"
})
print ("Attempting to match " + id + " with " + needOp + ".")
needOp = False
matchListing[needOp] = id
else:
needOp = id
pubnub.publish({
'channel' : 'MBPocketChange',
#Message order is, and should remain:
#----------Recipient, Command,Arguments, Sender
'message' : id + ' Searching server'
})
print "Finding a match for: " + id
elif cmd == "Confirm":
if matchListing[id] == arg1:
pubnub.publish({
'channel' : 'MBPocketChange',
#Message order is, and should remain:
#----------Recipient, Command,Arguments, Sender
'message' : arg1 + ' FoundCOp,' + id + ' server'
})
matchListing[arg1] = id
else:
pass #Cheater.
elif cmd == "SConfirm":
if matchListing[id] == arg1 and matchListing[arg1] == id:
os.system('python server.py MBPocketChange' + arg1)
#Here, the argument tells both players what room to join.
#The room is created from the first player's ID.
pubnub.publish({
'channel' : 'MBPocketChange',
#Message order is, and should remain:
#----------Recipient, Command,Arguments, Sender
'message' : id + ' GameStart,' + arg1 + ' server'
})
pubnub.publish({
'channel' : 'MBPocketChange',
#Message order is, and should remain:
#----------Recipient, Command,Arguments, Sender
'message' : arg1 + ' GameStart,' + arg1 + ' server'
})
else:
pass #hax
else:
pass
def connected():
pass
try:
channel = sys.argv[1]
server = False
print("Listening for messages on '%s' channel..." % channel)
pubnub.subscribe({
'channel' : channel,
'connect' : connected,
'callback' : receive
})
except:
channel = "MBPocketChange"
server = True
print("Listening for messages on '%s' channel..." % channel)
pubnub.subscribe({
'channel' : channel,
'connect' : connected,
'callback' : receive
})
tornado.ioloop.IOLoop.instance().start()
This error message happens if you run:
string.split(nil, ' ')
Double check your inputs to be sure you are really passing in a string.
Edit: in particular, msglist[0] is not the first position in the array in Lua, Lua arrays start at 1.
As an aside, this function was written when the intention that you'd use the colon syntactic sugar, e.g.
msglist=msg:split(' ')

Resources