I receive data from a API request and it contains a value "true" or "false".
Before I've used PDO::PARAM_BOOL to bind the value and insert it into MySQL
Now I'm using Laravel and I want to know how I can insert this value as boolean value 1 or 0.
I've created a migration which contains
$table->boolean('businessorder');
I save the data in an array and insert it in my table:
$orderarray = [];
foreach($csv as $data => $orderdata){
$orderarray[] = [
...
'businessorder' => $orderdata['is-business-order'],
...
];
}
I receive the following error
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'false' for column 1
The error message also shows the data to insert in the database as "false" not as 0.
How can I make sure it will insert 0 or 1 instead of true or false
When I do
'businessorder' => (bool)$orderdata['is-business-order'],
It will set everything to 1 (because (bool)'false' is true)
When you try to put the value of $orderdata['is-business-order'] into the DB column, MySQL tries to put true or false.
But true or false cannot be stored in a boolean type column. So we can do something like the below code to get 1 or 0 instead of true or false.
businessorder' => ($orderdata['is-business-order']=='true'?1:0)
According to this post you could do something like this:
'businessorder' => filter_var($orderdata['is-business-order'], FILTER_VALIDATE_BOOLEAN),
Related
I've been working on getting the data from mysql database into blade view. So, I've a field "total_sold" in my table. Below is my code
public function getDealVersions($dealId)
{
if ($dealId == "undefined") {
return array('isVersions' => FALSE);
}
$deal = Deal::find($dealId);
Log::info($deal);
$return = array(
'deal' => $deal,
'isVersions' => count($deal->versions) > 1 ? TRUE : FALSE,
'versions' => $deal->versions
);
return $return;
}
In the above code, $deal has the results from the mysql query and the value of total_sold field is 0 which is the default value but the actual value in the database is 2352. Values for all the other fields are returning the expected values except for this field "total_sold". In mysql, for the total_sold field,
type=int(11), Default Value = 0 and Nullable=YES
So, I'm not able to understand if I should change something with my query or should I change some property in the mysql. Any help or advise is greatly appreciated.
Thank You!
im use code php in method get to post in column 'tr_no_hp'
like
$nomorhp = $this->input->get('nomor_hp');
but after i try to insert in database column cant be null.
how to fix this problems
this my controllers code
$nomorhp = $this->input->get('nomor_hp');
$data = array(
'us_id' => $this->user->us_id,
'sv_id' => $voucher->sv_id,
'op_id' => $voucher->op_id,
'tr_id_plgn' => $nomor,
'tr_no_hp' => $nomorhp,
);
$this->db->insert('transaksi', $data);
$trx_id =$this->db->insert_id();
and i got this eror code
Query error: Column 'tr_no_hp' cannot be null - Invalid query: INSERT INTO `transaksi`
thanks
Assign default value of 'tr_no_hp' column to NULL in phpmyadmin
You can either modify you tables to allow null (but this might break other things) or set a default value.
For example:
$nomorhp = $this->input->get('nomor_hp') ?: ''; // Default to empty string
I'm trying to validate a request to load stock into a table. Up until now stock has always had a positive value and the following validation rule worked exactly as expected:
[
"value" => "required|integer|min:0"
]
Stock is stored and can have multiple values and now stock can have a value of zero (0), I don't think it works with the 'required' rule.
I have changed it to use 'present' which I thought should suffice however it still fails, and adding 'nullable' also doesn't work:
[
"value" => "present|integer|min:0"
]
Are there validation rules to specify that a field must be present but the value can be zero?
Your initial validation rule just keeps working as desired; required doesn't throw an error on 0:
[
"value" => "required|integer|min:0"
]
From the Laravel documentation:
The field under validation must be present in the input data and not
empty. A field is considered "empty" if one of the following
conditions are true:
The value is null.
The value is an empty string.
The value is an empty array or empty Countable object.
The value is an uploaded file with no path.
So the issue was actually with my use of $request->intersect(...) in that it treats keys with a value of zero (0) as false and therefore removes them from the request data array.
For anyone else who may encounter this issue, here is the solution to treat zero (0) values as truthy while; null values, empty strings, and false will be treated as false.
Nb. $params, $rules, and $messages are arrays. See https://laravel.com/docs/5.4/validation#manually-creating-validators for more information.
return \Validator::make(array_filter($request->only($params), function($param) {
// This is needed to strip out empty values but treat zero (0) as truthy (default array_filter behaviour is
// to treat zero (0) as false) but we want these values to be present in the validated request data array as
// zero (0) in the context of a denomination is valid now that we will hold unactivated stock in the Vault.
return ($param !== null && $param !== false && $param !== '');
}), $rules, $messages);
I am using the wordpress replace query to update/add the records But i am facing an error . It updates the records successfully But the values not in array becomes null .Here is my code
function ux_add_data($table,$postdata){
global $wpdb;
$tablename=$wpdb->prefix.$table;
$updated_data=$postdata['BX_data'];
if(isset($updated_data['isActive']) && $updated_data['isActive']==1)
$updated_data['isActive']=1;
else
$updated_data['isActive']=0;
$data=$wpdb->replace($tablename,$updated_data,array('%s') );
if($data)
return UX_flash('success','Data has been added successfully.');
else
return UX_flash('danger','Some errror to save your data.');
}
if i have columns in database recordid,ID,name,class,created,modified and in array i have only recordid,name,modified then ID,class,modified becomes null .
Please tell me where i am doing wrong.
Thanks
You're using $wpdb->replace function, please notice that
wpdb::replace( string $table, array $data, array|string $format = null )
$data
(array) (Required) Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped). Sending a null value will cause the column to be set to NULL - the corresponding format is ignored in this case.
So, while you're setting some columns, some others will set null.
find more at here.
When I use the json_encode() function, the method return a Json with two time the same value: one with the string key and one with an index. I did not have this problem before.
$req = $bdd->prepare("SELECT mail,description FROM identifiant WHERE mail = :mail AND pass=:pass");
if ($req->execute(array(
'mail' => $_COOKIE['mail'],
'pass' => $_COOKIE['pass']))) {
header('Content-type: application/json');
return json_encode($req->fetchAll());
The response:
[
{
"mail": "root#root.com",
"0": "root#root.com",
"description": "a description",
"1": "a description"
}
]
How can I do for don't have index keys ?
Use PDO::FETCH_ASSOC fetching mode:
return json_encode($req->fetchAll(PDO::FETCH_ASSOC));
It's not json_encode, it's because your PDO instance's fetch mode is set to PDO::FETCH_BOTH. See the documentation for PDOStatement::fetchAll's fetch style.
use this:
PDO::FETCH_ASSOC: returns an array indexed by column
name as returned in your result set
PDO::FETCH_BOTH (default): returns an array indexed by
both column name and 0-indexed column number as returned in your
result set
PDO::FETCH_BOUND: returns TRUE and assigns the
values of the columns in your result set to the PHP variables to which
they were bound with the PDOStatement::bindColumn()
method
PDO::FETCH_CLASS: returns a new instance of the
requested class, mapping the columns of the result set to named
properties in the class. If fetch_style
includes PDO::FETCH_CLASSTYPE (e.g. PDO::FETCH_CLASS |
PDO::FETCH_CLASSTYPE) then the name of the class is
determined from a value of the first column.
PDO::FETCH_INTO: updates an existing instance
of the requested class, mapping the columns of the result set to
named properties in the class
PDO::FETCH_LAZY: combines
PDO::FETCH_BOTH and PDO::FETCH_OBJ,
creating the object variable names as they are accessed
PDO::FETCH_NUM: returns an array indexed by column
number as returned in your result set, starting at column 0
PDO::FETCH_OBJ: returns an anonymous object with
property names that correspond to the column names returned in your
result set
PDOStatement::fetch
return json_encode($req->fetchAll(PDO::FETCH_ASSOC));
you have to use PDO::FETCH__ASSOC as a parameter
$req = $bdd->prepare("SELECT mail,description FROM identifiant WHERE mail = :mail AND pass=:pass");
if ($req->execute(array(
'mail' => $_COOKIE['mail'],
'pass' => $_COOKIE['pass']))) {
header('Content-type: application/json');
return json_encode($req->fetchAll(PDO::FETCH_ASSOC));
}