Handle database error in CodeIgniter [Error Number: 1062] - database

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;

Related

Can't create Portal User. REQUIRED_FIELD_MISSING, Required fields are missing: [Profile]: [Profile]

I am trying to create Portal User from Community public page using this code:
this.userVar = new User(
Alias = (this.contactVar.FirstName + this.contactVar.LastName).toLowerCase(),
Email = this.contactVar.Email,
FirstName = this.contactVar.FirstName,
LastName = this.contactVar.LastName,
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_AU',
Country = 'Australia',
ProfileId = assistanceHubProfile.Id,
IsActive = true,
TimeZoneSidKey = 'Australia/Sydney',
Username = this.contactVar.Email,
ContactId = this.contactVar.Id
);
System.debug(this.userVar);
insert this.userVar;
but I have this error:
Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Profile]: [Profile]
System debug before insert:
User:{Alias=tedsttestte, Email=test#test.com, FirstName=Tedst, LastName=Testte, EmailEncodingKey=UTF-8, LanguageLocaleKey=en_US, LocaleSidKey=en_AU, Country=Australia, ProfileId=00e920000002Ag1AAE, IsActive=true, TimeZoneSidKey=Australia/Sydney, Username=test#test.com, ContactId=00392000003RLeXAAW}
As you can see ProfileId is populated. I can't understand why this error is occurred.
There are no triggers and triggered-flow for User SObject
It was because I didn't use without sharing key words in apex class definition. In my case apex class will use with sharing settings by default.

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

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();
}

Service Stack OrmLite and Identity_Insert

When using Service Stack OrmLite how do you insert identity values exactly?
For instance in SQL Server when Identity_Insert is turned on for a table the identity value will be inserted exactly as specified and will not instead be auto generated.
Do not decorate your primary key with the [AutoIncrement] attribute. If you do so, then OrmLite will leave that column name and value out of the INSERT statement.
Issue the SET IDENTITY_INSERT statement. Make sure to let OrmLite build the table name for you, taking into account any [Schema] and [Alias] attributes.
For example:
public void InsertAll(IEnumerable<TTable> set)
{
const string identity = "SET IDENTITY_INSERT {0} {1}";
var schema = typeof(TTable).FirstAttribute<SchemaAttribute>();
var tableName = typeof(TTable).FirstAttribute<AliasAttribute>();
var qualified = (schema == null ? "dbo" : schema.Name) + "." +
(tableName == null ? typeof(TTable).Name : tableName.Name);
using (var db = _dbConnectionFactory.OpenDbConnection())
{
try
{
db.ExecuteSql(string.Format(identity, qualified, "ON"));
db.InsertAll(set);
}
finally
{
db.ExecuteSql(string.Format(identity, qualified, "OFF"));
}
});
}

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

SQLite If Column Exists

I was wondering if there is a nice IF NOT EXISTS for checking columns and indexes in SQLite, or do I need to bring back the entire database schema and validate against that?
There is a system catalog table called sqlite_master that you can use to check index (or other) names:
SELECT name FROM sqlite_master WHERE type='index' ORDER BY name;
You can use a pragma to get the indexed columns:
PRAGMA index_info(index-name);
And this one to get the column names for a table:
PRAGMA table_info(table-name);
Yes the following syntax is supported in sqlite: CREATE INDEX IF NOT EXISTS ...
See here
To check existence of a column you could simply try to do something like SELECT col from TABLE. If it does not return an error your table contains col.
In SQLite, If you want to check whether your column/field exist in your table or not....try this answer work for me...
https://stackoverflow.com/a/28146506/3126569
Cursor res = db.rawQuery("PRAGMA table_info("+tableName+")",null);
int value = res.getColumnIndex(fieldName);
This is how I do it,
INSERT INTO AUDITEVENT (CODE, DESCRIPTION, AUDITEVENTPK)
SELECT 'value1', 'value2', 'value3'
WHERE NOT EXISTS (SELECT 1 FROM AUDITEVENT WHERE CODE = 'value1')
In my IDConneciton, I have a method called ProcessCommandText to update the query from SQL Server syntax to SQLite only.
This is the implementation of that method
public string ProcessSqlText(string text)
{
var result = text.Replace("SET ANSI_NULLS ON", "").
Replace("SET ANSI_NULLS ON", "").
Replace(" ASC)", ")").
Replace("TOP 100", "TOP(100)").
Replace("TOP 1", "TOP(1)").
Replace(" VARCHAR", " NVARCHAR").
Replace(" CHAR", " NCHAR").
Replace(" TEXT", " NTEXT").
Replace("WITH ( IGNORE_DUP_KEY = OFF)", "").
Replace("SET QUOTED_IDENTIFIER ON", "").
Replace("SET ANSI_PADDING ON", "").
Replace("SET ANSI_PADDING OFF", "").
Replace("SET ANSI_WARNINGS ON", "").Trim(' ').
Replace("WITH NOCHECK", "").
Replace("(nolock)", "").
Replace("CREATE CLUSTERED INDEX", "CREATE NONCLUSTERED INDEX").
Replace("CREATE UNIQUE CLUSTERED INDEX", "CREATE UNIQUE NONCLUSTERED INDEX").
Replace("[dbo].", "").
ToUpper().
Replace("NEWID()", "'" + Guid.NewGuid().ToString() + "'"). // NEWID() is not supported
Replace("GO", ""); // GO is not supported
if (result.Contains("TOP(100)"))
{
result = result.Replace("TOP(100)", "");
result += " LIMIT 100";
}
if (result.Contains("TOP(1)"))
{
result = result.Replace("TOP(1)", "");
result += " LIMIT 1";
}
if (result.Contains("DATEPART"))
{
result = result.Replace("DATEPART", "strftime");
result = result.Replace("minute", "'%M'");
result = result.Replace("day", "'%d'");
result = result.Replace("month", "'%m'");
result = result.Replace("year", "'%Y'");
}
result = TransformIfNotExistsQueriesToSqlLite(result);
return result;
}
private string TransformIfNotExistsQueriesToSqlLite(string query)
{
var ifNotExistsRegEx = #"(IF NOT EXISTS\s+)\(+.+\)+\r+\n+INSERT+";
var m = Regex.Match(query, #"(IF NOT EXISTS\s+)\(+.+\)+\r+\n+INSERT+", RegexOptions.IgnoreCase);
if (m.Groups.Count > 0 && m.Groups[0].Value.Contains("IF NOT EXISTS"))
{
var conditionalStatement = m.Groups[0].Value;
var newQuery = query.Replace(conditionalStatement, " INSERT ");
conditionalStatement = conditionalStatement.ToUpper().Replace("IF", "WHERE").Replace("INSERT", "");
newQuery = Regex.Replace(newQuery.ToUpper(), #"VALUES\s+\(+", " SELECT ");
var lastIndexOfClosingBracket = newQuery.LastIndexOf(')');
newQuery = newQuery.Substring(0, lastIndexOfClosingBracket);
return newQuery + " " + conditionalStatement;
}
return query;
}
Why dont you just catch the exception? For example:
try{
db.execSQL("ALTER TABLE ACCOUNT_ENTRY ADD COLUMN ID_CONCEPT NUMBER(10)");
}catch(Exception e){
System.out.println(e);
}

Resources