Correct syntax for SQL Submittion - php

I'm working with Prestashop and I've got a module that generates shipping labels for my orders. When a label is made it generates a tracking code that can be used on the carriers website. The problem though is that our shippers have to copy and paste this code into prestashop for customers to receive a tracking email. It's my goal to automate this process to minimize human error within our system.
I've found the table and column within prestashop's database that houses the tracking code (ps_order_carrier, tracking_number) and I have confirmed that changing this value in the database effects the order in the way I have intended. Within the prestashop module there is a section of code that submits the tracking number and various order information like the order id which I will likely need to it's own table so I'm assuming I can just duplicate this portion of code and modify it to meet my needs. The following is the code within the module:
$sql = 'INSERT INTO '._DB_PREFIX_.$this->name.'_labels
(
id_order,
id_shipment,
postage_label_ref_id,
postage_label_object,
postage_label_updated_at,
postage_label_label_url,
tracking_code,
selected_rate_ref_id,
selected_rate_object,
selected_rate_updated_at,
selected_rate_service,
selected_rate_carrier,
selected_rate_shipment_ref_id,
tracker_ref_id,
tracker_object
)
VALUES
(
"'.(int)$data['id_order'].'",
"'.pSQL($data['id_shipment']).'",
"'.pSQL($data['postage_label']['ref_id']).'",
"'.pSQL($data['postage_label']['object']).'",
"'.pSQL($data['postage_label']['updated_at']).'",
"'.pSQL($data['postage_label']['label_url']).'",
"'.pSQL($data['tracking_code']).'",
"'.pSQL($data['selected_rate']['ref_id']).'",
"'.pSQL($data['selected_rate']['object']).'",
"'.pSQL($data['selected_rate']['updated_at']).'",
"'.pSQL($data['selected_rate']['service']).'",
"'.pSQL($data['selected_rate']['carrier']).'",
"'.pSQL($data['selected_rate']['shipment_ref_id']).'",
"'.pSQL($data['tracker']['ref_id']).'",
"'.pSQL($data['tracker']['object']).'"
)';
Db::getInstance()->Execute($sql);
I made a copy of this directly underneath and amended it to meet my needs but it doesn't seem to do what I want it to. I have a feeling I'm messing up the syntax. I've tried a few different variations of it so it's a bit chaotic but here is what I have as of writing this:
$sql2 = 'INSERT INTO `ps_order_carrier` WHERE `id_order` = '.(int)$data['id_order'].'
(
tracking_number
)
VALUES
(
"'.pSQL($data['tracking_code']).'"
)';
Db::getInstance()->Execute($sql2);
Any help would be greatly appreciated as this would save us so much time.
Thanks!

You're trying to update a row using an "INSERT" query.
$sql2 = 'UPDATE `ps_order_carrier` SET tracking_number = "'.pSQL($data['tracking_code']).'" WHERE `id_order` = '.(int)$data['id_order'].'
Db::getInstance()->Execute($sql2);
But the best way would be to first load the orderCarrier Object and change its tracking value without doing a direct query to DB.
$order = new Order($data['id_order']);
$orderCarrier = new OrderCarrier($order->getIdOrderCarrier());
$orderCarrier->tracking_number = $data['tracking_code'];
$orderCarrier->save();

To avoid all kind of mistakes in MySQL query syntax Prestashop have some classes and functions you can use:
Db::getInstance()->insert($this->name.'_labels',
array(
'id_order' => (int)$data['id_order'],
'id_shipment' => pSQL($data['id_shipment']),
/*and so on*/
)
);
Remember to cast all ID values to int and use pSQL in all string values.
There is an update function if you need it too.
Good luck.

there is no where clause in the insert statement.
specify all the values - and you get a new record.
$sql2 = 'INSERT INTO ps_order_carrier
(
tracking_number
, id_order
)
VALUES
(
"'.pSQL($data['tracking_code']).'"
, "'.(int)$data['id_order'].'"
)';
not tested - you may still need to fiddle with the quotes...

Related

How to DELETE multiple rows using values provided with an array PHP | SQL

I've restructuring my code to better fit the application and the one problem I can't seem to wrap my head around is deleting multiple rows with an array I'm providing to the back-end.
The query I'm using is as follows
$items = json_decode(file_get_contents('php://input'))
//the item is passed as an object {"values": ["string1", "string2", "string3"]}
$values = implode(",", $items->values);
$sql = "DELETE FROM products WHERE value IN($values)";
Before the changes this query was used to delete with ids instead of looking up specific values in rows.
$ids = json_decode(file_get_contents('php://input'))
$values= implode(",", $ids->ids);
$sql = "DELETE FROM products WHERE id IN($values)";
This worked without a hitch, but trying to run the new query keeps throwing the error
unknown column in where clause
I've tried multiple different approaches but can't get this to work.
help would be much appreciated.

