Why my fields are not getting added to the database? - php

I am trying to add some fields to the column of my table. When I check my table, I see that the column could be created but the fields could not be added. However, I get no error or anything.
public function isset_row($target, $sender_table, $receiver_table, $sender_row) {
$this->load->model('Connection_model');
if ($this->Connection_model->get_custom_db($target)->get($sender_table)) {
// Add column(s)
$this->myforge = $this->load->dbforge($this->Connection_model->get_custom_db('receiver'), TRUE);
$fields = array(
$sender_row => array('type' => 'TEXT')
);
$this->myforge->add_column($receiver_table, $fields);
$query = $this->Connection_model->get_custom_db('sender')->get($sender_table);
foreach ($query->result() as $row) {
echo $row->$sender_row . '<br>'; // Returns fields from a table (string)
echo $receiver_table; // Returns table name (string)
$this->Connection_model->get_custom_db('receiver')->update($receiver_table, $row->$sender_row);
}
}
}
Edit1:
var_dump($this->Connection_model->get_custom_db('receiver')->update($receiver_table, $row->$sender_row));
This line returns bool(false)
Edit2:
With the update() function I am just saying to add the fields to the table but I am not saying to which column of the table. I think that must be the point but how can I specify the column when trying to update?

Complete your model get_custom_db(). Use get() query builder method in model. So your condition should like this
if ($this->Connection_model->get_custom_db($table_name)) {
...
}
and use get() in model
public function get_custom_db($table_name){
....
$test = $this-db->get($table_name);
return $test->result();
}
OR provide the model code, I'll figure out it for you. Thanks

Related

Show error message when detected duplicate entry

