SQLSTATE[22007]: Invalid datetime forma - sql

I try to save some data that it brings me from my view, which is a table, but I don't know why it throws me that error with the insert.
result of insert
this is my view:
table of view
this is my controller:
$checked_array = $_POST['id_version'];
foreach ($request['id_version'] as $key => $value) {
if (in_array($request['id_version'][$key], $checked_array))
{
$soft_instal = new Software_instalacion;
$soft_instal->id_instalacion = $instalaciones->id;
$soft_instal->id_historial = $historial->id;
$soft_instal->id_usuario = $request->id_usuario;
$soft_instal->id_version = $_POST['id_version'][$key];
$soft_instal->obs_software = $_POST['obs_software'][$key];
$soft_instal->id_tipo_venta = $_POST['id_tipo_venta'][$key];
$soft_instal->save();
}
}

id_tipo_venta seems to be an empty string which is apparently not valid.
You can try debugging what you get in :
var_dump($_POST['id_tipo_venta'][$key]);
die;
Your database field expects to receive an integer. Therefore, using the intval() function can solve your problem.
Indeed, I think your code returns an alphanumeric string.
Therefore, the code below will return 0 in all cases if no version is returned (not set, string or simply null):
$soft_instal->id_tipo_venta = intval($_POST['id_tipo_venta'][$key]);
On the other hand, intval() will always convert to int, so a decimal will be converted, example :
intval("1.1") // returns 1
intval("v1.1") // returns 0
If this is not the desired behavior, maybe you should think about changing your database type.
EDIT :
Of course, you can also set the value as null if you prefer to 0. You must allow nullable values in your database.

id_tipo_venta can not be empty, try with some number or change type column to varchar in the database

Related

Data class .copy only if nullable parameter is not null