How to get max of an ID as a PHP variable and insert it into another table where the ID is also max

I have two tables, Requests & Accounting_Fundscenter_Request
I'm creating a SQL query in PHP that updates
Request_ID from Accounting_Fundscenter_Request WHERE ID is max
to
the max Request_ID from Requests
So far I have gotten the max(Request_ID) rom Requests, but I don't know how to take that value in php & sql and update the other Request_ID to equal that value.
Also, I cannot use the syntax "max(id)" because the "max" function will not work in my first query and I don't know why.
Here's what I have so far:
/* GET MAX ID FROM REQUESTS */
$selectMaxID = 'SELECT Request_ID FROM Requests ORDER BY Request_ID DESC LIMIT 1';
$maxIdResult = mysqli_query($conn, $selectMaxID); //run query
if (mysqli_num_rows($maxIdResult) > 0) {
while($maxid = mysqli_fetch_assoc($maxIdResult)) {
echo "Max Request ID: " . $maxid["Request_ID"]. "<br>";
} //echo result of
}
$insertFundsCenterMaxId = "INSERT INTO `Accounting_Fundscenter_Request` (
`Request_ID`,
VALUES (
$maxid["Request_ID"],
)
WHERE MAX(`ID`);";
/* RUN THE QUERY */
$insertFundsCenterMaxId = mysqli_query($conn, $insertFundsCenterMaxId);
This does not work. Is there a way to fix this or maybe do it in one query?
EDIT: with your help I found the solution:
You have many options here:
You can fix the syntax error you have in you insert query execution like this:
$insertFundsCenterMaxIdQuery = sprintf('INSERT INTO Accounting_Fundscenter_Request (Request_ID) VALUES (%d)', $maxid["Request_ID"]);
/* RUN THE QUERY */
$insertFundsCenterMaxId = mysqli_query($conn, $insertFundsCenterMaxIdQuery);
This way you use string formatting to replace the variable instead of directly using $maxid["Request_ID"] in a string.
Please replace %d with %s in case the Request_ID is supposed to be string/varchar.
Or you can follow another approach and just use one query to do the work like this:
INSERT INTO Accounting_Fundscenter_Request (Request_ID)
SELECT MAX(Request_ID) FROM Requests
And just execute this query
You're facing a syntax error in the update query:
$insertFundsCenterMaxId = "INSERT INTO `Accounting_Fundscenter_Request` (
`Request_ID`,
VALUES (
$maxid["Request_ID"],
)
WHERE MAX(`ID`);";
Using the double quotes in that variable hiding in the VALUES part, you are ending the string contained in insertFundsCenterMaxId. Following it is a raw string containing Request_ID which cannot be parsed by PHP. That's simply invalid code.
To solve it, you could start using prepared statements. They will also help you to secure your application against SQL injection.
There is also a solution to the syntax error problem alone - but that will leave your application vulnerable. That's why I haven't included a fix for that, but by checking how to build strings you might find it on your own. But please, please do not use it for this problem. Please.

SQL - change an existing row

