minus the quantity value in the database by $_POST in yii - database

I have a table called Apparatus and there is a column there called "quantity",
I have another table called Transaction where you can select the apparatus id and reserve a quantity
how can i minus the quantity in the transaction from the quantity in apparatus? I'm getting undefined index: id error...
here is a code in my controller:
if (isset($_POST['Transaction']))
{
$transaction->attributes = $_POST['Transaction'];
$transaction->save();
$apparatus = Apparatus::model()->findByPk($_POST['id']);
$apparatus->quantity = $apparatus->quantity - ($_POST['quantity']);
$apparatus->save();

Before doing arithematic operation, check whether the index id is present.
I am sure, your $_POST variables does not hold id as index.
So, i suggest to do the following:
if(Yii::app()->request->getPost('id') && Yii::app()->request->getPost('quantity') && Yii::app()->request->getPost('Transaction')){
$id = (int) Yii::app()->request->getPost('id');
$quantity = (int) Yii::app()->request->getPost('quantity');
$apparatus = Apparatus::model()->findByPk($id);
if($apparatus){
$apparatus->quantity = $apparatus->quantity - $quantity;
if($apparatus->validate()){
$apparatus->save();
}else{
// Log
var_dump($apparatus->errors);
}
}
}
Alternatively, you can dump {var_dump($_POST)} the post variables to see whether the $_POST contains id as index.

Here's what I did: (controller)
if (isset($_POST['Transaction']))
{
$transaction->attributes = $_POST['Transaction'];
$transaction->save();
$id=$transaction->apparatus_id=($transaction['apparatus_id']);
$quantity=$transaction->quantity=($transaction['quantity']);
$apparatus = Apparatus::model()->findByPk($id);
$apparatus->quantity = $apparatus->quantity - $quantity;
$apparatus->save();
}

Related

What are the options available to get Primary Key Column Names in Snowflake?

I need to fetch all Primary Keys, their parent Table Name , Column Name, and Schema Name together.
I am using INFORMATION_SCHEMA for all metadata fetching, SHOW PRIMARY KEYS/DESCRIBE TABLE does the job but it's not an option here.
Need something similar to SELECT *FROM DB.INFORMATION_SCHEMA.XXX.
What are the options we have here?
*I am Using JDBC
You may consider using: getPrimaryKeys(String, String, String)
Details: https://docs.snowflake.com/en/user-guide/jdbc-api.html#object-databasemetadata
A while back, I wrote a user defined table function (UDTF) to get the PK column(s) for a single table, each column in the PK as a single row in the return. I extended it to return a table with all the columns in PKs in an entire database.
Once you create the UDTF, you can get all the PKs for a database like this:
select * from table(get_pk_columns(get_ddl('database', 'MY_DB_NAME')));
It will return a table with columns for the schema name, table name, and column name(s). Note that if there's a composite PK, it shows in the table as one row per column. You can of course use an aggregate function such as listagg() to change that into a single row with the columns names of the composite PK separated by commas.
It's possible that if you have a very large number of tables/columns in your database, the return of the GET_DDL() function will be too large to fit into the 16mb limit. If it does fit, this should return the results quickly.
/********************************************************************************************************
* *
* User defined table function (UDTF) to get all primary keys for a database. *
* *
* #param {string}: DATABASE_DDL The DDL for the database to get the PKs. Usually use GET_DDL() *
* #return {table}: A table with the columns comprising the table's primary key *
* *
********************************************************************************************************/
create or replace function GET_PK_COLUMNS(DATABASE_DDL string)
returns table ("SCHEMA_NAME" string, "TABLE_NAME" string, PK_COLUMN string)
language javascript
as
$$
{
processRow: function get_params(row, rowWriter, context){
var startTableLine = -1;
var endTableLine = -1;
var dbDDL = row.DATABASE_DDL.replace(/'[\s\S]*'/gm, '')
var lines = dbDDL.split("\n");
var currentSchema = "";
var currentTable = "";
var ln = 0;
var tableDDL = "";
var pkCols = null;
var c = 0;
for (var i=0; i < lines.length; i++) {
if (lines[i].match(/^create .* schema /)) {
currentSchema = lines[i].split("schema")[1].replace(/;/, '');
//rowWriter.writeRow({PK_COLUMN: "currentSchema = " + currentSchema});
}
if (lines[i].match(/^create or replace TABLE /)) {
startTableLine = i;
}
if (startTableLine != -1 && lines[i] == ");") {
endTableLine = i;
}
if (startTableLine != -1 && endTableLine != -1) {
// We found a table. Now, join it and send it for parsing
tableDDL = "";
for (ln = startTableLine; ln <= endTableLine; ln++) {
if (ln > 0) tableDDL += "\n";
tableDDL += lines[ln];
}
startTableLine = -1;
endTableLine = -1;
currentTable = getTableName(tableDDL);
pkCols = getPKs(tableDDL);
for (c = 0; c < pkCols.length; c++) {
rowWriter.writeRow({PK_COLUMN: pkCols[c], SCHEMA_NAME: currentSchema, TABLE_NAME: currentTable});
}
}
}
function getTableName(tableDDL) {
var lines = tableDDL.split("\n");
var s = lines[1];
s = s.substring(s.indexOf(" TABLE ") + " TABLE ".length);
s = s.split(" (")[0];
return s;
}
function getPKs(tableDDL) {
var c;
var keyword = "primary key";
var ins = -1;
var s = tableDDL.split("\n");
for (var i = 0; i < s.length; i++) {
ins = s[i].indexOf(keyword);
if (ins != -1) {
var colList = s[i].substring(ins + keyword.length);
colList = colList.replace("(", "");
colList = colList.replace(")", "");
var colArray = colList.split(",");
for (pkc = 0; c < colArray.length; pkc++) {
colArray[pkc] = colArray[pkc].trim();
}
return colArray;
}
}
return []; // No PK
}
}
}
$$;
I did this using a very simple SQL based UDTF:
CREATE OR REPLACE FUNCTION admin.get_primary_key(p_table_nm VARCHAR)
RETURNS TABLE(column_name VARCHAR, ordinal_position int)
AS
WITH t AS (select get_ddl('TABLE', p_table_nm) tbl_ddl)
, t1 AS (
SELECT POSITION('primary key (', tbl_ddl) + 13 pos
, SUBSTR(tbl_ddl, pos, POSITION(')', tbl_ddl, pos) - pos ) str
FROM t
)
SELECT x.value column_name
, x.index ordinal_position
FROM t1
, LATERAL SPLIT_TO_TABLE(t1.str, ',') x
;
You can then query this in a SQL statement:
select *
FROM TABLE(admin.get_primary_key('<your table name>'));
Unfortunately, due to the odd implementation of GET_DDL(), it will only accept a string literal and you can't use this function with a lateral join to information_schema.tables. Get the following error:
SQL compilation error: Invalid value [CORRELATION(T.TABLE_SCHEMA) ||
'.' || CORRELATION(T.TABLE_NAME)] for function '2', parameter
EXPORT_DDL: constant arguments expected

Update or insert from csv into sql server

I have a CSV file containing user info, say
first_name;last_name;user_id;full_name
column separator is ;, row terminator is \n.
What I need to do is to insert or update into users table. Unique key is user_id: if record with this user_id already exists, I need to update, if it doesn't I need to insert.
However, there are some problems that prevent me from using management studio data-import or bulk insert.
First, there are more fields in the users table (not just 4) and the order of columns in csv file does not correspond to the order of columns in the table. So I need to be able to specify which column from the file goes to which column in the table.
Secondly, some additional fields need to be filled. For example, users.email = users.user_id. Here is another obstacle - though for a newly inserted row users.email = users.user_id it is possible that users.email will change in the future, so I cannot just insert user_id and then run update [users] set [email] = [user_id].
Use fgetcsv
Example with two colonne :
<?php
$row = 0;
$update = "";
//separator of column
$separator = ";";
//creates two variables containing the index columns to read / modify
$idx_nom = 0;
$idx_rubrique = 1;
//Open file writing
if (($handle = fopen("test.csv", "r")) !== FALSE)
{
//we travel the file line by line, storing the data in a table
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
{
//can not control that the second line if the first contains the column headers
if ($row != 0)
{
//conditions of one column
if (stristr($data[$idx_nom], 'chemise'))
{
$data[$idx_rubrique] = 1;
}
else if (stristr($data[$idx_nom], 'costume'))
{
$data[$idx_rubrique] = 2;
}
else if (stristr($data[$idx_nom], 'cravate'))
{
$data[$idx_rubrique] = 3;
}
}
$update .= implode($separator,$data)."\r\n";
$row++;
}
fclose($handle);
}
//update from csv
$ouvre=fopen("test.csv","w+");
fwrite($ouvre,$update);
fclose($ouvre);
?>

Add value into database plus 1

In my database I have:
Row ID - Driver ID - Log ID.
Row ID is unique and auto-increments. What I want is for the Log ID to be unique for each row that has that Driver ID.
For example say a row is inserted with Driver ID 1 I want that row to have a Log ID of 1 but the next time a row is inserted with Driver ID 1 I want it to have a Log ID of 2.
How can I achieve this?
By way for database i am using PHPMyAdmin.
----------------Edit----------------------
This is what i have in my PHP now, but it says:
On the webpage: Incorrect integer value: '' for column 'FinesCost' at row 1
And i dump the variables and get this: string(2) "16" string(2) "16" string(2) "16" so i dont understand why it is saying incorrect integer value and why it is saying they are undefines because they are very clearly defined.
In the PHP error log: [19-Jul-2013 10:44:18 Europe/Minsk] PHP Notice: Undefined variable: FinesCostP‌ost2 in C:\inetpub\wwwroot\hosting\Dan\JWT\drivers-log-send.php on line 336
[19-Jul-2013 10:44:18 Europe/Minsk] PHP Notice: Undefined variable: TravelExpensesPo‌​st2 in C:\inetpub\wwwroot\hosting\Dan\JWT\drivers-log-send.php on line 336
///PHP TO INSERT DRIVER'S BANK DETAILS INTO BANK DATABASE
session_start();
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="jwtdriversbank"; // Table name
$un = "";
$usrname = "";
$usrpass = "";
$userID = "";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
if(isset ($_SESSION['usrName']))
{
$usrname = $_SESSION['usrName'];
}
else
{
echo "4";
}
//var_dump ($usrname);
if(isset ($_SESSION['usrPass']))
{
$usrpass = $_SESSION['usrPass'];
}
else
{
echo "5";
}
$sql="SELECT * FROM jwtdrivers WHERE username='$usrname' and password='$usrpass'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
$userID = $rows['id'];
//var_dump ($userID);
if($userID == "")
{
echo "3";
}
else
{
$TotalProfitPost = $TotalProfit;
$LateFeePost = $LateFee;
$FinesCostPost2 = $FinesCost;
$TravelExpensesPost2 = $TravelExpenses;
$FuelCostPost = $FuelCost;
$CargoDamagePost = $CargoDamage;
$TruckDamagePost = $TruckDamage;
var_dump ($TotalProfitPost);
var_dump($FinesCostPost2);
var_dump($TravelExpensesPost2);
$sql="INSERT INTO jwtdriversbank2 (DriverID, LogID, TotalProfit, LateFee, FinesCost, TravelExpenses, FuelCost, CargoDamage, TruckDamage) VALUES ('$userID', COALESCE((Select MAX(LogID) from jwtdriversbank2 tab2 where tab2.DriverID = '$userID'),0)+1,'$TotalProfitPost','$LateFeePost', '$FinesCostP‌ost2' , '$TravelExpensesPo‌​st2' ,'$FuelCostPost','$CargoDamagePost','$TruckDamagePost')";
$result = mysql_query($sql);
if($result)
{
}
else
{
die(mysql_error());
}
}
Add a primary key for the two columns.
It should do the trick.
Look at this link for help
ALTER TABLE table_name
ADD CONSTRAINT pk_DriverID PRIMARY KEY (DriverID,LogID)
Do not forget to drop the first primary key because you will not need it no more.
EDIT : COMPLETE WITH THE OTHER ANSWER
Here is the code to insert your data.
Insert into <table_name>
values p_RowID, p_DriverID, COALESCE((Select MAX(Log_id) from <table_name> tab2 where tab2.Driver_id = p_DriverID),0)+1;
That should close the question.
You did not defined variable because PHP can't read them.
I opened your program inside VIM editor and I found "<200c>" char inside $FineCostPost2 in the SQL query. You have to change it to make it work.
A quick solution would be to use a subquery to find the maximum log (last log id) then increment it, something like this
Insert into <table_name>
values p_RowID, p_DriverID, COALESCE((Select MAX(Log_id) from <table_name> tab2 where tab2.Driver_id = p_DriverID),0)+1;
Here p_RowID and p_DriverID are the values you pass to insert into your table. The Coalesce function would check the given value and if it is NULL then it would replace it with the second parameter, in this case 0

Handle database error in CodeIgniter [Error Number: 1062]

I'm getting the following error while executing database query:
A Database Error Occurred
Error Number: 1062
Duplicate entry '1' for key 'PRIMARY'
UPDATE tbl_galeri SET id_galeri = '1', galeri_kat_id = '1', nama = 'Elyza Okiliyandass', foto = 0, deskripsi = 'Elyza Okiliyanda'
Filename: C:\xampp\htdocs\indonesiausher\system\database\DB_driver.php
Line Number: 330
Controller:
$pilih['id_galeri'] = $this->uri->segment(3);
$dt_galeri = $this->app_model->getSelectedData("tbl_galeri",$pilih);
foreach($dt_galeri->result() as $db)
{
$bc['id_galeri'] = $db->id_galeri;
$bc['galeri_kat_id'] = $db->galeri_kat_id;
$bc['nama'] = $db->nama;
$bc['foto'] = $db->foto;
$bc['deskripsi'] = $db->deskripsi;
$bc['stts'] = "edit";
}
$this->load->view('backend/gallery/bg_input_usher',$bc);
}
Model:
public function getSelectedData($table,$data)
{
return $this->db->get_where($table, $data);
}
How to handle this error?
Thanks..
Once try by removing the id_galeri like below in UPDATE Query
UPDATE tbl_galeri SET galeri_kat_id = '1', nama = 'Elyza Okiliyandass', foto = 0, deskripsi = 'Elyza Okiliyanda' WHERE id_galeri = '1'
EDIT
May be you don't need to update the PRIMARY & AUTO INCREMENT Key. So remove id_galeri
I don't think your SQL statement is complete. You should have something like the following:
UPDATE table SET field = '$value' WHERE id = '$id'
you can check out your primary key field auto increment field.
if in your table any data stored then first up all take data backup then remove data and ALTER TABLE table CHANGE your primary key field your primary key field INT(11) NOT NULL AUTO_INCREMENT;

