I have a sql table in my database "accounts" whose structure looks like this.
ItemNo CostPrice SellingPrice Discount(10%) Price(INR)
100 $100 $150 $135 Rs.7425
101 $200 $250 $225 Rs.10395
102 $150 $200 $180 Rs.7920
103 $500 $550 $495 Rs.25245
Here each column is dependent on the previous one.
SellingPrice = CostPrice + 50
Discount = SellingPrice + (0.1 * SellingPrice)
Price(INR) = SellingPrice * ($_Conversion_rate_to_Rs)
I need to calculate the SellingPrice and update it in the table.
Then I calculate the Discount and update the table
Then I calculate the Price(INR) and update the table.
I am trying the following code but it doesnt seem to be working.
$i = 0;
foreach($item_no as $item ){
mysql_query("UPDATE accounts SET SellingPrice = CostPrice + 50 WHERE item_no = '$item[$i]'") or die(mysql_error());
++$i;
}
Now after updating the SellingPrice I need to calculate the discount and update the database.
$i = 0;
foreach($item_no as $item ){
mysql_query("UPDATE accounts SET Discount = SellingPrice + (0.1 * SellingPrice) WHERE item_no = '$item[$i]'") or die(mysql_error());
++$i;
}
And so on..
My doubt may be quite simple but I tried a lot and couldn find a correct solution.
Can I know my mistakes and the correct solution ?
EDIT!
The way I edit multiple fields is with a custom update function. The function takes an associative array of "field"=>"new value". Here's the function:
function update($table,$values,$conditions){
$query = "UPDATE `" . $table . "` SET ";
foreach($values as $key => $value){
if($key == "password")
$query .= "`password` = PASSWORD('" . $mysqli->real_escape_string($value) . "'),";
else if(is_numeric($value))
$query .= "`" . $mysqli->real_escape_string($key) . "` = " . $mysqli->real_escape_string($value) . ",";
else
$query .= "`" . $mysqli->real_escape_string($key) . "` = '" . sanitize($value) . "',";
}
$query = substr($query,0,-1);
if(!is_string($conditions)){
$conditionStr = "";
foreach($conditions as $key => $value){
if($key == "password")
$conditionStr .= "`password` = PASSWORD('" . $mysqli->real_escape_string($value) . "') AND ";
else if(is_numeric($value))
$conditionStr .= "`" . $mysqli->real_escape_string($key) . "` = " . $mysqli->real_escape_string($value) . " AND ";
else
$conditionStr .= "`" . $mysqli->real_escape_string($key) . "` = '" . sanitize($value) . "' AND ";
}
$conditionStr .= substr($conditionStr,0,-4);
$conditions = $conditionStr;
}
$query .= " WHERE " . $conditions . " ;";
$mysqli->query($query);
}
You use it like this:
update("theTable",array("username"=>"whateverTheNewNameIs"),array("userID"=>55));
That updates userID=55 and makes the username something new. You can just expand the second array to update more things.
I think you a problem in your updates and your where clause
I'd make a variable for your new cost price,
$newSellingPrice = $item[$i]['sellingPrice'] + 50;
In your update you can use $newSellingPrice
Then in your where, you have a typo, you didn't use the $ to get the item array.
You'll need to leave the query string if you're using square bracket notation
"... WHERE item_no = " . $item[$i] . " ;";
To answer your question, if you want to update all fields in the table, there is no need to add a WHERE condition, you can just use:
UPDATE accounts SET SellingPrice = CostPrice + 50
and run only one query in total instead of one query per item.
However, all columns that depend on other columns really don't need to be separate columns, you would be a lot better of with a table with just 2 columns and calculate the prices as you need them. Now you have a lot of duplicate information as the cost price and the multipliers are the only values you really need to store.
Related
I have a table in Database PhpMyAdmin with certain values, and I want to UPDATE only ONE value of these, WHERE the latest initial_date (TIMESTAMP) is.
I write down here the code I generated as an example, so you can see I actually obtain that date value through SELECT, but I don't manage to UPDATE it. Thank you very much.
$select = "SELECT MAX(initial_date) AS max_value FROM services WHERE matricula = '" . $_POST["taxi"] . "'";
$select_results = mysqli_query($conexion, $select);
while($row = mysqli_fetch_array($select_results)){
echo $row['max_value'];
$update_carrera = "UPDATE services SET";
$update_carrera .= " costo_carrera = costo_carrera + " . $_POST["costo_carrera"] . ",";
$update_carrera .= " final_date = CURRENT_TIMESTAMP";
$update_carrera .= " WHERE initial_date = ''";
$update_carrera_results = mysqli_query($conexion, $update_carrera);
}
I leave WHERE initial_date = '' empty so you can tell what should it be. I get a correct date value in the echo $row['max_value']; if I solve the WHERE with a WHERE initial_date = '20160405153315' (INTEGER), but I don't want to put myself the integer, of course I want to get the newest date from the table database.
I have latest MySQL version (5.5) and this is the screenshot of groupid field
I didn't touch anything yet, but some cells are not ordered correctly like this
But if I click groupid name in the top, it will ordered correctly like this:
Below PHP code output is like first screenshot above, that are not ordered correctly. Please help how to make the output ordered correctly, like it is displayed in the second screenshot above,
Maybe add code like this : order by id asc, but which is the right place to add it below?
$group_ids = explode(" ", $options['groupchoice_ids']);
$groupsql = "SELECT id, title FROM " . TABLE_PREFIX . "thegroup WHERE";
$first = true;
foreach($group_ids as $value)
{
if (!$first)
{
$groupsql = $groupsql . " OR ";
}
else
{
$first = false;
}
$groupsql = $groupsql . " id = '" . $value . "' ";
}
$kh_optionsgroup = '<select name = "accounttype">';
$checksec = $db->query_read($groupsql);
if ($db->num_rows($checksec))
{
while ($lboard = $db->fetch_array($checksec))
{
$kh_optionsgroup = $kh_optionsgroup . "<option value
='" . $lboard['id'] . "'>" . $lboard['title'] . "</option>";
}
}
$verifystring = '$human_verify';
$kh_optionsgroup = $kh_optionsgroup . "</select>";
At the end of your query, you need to set an order, like so:
$groupsql="SELECT id, title FROM " . TABLE_PREFIX . "thegroup WHERE";
$first=true;
foreach($group_ids as $value){
if(!$first){
$groupsql = $groupsql." OR ";
}else{
$first = false;
}
$groupsql = $groupsql." id = '".$value."' ORDER BY groupid ASC";
}
ORDER BY id ASC
This will make the query return its results in ascending order from the groupid column. Simply change ASC to DESC if you want it to go descendinng (high->low).
Below is my small code for inserting some info into AthleteID. It doesn't actually insert the information to the table though, any help is appreciated. (sorry for asking twice, but I think my first question isn't addressing whatever issue is holding me up here!)
<?php
require_once('resources/connection.php');
echo 'hello noob' . '<br />';
$query = mysql_query('SELECT LName, MyWebSiteUserID FROM tuser WHERE MyWebSiteUserID = MyWebSiteUserID');
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebSiteUserID"];
$update = "UPDATE `tuser` SET `AthleteID`='$athleteId' WHERE `MyWebSiteUserID` = `MyWebSiteUserID`;";
while($row = mysql_fetch_array($query)){
mysql_query( $update);
}
Where to begin..
1) Your using mysql and not mysqli. mysql is now deprecated but you could be on a PHP 4 system so keep that in mind.
2) You are building the $athleteID before you have found out what LName and SkillshowUserID is.
3) Your using a where of 1 = 1. You dont need this as it will return true for every row.
4) So...
// Execute a query
$results = mysql_query('SELECT LName, MyWebsiteID FROM tuser WHERE SkillshowUserID = SkillshowUserID');
// Loop through the result set
while($row = mysql_fetch_array($query))
{
// Generate the athleteId
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebsiteID"];
// Generate an sql update statement
$update = "UPDATE `tuser` SET `AthleteID`='" . $athleteId . "' " .
" WHERE LName = '" . $row['LName'] . "' " .
" AND MyWebsiteID = '" . $row['MyWebsiteID'] . "';";
// Fire off that bad boy
mysql_query($update);
}
I'm new to PHP, and I do not it's syntax and principles very well.
I have such code:
function exportFromTransbase($table_name) {
//$odbc_query = "SELECT * FROM " . $table_name. " WHERE ((CDS_CTM subrange(248 cast integer) = 1) AND (CDS_LNG_ID = 16))";
$odbc_query = "SELECT * FROM " . $table_name. "";
$data = odbc_exec($this->odbc_id, $odbc_query);
odbc_longreadlen($data, 10485760);
$oufile=fopen($table_name.".sql", 'w') or die("error writing file");
$q1='INSERT INTO `' . substr($table_name, 4) . '` VALUES';
fwrite($oufile, $q1);
while($row = odbc_fetch_array($data))
{
foreach($row as $key => $value) {
$keys[] = "`" . $key . "`";
if ($value == ""){
$value = 'NULL';
$values[] = "" . mysql_real_escape_string($value) . "";
}
else{
$values[] = "'" . mysql_real_escape_string($value) . "'";
}
//echo "\n \n ololo ".$value;
}
$mysql_query = "\n (".implode(",", $values).")," ;
fwrite($oufile, $mysql_query);
//mysql_query($mysql_query);
set_time_limit(0);
unset($keys);
unset($values);
unset($row);
}
$stat = fstat($oufile);
ftruncate($oufile, $stat['size']-1);
fseek($oufile, 0, SEEK_END);
fwrite($oufile, ";".$r);
//} while ($r < 5 );
fclose($oufile);
if ($mysql_query){
print "Ýêñïîðò äàííûõ èç òàáëèöû " . $table_name . " çàâåðøåí!";
//strtolower(substr($table_name, 4))
}
}
what and where i need to custom, so that i export all table fields except one, for example called Size, i must insert in db is this field nulls....
Also if it is easy, how to split my sql query in batches of 5000 rows? so insert (5000 rows) then insert another 5000....
But first i need to export all fields, except one...
To the best of my knowledge, it can't be possible.
You can use simply:
SELECT field1, field2, field3, field4 FROM table
See Select all columns except one in MySQL?
And if you have more fields in your table then you can use * only.
At the time of insert you can make a condition which ignores the field which you don't want in new table.
Can you use
"select * from {table} where {sth} != {condition}"
Then you can fetch all data except one. The one is excrpted follow your condition.
Meanwhile,if you want to insert by 5000, you can read 5000 lines one time and insert into.
I am trying to make dynamic product filtering for opencart in which user could add filters, assign them to categories and assign filter values for products.
Currently I Have these mysql tables:
Filters - ID NAME
Filters_categories - ID FILTER_ID CATEGORY_ID
Filters_values - ID FILTER_ID VALUE
Filters_products - ID FILTER_ID VALUE_ID PRODUCT_ID
The problem is with this structure that i can't get products when more than one filter is activated because i get MySQL query which looks something like this:
SELECT product_id FROM Filters_products WHERE ((name_id='1' OR name_id='2') AND filter_id='1') AND ((name_id='3' OR name_id='4') AND filter_id='2')
And it doesn't make any sense. I can't figure out how should i change my database structure to make dynamic filtering possible. How can I solve this situation?
Thank you.
SELECT product_id FROM Filters_products WHERE (screen_id='1' OR screen_id='2') and (connection_id='1')
Use this awesome extension,
http://www.opencart.com/index.php?route=extension/extension/info&extension_id=10098
Hope this helps.
in file /catalog/model/catalog/product.php find line nr. 91 and replace "if {}" block whit this code...
if (!empty($data['filter_category_id'])) {
if (!empty($data['filter_sub_category'])) {
$sql .= " AND cp.path_id = '" . (int)$data['filter_category_id'] . "'";
} else {
$sql .= " AND p2c.category_id = '" . (int)$data['filter_category_id'] . "'";
}
if (!empty($data['filter_filter'])) {
$implode = array();
$filters = explode(',', $data['filter_filter']);
foreach ($filters as $filter_id) {
$filterSQL = $this->db->query("SELECT * FROM " . DB_PREFIX . "filter WHERE filter_id = ". $filter_id);
$implode[$filterSQL->row['filter_group_id']][] = (int)$filter_id;
}
foreach($implode AS $implode2) {
$sql .= " AND (";
foreach($implode2 AS $filterID) {
$sql .= "(SELECT count(*) FROM product_filter WHERE product_filter.product_id=p.product_id AND product_filter.filter_id=$filterID) OR ";
}
$sql = substr($sql, 0, -4);
$sql .= ")";
}
}
}