I'm using PHP in order to create a website where managers have access and review forms that employees have submitted. In the reviewing PHP file, I have created two buttons which basically approve or disapprove the form. After they click on one of the buttons, they are being redirected to another PHP file which actually inserts into the MySQL Database a change in a column I named 'processed'. It changes 0 which is unprocessed to 1, which is processed. The table I am referring to has columns such as formid, fullname, department and other job related stuff, as well as the 'processed' column which allows the managers to see if there is a pending form to be reviewed.
My problem is that I have no idea how to actually allow MySQL to find the proper row and change only the cell with the name 'processed' from 0 to 1 without having to insert every cell again. Here's what I have tried till now:
$id = $_SESSION[id];
$fullname = $_SESSION[fullname];
$teamformid = $_SESSION[teamformid];
if (isset($_POST['approved'])) {
$sql = "INSERT INTO carforms (processed) where aboveid='$id' and processed='0' and teamformid=$teamformid
VALUES ('0')";
}
else if (isset($_POST['disapproved'])) {
//todo
}
How do I tell SQL to only find the specific row I want and change only one column which is processed?
Also, do I always have to type every column name when I use the INSERT INTO command?
Thanks in advance.
Use the Below code it'll work for you.
$id = $_SESSION[id];
$fullname = $_SESSION[fullname];
$teamformid = $_SESSION[teamformid];
if (isset($_POST['approved'])) {
$sql = "UPDATE `carforms` SET processed = '1' WHERE `aboveid` = '".$id."' AND `teamformid` = '".$teamformid."'";
}
Try:
"UPDATE carforms SET processed = 1 WHERE aboveid = $id AND teamformid = $teamformid"
From what I have interpreted from your question, it seems like you need to use the MySQL UPDATE command. This will update any existing rows.
For example, let's say you have a table called 'forms', consisting of a Primary Key 'form_id' and a field named 'processed'.
If we want to change the value of 'processed' to '1', we would run...
UPDATE forms SET processed = 1 WHERE form_id = [whatever number the form is];
Obviously this only works where the form (with a form_id) exists already
There is no "INSERT...WHERE" in SQL.
To change an existing record there are 2 options, REPLACE or UPDATE. The former will create the record if it does not already exist and has similar syntax to INSERT. UPDATE uses the WHERE clause to identify the record(s) to be changed.
Using REPLACE is tricky. It needs to work out whether it should INSERT a new record or UPDATE an existing one - it does this by checking if the data values presented already exist in a unique index on the table - if you don't have any unique indexes then it will never update a record. Even if you have unique indexes just now, the structure of these may change over time as your application evolves, hence I would recommend NOT using REPLACE for OLTP.
In your question you write:
where aboveid='$id' and processed='0' and teamformid=$teamformid
(it would have been helpful if you had published the relevant part of the schema)
'id' usually describes a unique identifier. So there shouldn't be multiple records with the same id, and therefore the remainder of the WHERE clause is redundant (but does provide an avenue for SQL injection - not a good thing).
If the relevant record in carforms is uniquely identifed by a value for 'id' then your code should be something like:
$id=(integer)$id;
$sql = "UPDATE carforms SET processed = $action WHERE aboveid=$id";
But there's another problem here. There are 3 possible states for a record:
not yet processed
declined
approved
But you've only told us about 2 possible states. Assuming the initial state is null, then the code should be:
$action=0;
if (isset($_POST['approved'])) {
$action=1;
}
$id=(integer)$id;
$sql = "UPDATE carforms SET processed = $action WHERE aboveid=$id";
if ($id &&
(isset($_POST['disapproved']) || isset($_POST['approved']))
) {
// apply the SQL to the database
} else {
// handle the unexpected outcome.
}

SQL Query invalid/not displaying results

I am working on a property management software projects and I have been stuck at this point for a while now and I'm getting no where.
I can have one section working then another breaks so I'm chasing my tail here.
I'm trying to accomplish a form to search a database for specific entries such as bedrooms/baths, maxrent/minrent, and sorting functions included in the form.
SQL,
$beds = $_POST['beds'];
$baths = $_POST['baths'];
$minrent = $_POST['minrent'];
$maxrent = $_POST['maxrent'];
$result = mysqli_query($con,"SELECT * FROM units WHERE bed LIKE '%$beds%' OR bath LIKE '%$baths%' AND rent>='$minrent' AND rent<='$maxrent'");
while($row = mysqli_fetch_array($result)){}
Any help to the correct formatting of the sql would be fantastic. Thanks
EDIT: This is just a local project, not trying to make it web-safe.
Also, the columns I am using are rent, bed, bath with ~150 records.
EDIT: Solved, changed the column type from TEXT to INT.
You can try this, Added ( for OR )
"SELECT * FROM units WHERE (bed LIKE '%$beds%' OR bath LIKE '%$baths%')
AND (rent between '$minrent' AND '$maxrent' )"

T_STRING error - Trying to use PHP array in SQL where statement

I feel like I'm making a rookie error here somewhere but can't figure out what's going wrong. I am using PHP and mySQL. I have an array $users that stores a current user's information. The array is storing the customer id (cid, its an integer). So I'm trying to pull information that is only tagged to a specific customer. My code is:
try
{
$sql = 'SELECT id, title, image_url FROM shelf WHERE cid = $user['cid']';
$result = $pdo->query($sql);
}
I feel like I have similar code in other parts of my program that are working so this seems like I may be doing something wrong in terms of syntax. If I replace $user['cid'] in the request with a hard-coded number like 22, the statement works fine. However, I need to pull the integer from $user. I'm getting a T_STRING error on the SELECT statement line. I have also tried to add an additional set of single quotes around $user['cid'] but that's not working either (i.e. $user['cid'])
Thanks for your help.
Twine
You're using PDO, so you should be using place-holders, too:
$stmt = $pdo->prepare('SELECT id, title, image_url FROM shelf WHERE cid=:cid');
$stmt->bindParam(':cid', $user['cid']);
$stmt->execute();
This ensures your data is escaped correctly and handles conversion to the appropriate database format where required.
Yup, rookie error. Change to double quotes and add { } around value like:
$sql = "SELECT id, title, image_url FROM shelf WHERE cid = {$user['cid']}";
$sql = 'SELECT id, title, image_url FROM shelf WHERE cid = '.intval($user['cid']);

Categories