Django Field Choices

Given below is my Model definition and I have added this module part of the Admin. I'm trying to create new row and while selecting value '3' or any other value for Duration field(listed as select fields), I get the following error.- "Value 3 is not a valid choice".
Please provide your inputs.
Model Definition
NO_OF_HRS = (
('1','One'),
('2','Two'),
('3','Three'),
('4','Four'),
('5','Five'),
('6','Six'),
('7','Seven'),
('8','Eight'),
('9','Nine'),
('10','Ten'),
('11','Eleven'),
('12','Twelve'),
)
YR_MONTH = (
("Y", "Year"),
("M", "Month"),
)
POS_STATUS = (
("A", "Active"),
("C", "Closed"),
)
datecreated = models.DateTimeField()
volposition = models.CharField(max_length=300)
roledesc = models.CharField(max_length=5000)
noofhours = models.IntegerField(blank = True,null = True)
Qualreqt = models.CharField(max_length=8000)
Duration = models.IntegerField(choices=NO_OF_HRS,blank = True,null = True)
Durationyrmon = models.CharField(choices=YR_MONTH,max_length=10)
posstatus = models.CharField(choices=POS_STATUS,max_length=1)
teamrelation = models.CharField(max_length=50)
When you use choices, the first value of the tuple is the value that will be stored in the database and the second value is the value that will be shown in the admin.
In NO_OF_HRS the values are strings (for example '1', '2') but it is a models.IntegerField so the values should be integers. That's why you're now getting an error.
Opened a ticket on django with fix and dirty fix:
https://code.djangoproject.com/ticket/24897

Resources