I wanted to let the system to show error message when detect duplicated entry of full_name column without applying unique in the full_name column from public function rules() in model.
My code is like this :
if ($model->load(Yii::$app->request->post()) ) {
$model->full_name = $model->first_name .'' . $model->last_name ;
$name = StudentInfo::find()->select('full_name')->where(['full_name'=> $model->full_name]);
if($name == $model->full_name ){
echo "<script type='text/javascript'>alert('Same student name is detected');</script>";
}
else{
$model->status ="Active";
$model->call_format = Countries::find()->select('phonecode')->where(['name'=> $model->country]);
$model->date_created = new Expression('NOW()');
$user->user_type ='student';
$user->user_name = $model->full_name;
$user->user_status = $model->status;
$user->authKey = Yii::$app->security->generateRandomString(10);
$user->accessToken = Yii::$app->security->generateRandomString(10);
$user->save();
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
}
But it shows error like :missing required parameters: id. When i apply model->save(false) ,it seems that the sql statement wont run because of duplicate entry in full_name column. How do i fix it?
Well, there is a construct exists() for such a purposes (see Yii2: check exist ActiveRecord model in database ).
if(StudentInfo::find()->where(['full_name'=> $model->full_name])->exists()){
echo "<script type='text/javascript'>alert('Same student name is detected');</script>";
}
else{...}
it generates the EXISTS query, which is faster and you don't have to load all the data from DB.
If you don't have such a column in your table, then check it by the first/last name.
change it:
$name = StudentInfo::find()->select('full_name')->where(['full_name'=> $model->full_name]);
To:
$name = StudentInfo::find()->select('full_name')->where(['full_name'=> $model->full_name])->one();
Also, if you use the select() method, to use the update() and save() or updateCounters() ... methods, you need the row ID in the same query.
Example:
->select('id') or ->select(['id', 'full_name'])
info: Multi-parameter is an array in select()
:missing required parameters: id
could mean that it couldn't find id, not by duplicate entry in full_name column. please check again
There are two problems with your code.
$name = StudentInfo::find()->select('full_name')->where(['full_name'=> $model->full_name]);
When this line is executed the $name variable will contain instance of yii\db\ActiveQuery. You want to call some method, that will actually execute your query and return result.
You can use scalar() to get the selected value. In that case the $name will contain the content of full_name column from result.
$name = StudentInfo::find()
->select('full_name')
->where(['full_name'=> $model->full_name])
->scalar();
Or you can use count() to get the number of rows that match condition. In that case you may leave out the select() method call but you will need to modify your condition
$count = StudentInfo::find()
->where(['full_name'=> $model->full_name])
->count();
if ($count > 0) {
echo "<script type='text/javascript'>alert('Same student name is detected');</script>";
} else {
// ...
}
The other problem is that you are not checking whether your $model->save() was successful. If your $model is new instance and the id attribute is auto-generated then when $model->save fails the $model->id is empty and then you are trying to redirect user to view with empty id.
Your code should look like this:
if ($user->save() && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
If the save fails because of validation the validation errors will be stored in models and if you are using ActiveForm widget the errors will be displayed. If you are not using ActiveForm you should do something to tell user that operation failed.
Since you are saving two different models you might want to consider use of transactions to prevent a situations where $user model is saved but save of $model fails.

Laravel - Update database record if already exists - all fields

I am trying to get Laravel to update a database record, if it's already exists. This is my table:
id | booking_reference | description | date
------------------------------------------------------
PRI KEY | UNIQUE | MEDIUM TEXT | DATE
AUTO INC | |
My model looks like this:
Document.php:
class Document extends Model
{
protected $fillable = [
'booking_reference', 'description', 'date'
];
}
And my controller, looks like this - please note that it's webhook() that's being called.
DocumentController.php:
class DocparserController extends Controller
{
//This is the function to capture the webhook
public function webhook(Request $request)
{
$document = new Document();
$document->fill($request->all());
//Grab the date_formatted field from our request.
$document->date = $request->input('date_formatted');
$document->updateOrCreate(
['booking_reference' => $document->booking_reference],
//How can I do so it updates all fields?
);
return response()->json("OK");
}
}
So my problem is, that I cannot figure out how to update my entire row, where the booking_reference is already present.
I want to update all fields (description, date), without having to enter them all like:
['booking_reference' => $document->booking_reference],
['description' => $document->comments, 'date' => $document->date]
Document::updateOrCreate(
['booking_reference' => $request->input('booking_reference')],
$request->all() + ['date' => $request->input('date_formatted')]
);
If you wanted to adjust the request inputs before calling that you could do that mapping and slim this down.
$request->merge(['date' => $request->input('date_formatted')]);
// now $request->all() has `date`
...updateOrcreate(
[...],
$request->all(),
)
That particular field has to be mapped at some point ... if you really really wanted to you could actually have a middleware do this mapping, which would slim this down to just $request->all() as the second array.
Or even set up a mutator for date_formatted that sets date.
Basically this has to happen somewhere, it just depends where.
You can use any one of the following to check if the records exists and run the update query if the data already exists.
$user = Document::where('booking_reference', '=', $request->booking_reference)->first();
if ($user === null) {
// user doesn't exist
}
OR
if (Document::where('booking_reference', '=', $request->booking_reference)->count() > 0) {
// user found
}
Or even nicer
if (Document::where('booking_reference', '=', $request->booking_reference)->exists()) {
// user found
}
And i do not think you can update an entire row of data at once. You have to point which attribute to update to which one.
I would have a private function to normalize the input data:
private static function transformRequestInput($requestArray)
{
$map = ['date_formatted'=>'date'];
foreach($map as $key=>$newKey){
if(isset($requestArray[$key])) {
$requestArray[$newKey] = $requestArray[$key];
unset($requestArray[$key]);
}
}
return $requestArray;
}
And I would use it like so:
$document->updateOrCreate(
['booking_reference' => $document->booking_reference],
self::transformRequestInput($request->all())
);
If you want a class or object to associative array (properties must be public):
$updateArr = (array) $document;
$document->updateOrCreate($updateArr);
However, you use a protected property ($fillable) so you must:
$document = new Document();
$document->fill($request->all());
//Grab the date_formatted field from our request.
$document->date = $request->input('date_formatted');
$reflection = new ReflectionClass($document);
$property = $reflection->getProperty('fillable');
$property->setAccessible(true);
$updateArr = (array) $property->getValue($document);
$property->setAccessible(false);
$document->updateOrCreate($updateArr);
return response()->json("OK");

How to add a new key in result of codeigniter model return result()

I have a function in my model that get all company details I am fetch this
I have to add a new key city_name in my return result() how can I add ?? I am very confused but I am not get any useable example.
function xxxx($search=array(),$page,$limit){
$this->db->select("*");
$this->db->from("xxx");
$this->db->join("xx","xx.xx=xxx.xx");
$this->db->limit($limit,$page);
$company_data = $this->db->get();
if($company_data->num_rows()){
return $company_data->result();
}
else{
return 0;
}
}
Change the following line:
return $company_data->result(); // It return Stc Class Object
to
return $company_data->result_array(); // Now it returns an array
Now you can use array_push() function, it inserts one or more elements to the end of an array.
Or simply use:
$company_data['index'] = value;
Keep your model same return $company_data->result().
In your controller, you need to iterate it for the number of results you get and add new key to your objects.(result() method returns Standard Class Object).
function yourControllerMethod()
{
$company_data = $this->your_model->xxx(search_array, $page, $limit);
if(!empty($company_data)
{
foreach($company_data as $cd)
{
$cd->city_name = "pune"; // or anything you want
}
}
var_dump($company_data);
}
Try this to add new key to your results.
Edit:
You asked that you don't have city_name key in your object.
Yes, you don't have. The above code adds a key in your object.
Just like array.
$temp = array();
$temp["id"] = 1;
In this code, initially the array is empty, the next statement add the id as key in the array.

Laravel update controller with many inputs

I have a resource and I'm trying to set up the update controller. In my case my edit form has many inputs and I need to update the database with them but there might be columns in the database not changed by the edit form. So I have my controller like this:
public function update($id)
{
$hostess = Hostess::find($id);
$inputs=Input::all();
foreach ($inputs as $key => $value) {
$hostess->$key= $value;
}
if ($hostess->save())
{
return Redirect::route('hostesses.show', $hostess->id);
}
return Redirect::back()->withInput()->withErrors($hostess->getErrors());
}
This gives me an error because I am using PUT in my view and I get
Column not found: 1054 Unknown column '_method' in 'field list'
Because my Input::all() is getting the hidden inputs for the PUT method. I can use Input::except() for that, but is that the proper way of updating with laravel?
You can actually do something like this:
$hostess = Hostess::find($id)
$post_data = Input::all();
// or
$post_data = Input::except('_method');
// warning untested if block below
if ($hostess->update($post_data))
{
return Redirect::route('hostesses.show', $hostess->id);
}
return Redirect::back()->withInput()->withErrors($hostess->getErrors());
As short as that would update all available key and value pairs.
Do note that you have to add the columns to the $fillable property in the model to avoid the mass assignment warning.
You could do something like this:
$inputs = Input::all();
$inputs = array_except($input, '_method');

Model returning null values

I'm a new bee to web development. I need to get data (some columns) from the job table and filter it according to the user name in the session and a status value (status is a TINYINT there for contains 0 and 1).
Here is my model:
public function show_work() {
$user_name = $this->session->userdata('Name');
$this->load->database();
$this->db->select('jbStageID, Description, StartDate, SpecialDetails, EstimateTime, Instrauctions');
$this->db->where('Name',$user_name);
$this->db->where('status','0');
$rset=$this->db->get('job');
$result=$rset->result_array();
}
Here is my controller:
public function employees()
{
$this->load->model('show_details');
$result= $this->show_details->show_work();
$data = array();
$data['inbox'] = $this->show_details->show_work();
var_dump($result);
echo "<pre>";
print_r($data);
echo "</pre>";
die();
}
The issue is I don't get values from the database but value null with empty array.
The result is like this:
Array(
[inbox] =>
)
You need to use the return to return the data as below in the model's last line:
$result=$rset->result_array();
return $result;
you missed $this->db->from
that means from table in sql query.

Categories