I'm working on a project that has one main article and you can attach many different articles to it. So on submit I have broken the article from into two different sections, since I need them to submit into two different tables.
After submitting the first part, I'm trying to get the last submitted id based on their user_name so I can attach the rest of the article. If that makes sense.
I've tried several different things, but nothing seems to grab back that id.
First I tried the insert_id() meathod, but that returns a 0
public function pullLastStoryId($author){
$this->db->where('author', $author);
$this->db->insert_id();
$story = $this->db->get('story_tbl');
return $story->result();
}
So then I also tried just grabbing
public function pullLastStoryId($author){
$story = $this->db->query('SELECT LAST_INSERT_ID() INTO story_tbl;')
return $story->result();
}
Any idea's
My guess is that you are talking about a foreign-key relationship between two tables. One way to do this would be something like:
$this->db->insert('author',$vals);
$id = $this->db->insert_id();
// do something with ID.
From what I can tell, you would probably then do something like this:
$story_row = $this->db->get_where('story_tbl',array('id' => $id));
You should not have to worry about different user_name property, because that will be last created ID. If you really wanted to get that row back, though, you could do this:
$author_row = $this->db->get_where('author',array('author_id' => $id));
If you need to have this ID somewhere else (say, after another form is submitted), you can either use a hidden form input or (this is a bit more secure), you can store that ID in session.
I am not clear with the question. Are you looking for something like this?
public function pullLastStoryId(){
$story = $this->db->query('SELECT id from tablename where id = LAST_INSERT_ID()')
return $story->result();
}
OR
public function pullLastStoryId(){
$id = $this->db->insert_id();
$this->db->where('id',$id);
$story = $this->db->get('story_tbl');
return $story->result();
}
If you want to get Last id, your way is wrong. $this->db->insert_id() or etc for active query. Try this: SELECT id FROM table ORDER BY id DESC LIMIT 1
Related
So I am quite new to Laravel, and I have a situation, where I am trying to gather data from a pivot table (contains 2 foreign keys only) in order to retrieve data from other tables.
Before everything, I'd like to note, that word "campaign" is the same as "box". Simply it differs in database and front.
I have multiple boxes, that contains specific gifts.
I have set the URL of the box to be something as such: http://127.0.0.1:8000/box/1
http://127.0.0.1:8000/box/2
etc..
I have done so, by simply using a button with the {id}:
View the box
My plan is, to print out only that specific boxes gifts (right now, all boxes print out all gifts).
I have tried to use the ->where option within my function, although, it seems that I can't try equaling to the campaigns ID.
Incorrect code:
function box(){
$data = array(
'list'=>DB::table('campaigns_gifts')
->join('gift_items', 'gift_items.id', '=', 'campaigns_gifts.gift_foreignK')
->select('gift_items.*')
->where($campaign_foreignK = '{id}')
->get()
);
return view('DBqueries.boxView', $data);
}
My question is, how can I specifically return data, that only belongs to that specific box, since I am not able to use mysql where option.
For reference, these are the database tables:
Basically, I would need to match my URL's id with campaign_foreignK
Thank you in advance.
First of all, yout need to start to use Laravel Eloquent Models.
But doing by your way (the hardest):
You need to create a route in web or api, something like that:
Route::get('/box/{id}', [BoxController::class, 'view']);
Then you need to put this function on your controller:
function view($id){
/**
* You can do it by 2 ways:
* 1 - Do a where in the result of DB query (the bad way)
*/
$list = DB::table('campaigns_gifts')
->join('gift_items', 'gift_items.id', '=', 'campaigns_gifts.gift_foreignK')
->select('gift_items.*')
->where($campaign_foreignK = '{id}')
->get();
$list = (array)collect($list)->where('abc', 123);
/**
* Or the second way (the best is to use the Eloquent, but using DB the following is the best)
* 1 - Get the relations:
* Is git_items id the key for gift_foreignK ? i'm supposing that is it! so....
*/
$giftsIds = array_values((array)DB::select("select * from campaigns_gifts where campaign_foreignK = $id"));
$giftsIdsString = implode($giftsIds, ',');
$list = (array)DB::select("select * from gift_items where id in ($giftsIdsString)");
return view('DBqueries.boxView', ['list' => $list]);
}
I have a strange issue in Codeigniter. I have a controller and a model to fetch product listings from MySQL. I'm using the uri-segment functions to fetch the ID and put it into the model to retrieve that specific product listing based on the ID.
The right URl would be (which works great):
http://example.com/listing/2000
However, when you type:
http://example.com/listing/2000ddd
this also works, which it shouldn't.
On the other hand, if you try to type a charachter before the id-number, it doesn't work.
http://example.com/listing/ddd2000
My controller:
public function index()
{
$listing_id = $this->uri->segment(3);
$messageinfo = $this->Messages_model->get_messageinfo($listing_id);
$data["messageinfo"] = $messageinfo;
$this->load->view('inc_includes/header');
$this->load->view('pages_sendmessage/sendmessage', $data);
$this->load->view('inc_includes/footer');
}
My model:
function get_messageinfo($listing_id = NULL)
{
$this->db->select('
azzo.listing_ads.listing_ads_id,
azzo.listing_ads.listing_ads_domain_url,
azzo.listing_ads.listing_ads_expire,
azzo.listing_ads.listing_ads_user_id,
azzo.users.username,
azzo.listing_ads.listing_ads_outprice
');
$this->db->from('azzo.listing_ads');
$this->db->join('azzo.users', 'azzo.listing_ads.listing_ads_user_id = azzo.users.id', 'inner');
$this->db->where('azzo.listing_ads.listing_ads_id', $listing_id);
$query = $this->db->get();
if($query->num_rows() == NULL)
{
return false;
}
else
{
return $query->row();
}
}
Any suggestions? What am I doing wrong here?
The reason behind your problem is - your data($listing_id) is converted to integer type when used in model. When you pass 2000ddd as parameter, you will get 2000, but when you pass ddd2000, you will get 0.
Yep, what #Jobayer said... That's PHP performing type casting behind the scenes... So it's taking a guess by how it's being used which in this case, is an integer.
Just be aware that when you allow data entry via a URL or by any user input, it is open to folks trying out all sorts of things. You could test that the segment is meant to be an integer by using is_integer($expected_integer_variable_to_check) and take the appropriate action like even just ignoring it...
I want to delete all record according to id and then insert record in same table,I tried many ways but can't find solution please help me.
Basically as per the document id i want to delete all document but it is not working.
Here is my controller code:
foreach ($receievers as $user) {
$this->shareRepo->deleteSharedDoc($resourceId);
$this->shareRepo->saveshareSharedDoc($resourceId, $user->id,$this->getCurrentUser());
}
The repository code:
function saveSharedDoc($resourceId, $sharedWith, $resourceOwnerId){
$shareDocs = new ShareDocs;
$shareDocs->resource_id = $resourceId;
$shareDocs->shared_with = $sharedWith;
$shareDocs->user_id = $resourceOwnerId;
$shareDocs->shared_on = $this->getCurrentDateTime();
$shareDocs->token = str_random(20);
$shareDocs->save();
return $shareDocs->token;
}
function deleteSharedDoc($resourceId){
$network = ShareDocs::where('resource_id','=',$resourceId);
$result=$network->delete();
return $result;
}
Please help me out
It's seems you're doing it correctly. But there are two things that you have to change.
You are calling to saveshareSharedDoc method within foreach loop to save data. but actual method name on your repo is saveSharedDoc. (there two "share" words on loop)
you can return deleted rows directly return ShareDocs::where('resource_id', $resourceId)->delete();
I currently have a website which should be able to take notes from user input and save them into the database. I'm looking for some guidance on the best way to achieve this.
The website should only show the most recent notes that were added, but all other notes should still be saved(but hidden). I don't know how many times the user will enter notes. My initial thought was to dynamically add a column to the database each time the user enters notes, but then I'd end up having a new column for every notes entry.Its worth mentioning that the notes are associated with a filename, so there may be many rows in the database that will all have different notes.
The dbforge method was the way I was going to go about it but that will repeatedly try to add 'notes' to the database (which will already exist after one go).
$fields = array(
('notes') => array('type' => 'TEXT','constraints' =>'255')
);
$this->dbforge->add_column('mytable', $fields);
Would anyone know a better way of doing this? I'm using php and the codeigniter framework.
All help is much appreciated!
I would have a notes table which stores User Id, Note and Date Added.
In your view, your form will point to this in your controller:
public function addNote($user_id)
{
$this->form_validation->set_rules('note', 'Note', 'required');
if ($this->form_validation->run() == true) {
$array = array (
'user_id' => $user_id,
'note' => $this->input->post('note')
);
$this->your_model->addRecord('notes', $array);
}
}
The addRecord() function in your model would look like:
public function addRecord($table, $array)
{
$this->db ->insert($table, $array);
return $this->db->insert_id();
}
You can then do a query like this and pass the results back to your view:
public function getLatestNoteByUser($user_id)
{
$this->db->select('id, note')
->from('notes')
->where('note_added_by', $user_id)
->order_by('date_added', desc)
->limit(1);
return $this->db->get()->row();
}
This will return only the last note added by a specified user. You could set the limit to whatever value you want and return row_array() instead of row(). You could even pass $limit, in the functions parameters and use ->limit($limit).
I'm trying to learn the code igniter library and object oriented PHP in general and have a question.
I've gotten as far as making a page which loads all of the rows from my database and in there, I'm echoing an anchor tag which is a link to the following structure.
echo anchor("videos/video/$row->video_id", $row->video_title);
So, I have a class called Videos which extends the controller, within that class there is index and video, which is being called correctly (when you click on the video title, it sends you to videos/video/5 for example, 5 being the primary key of the table I'm working with.
So basically all I'm trying to do is pass that 5 back to the controller, and then have the particular video page output the particular rows data from the videos table. My function in my controller for video looks like this:
function video()
{
$data['main_content'] = 'video';
$data['video_title'] = 'test';
$this->load->view('includes/template', $data);
}
So ya, basically test should be instead of test, a returned value of a query which says get in the table "videos", the row with the video_id of "5", and make $data['video_title'] equal to value of video_title in database...
Should have this figured out by now but don't, any help would be appreciated!
I don't know if I'm too late but maybe this can solve your problem...
put this in your video() function
data[$query] = $this->db->query("SELECT * FROM videos WHERE video_id = 5");
and then that in your video_view file...
if ($query->num_rows() > 0)
{
$row = $query->row_array();
echo $row['title'];
echo $row['something'];
echo $row['somethingElse'];
}
this is a good resource: http://codeigniter.com/user_guide/database/index.html
hope that helps...
and please someone edit the question because it's too hard to read...
What you need is to understand how the URI Class works
Basically:
$default_url_args = array('video');
$url_args = $this->uri->uri_to_assoc(3,$default_url_args);
$video_UID = $url_args['video'];
and then something like
$the_video = $this->videos_model->get_video_by_UID($video_UID);
You could use the URI Class, or you can do the following:
function video($video_id)
{
$data['main_content'] = $this->videoprovider->get_video( $video_id );
$data['video_title'] = 'test';
$this->load->view('includes/template', $data);
}
In other words, with functions inside classes that extend Controller, you can add parameters to those functions and CI will automatically pass in the URI items in order to those parameters.
function generic_function_in_controller($item1, $item2, ...)
{
// would receive as: http://example.com/controller/generic_function_in_controller/item1/item2
}