I have a Front-End application that sends me Data to update my User (updatedUser). Since I don't want to send the whole Userdata, I'm only sending the data that has changed. Now I want to Update my Userdata with the changes provided, so I'd like to know if there is a more elegant way to do this than just a list of ifs/lets. I'm quite new to kotlin, so don't expect too much from me^^
Not so elegant way:
changeData.firstname?.let { updatedUser.firstname = it }
changeData.lastname?.let { updatedUser.lastname = it }
...
Expected (doesn't work - type mismatch):
updatedUser.copy(
firstname = changeData?.firstname,
lastname = changeData?.lastname,
...)
the reason you get a type mismatch is There is a string type and a string nullable type
var variableName:String = "myData" // if you want a non nullable
var variableName:String? = "myDataThatCouldBeNull" // if you want a string that could be null

using sql reader to check for nulls when setting multiple values

I have a sql command that is picking up a row in my DB but sometimes one of the datetime values may be null.
example:
var reader = command.ExecuteReader();
if (reader.HasRows)
{
List<AdmissionsVm> appDetailsOut = new List<AdmissionsVm>();
while (reader.Read())
{
appListOut.Add(new AdmissionsVm
{
Parish = Convert.ToString(reader.GetValue(40)),
CofE = Convert.ToBoolean(reader.GetValue(41)),
OtherFaith = Convert.ToString(reader.GetValue(42)),
PrefSiblingName1 = Convert.ToString(reader.GetValue(43)),
if (!reader.GetValue(44).IsDbNull){SiblingDateOfBirth = Convert.ToDateTime(reader.GetValue(44))}
SiblingGender = Convert.ToString(reader.GetValue(45))
});
}
}
I am actually bringing back a lot of details but when the siblingdateofbirth is null, i cant seem to check it as i am getting errors with fields that have been added afterwards
any help would be appreciated
Its often better to specify the column name instead of the column position because if the query for some reason changes the order in which its returning columns, you may need to change the params of all the GetValue calls.
To check for null try something like this
if (!reader.IsDBNull(reader.GetOrdinal("YourColumnNameForPosition44")))
{SiblingDateOfBirth = Convert.ToDateTime(reader.GetString(reader.GetOrdinal("YourColumnAgain"))}

Convert IList<Interface> to List<Class>

List<CurrentElectionService> result = new List<CurrentElectionService>();
result = oElectionsManager.GetCurrentElectionsByEId(
employeeId.StringToGuid(), planYear) as List<CurrentElectionService>;
Public class CurrentElectionService : ICurentElection
{
// Implement Interface fields here
}
The method GetCurrentElectionsByEId returns me IList<ICurentElection> and I want to cast the interface into class CurrentElectionService, but it returns null. Please help.
Why not use LINQ to perform your cast
List<CurrentElectionService> result = oElectionsManager.GetCurrentElectionsByEId(
employeeId.StringToGuid(), planYear).Cast<CurrentElectionService>().ToList();
I hope this helps.
You need to find out of which type the actual return value is. The as keywort always returns null if your actual object is not of the type you want to cast it to.
With the definition you gave you could also try this:
List<ICurentElection> result;
result = oElectionsManager.GetCurrentElectionsByEId(
employeeId.StringToGuid(), planYear) as List<ICurentElection>;

"update" query - error invalid input synatx for integer: "{39}" - postgresql

I'm using node js 0.10.12 to perform querys to postgreSQL 9.1.
I get the error error invalid input synatx for integer: "{39}" (39 is an example number) when I try to perform an update query
I cannot see what is going wrong. Any advise?
Here is my code (snippets) in the front-end
//this is global
var gid=0;
//set websockets to search - works fine
var sd = new WebSocket("ws://localhost:0000");
sd.onmessage = function (evt)
{
//get data, parse it, because there is more than one vars, pass id to gid
var received_msg = evt.data;
var packet = JSON.parse(received_msg);
var tid = packet['tid'];
gid=tid;
}
//when user clicks button, set websockets to send id and other data, to perform update query
var sa = new WebSocket("ws://localhost:0000");
sa.onopen = function(){
sa.send(JSON.stringify({
command:'typesave',
indi:gid,
name:document.getElementById("typename").value,
}));
sa.onmessage = function (evt) {
alert("Saved");
sa.close;
gid=0;//make gid 0 again, for re-use
}
And the back -end (query)
var query=client.query("UPDATE type SET t_name=$1,t_color=$2 WHERE t_id = $3 ",[name, color, indi])
query.on("row", function (row, result) {
result.addRow(row);
});
query.on("end", function (result) {
connection.send("o");
client.end();
});
Why this not work and the number does not get recognized?
Thanks in advance
As one would expect from the initial problem, your database driver is sending in an integer array of one member into a field for an integer. PostgreSQL rightly rejects the data and return an error. '{39}' in PostgreSQL terms is exactly equivalent to ARRAY[39] using an array constructor and [39] in JSON.
Now, obviously you can just change your query call to pull the first item out of the JSON array. and send that instead of the whole array, but I would be worried about what happens if things change and you get multiple values. You may want to look at separating that logic out for this data structure.

CI active record, escapes & order_by datetime column

I've noticed that when ordering by a datetime column in CI with active record, it's treating the column as a string, or int.
Example:
$this->db->limit(12);
$this->db->where('subscribed',1);
$this->db->join('profiles','profiles.user_id=users.id');
$this->db->where('active',1);
$this->db->select('users.thumbUpload,users.vanity_url');
$this->db->select('users.created_on as time');
$this->db->order_by('time');
$query = $this->db->get('users');
This is where users.created_on is a datetime field. Firstly, is it because active record is rendering time escaped, or is it something else? And if it is, can I prevent the escaping on order_by somehow?
Also, stackoverflow, please stop autocorrecting 'datetime' to 'date time'. It's annoying.
Cheers!
When you set second argument as false, function wont check and escape string. Try this
$this->db->select('users.created_on as time', FALSE);
Or for you query use
$this->db->order_by('users.created_on', 'DESC'); //or ASC
And for complex queries
$this->db->query("query");
According to the signature of the method in core files of CI (currently 2.2), it does not have any option to allow to choose whether or not to escape.
// The original prototype of the order_by()
public function order_by($orderby, $direction = '') {
// Definition
}
As you see there is not argument as $escape = true in the argument list. One way to do so is to hack this core file (I normally do not suggest it, since if you upgrade CI to a newer version later, then these changes will be lost, but if you do not intend to do so, it is OK to use it).
To do so, first change the prototype as:
public function order_by($orderby, $direction = '', $escape = true) {
// Definition
}
And then check the conditions in the following parts of definition:
// Line 842
if($escape){
$part = $this->_protect_identifiers(trim($part));
}else {
$part = trim($part);
}
// Line 856
if($escape){
$orderby = $this->_protect_identifiers($orderby);
}
When you call it, to prevent the escaping:
$this->db->order_by($ORDERBY_CLAUSE, null, false);