Field mysql with multiple value - php

I have a field reply_level in a reply table.
   
protected function buildDomainObject(array $row)
{
$reply = new Reply();
$reply->setId($row['reply_id']);
$reply->setAuthor($row['reply_author']);
$reply->setContent($row['reply_content']);
$reply->setComParent($row['com_id']);
$reply->setLevel($row['reply_level']);
if (array_key_exists('art_id', $row))
{
$commentaireId = $row['art_id'];
$article = $this->articleDAO->find($commentaireId);
$reply->setArticle($article);
}
return $reply;
}
public function save(Reply $reply) {
$commentData = array(
'reply_content' => $reply->getContent(),
'reply_author' => $reply->getAuthor(),
'com_id' => $reply->getComParent(),
'art_id' => $reply->getArticle()->getId(),
'reply_level' => $reply->getLevel()
);
if ($reply->getId()) {
// update comment
$this->getDb()->update('t_reply', $commentData, array('reply_id' => $reply->getId()));
} else {
// The comment has never been saved : insert it
$this->getDb()->insert('t_reply', $commentData);
// Get the id of the newly created comment and set it on the entity.
$id = $this->getDb()->lastInsertId();
$reply->setId($id);
}
}
I would like to pass several values to reply_level, either reply_level, reply_level1, reply _level2, reply_level3 ...(Depending on the level of the sub-comment). How to pass multiple values ? i use pdo mysql.
Thank you

Related

how to pass the data in the post so that we can call the id?

how to pass the data in the post so that we can call the id ?
because we are trying to get the "qtopic_id" of the question but its not working and it keeps on giving me a null value.
I have tried declaring qtopic_id= 19 to see if its saving in the qtopic_id column.
I don't have to put a specific id value to save on the following column so that it wont save on that specific id only but instead it will save on its corresponding qtopic_id.
controller
public function addChoices(){
$this->form_validation->set_rules('ques','Question','required');
$this->form_validation->set_rules('ch_des1','Choices','required');
$this->form_validation->set_rules('ch_des2','Choices','required');
$this->form_validation->set_rules('ch_des3','Choices','required');
$this->form_validation->set_rules('ch_des4','Choices','required');
$this->form_validation->set_rules('ans','Answer','required');
$this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
if($this->form_validation->run() ){
echo $qtopic_id ;
$data['ques'] = ($this->input->post('ques'));
$data['ch_des1'] = ($this->input->post('ch_des1'));
$data['ch_des2'] = ($this->input->post('ch_des2'));
$data['ch_des3'] = ($this->input->post('ch_des3'));
$data['ch_des4'] = ($this->input->post('ch_des4'));
$data['ans'] = ($this->input->post('ans'));
if($id=$this->queries->registerChoices($data) )
{
$this->session->set_flashdata('message','Test Added Succesfully');
return redirect('admin/testtwo');
}
else {
$this->session->set_flashdata('message','Failed to Add Test');
}
return redirect('admin/testtwo');
}
else {
$this->addQuestion();
}
}
}
model:
----updated---
public function registerChoices($data) {
echo $this->input->post('qtopic_id');
$question_arr = [
'ques' => $data['ques'],
'qtopic_id' => 19
];
$choices_arr = [
'ques' => $data['ques'],
'ch_des1' => $data['ch_des1'],
'ch_des2' => $data['ch_des2'],
'ch_des3' => $data['ch_des3'],
'ch_des4' => $data['ch_des4'],
'ans' => $data['ans']
];
// echo "<pre>";
// var_dump($question_arr);
// var_dump($choices_arr);
// exit;
$this->db->insert('tbl_choices',$choices_arr);
$this->db->insert('tbl_question',$question_arr);
return $this->db->insert_id();
}
error messages that i encountered
Your code for register choices is a bit unclear. insert_id isn't a function that accepts data nor does it do inserting, it simply returns the last inserted id after you perform an insert query. I think what you want is something like:
function registerChoices($data) {
if ($this->db->insert('tablename', $data)) {
return $this->db->insert_id();
}
return false;
}
Usage:
$last_insert_id = $this->somemodel->registerChoices($data);
if ($last_insert_id) {
echo "item with id $last_insert_id was created!";
} else {
show_error('Query failed!');
}

How can I pass a variable from view to model in mvc (PHP)

I'm working on a similar thing as this one. But I'm trying to assign button either "Join" or "Enter" based on if someone joined the group. The problem is that I'm not sure how I can pass the variable from the category ID ($cats_id) to the view file.
I created a function in the model that checks if the row exists and returns true.
// check if joined the group
public static function checkIfJoined($cats_id)
{
$database = DatabaseFactory::getFactory()->getConnection();
$users_id = Session::get('user_id');
$sql = "SELECT cats_id,users_id FROM categories_joined WHERE users_id = :users_id AND cats_id = :cats_id";
$query = $database->prepare($sql);
$query->execute(array(':users_id' => $users_id, ':cats_id' => $cats_id));
// fetchAll() is the PDO method that gets all result rows
if ($query->rowCount() >= 1 || Session::get('user_account_type') == 7) {
return true;
}
}
Then in Controller I render the model to the view.
public function index()
{
$cats_id = ""; // this doesn't work right obviously
$this->View->render('dashboard/index', array(
'categories' => DashboardModel::getAllCategories(),
'joined' => DashboardModel:: checkIfJoined($cats_id)
));
}
in the view I pass the variable from the preview function 'categories'.
<?php if ($this->categories) { ?>
<?php foreach($this->categories as $key => $value) { ?>
...
<?php $cats_id = $value->cat_id; if ( $this->joined == true ): ?>Enter
<?php else: ?>Join
<?php endif; ?>
You can never pass anything from view to controller because view is parsed after controller.
What you can do here is use model directly by calling DashboardModel::checkIfJoined($cats_id) in your view but that's not perfect approach.
It'll be better to prepare that data in the controller and then pass it to view.
Example controller
public function index()
{
$this->View->render('dashboard/index', array(
'categories' => DashboardModel::getAllCategories(),
'userCategories' => DashboardModel::getUserCategories()
));
}
Example view
<?php
if ($this->categories) {
foreach ($this->categories as $key => $value) {
if (in_array($value->id, $this->userCategories) {
echo 'Joined';
} else {
echo 'Join';
}
}
?>
In this example DashboardModel::getUserCategories() should return results from SELECT cats_id FROM categories_joined WHERE users_id = :users_id.

SilverStripe dependent dropdown - x is not a valid option

I have a simple dropdown field with 2 values and a dependent dropdown field:
public function areaForm() {
$datasource = function($val) {
if ($val =='yes') {
$areas = DataObject::get('Area', 'ParentID = 0');
return $areas->map('ID', 'Name');
}
if ($val == 'no') {
return false;
}
};
$fields = new FieldList(
TextField::create('Name', 'Area Name:'),
$dropField = DropdownField::create('isChild', 'Is this a sub Area?', array('yes' => 'Yes', 'no'=>'No' ))
->setEmptyString('Select one'),
DependentDropdownField::create('ParentSelect', 'Select Parent Area:', $datasource)
->setDepends($dropField)
->setEmptyString('Select one')
);
return new Form($this, __FUNCTION__, $fields, FieldList::create(new FormAction('doSaveArea', 'Save area')));
}
public function doSaveArea($data, $form) {
var_dump($data);
exit;
$name = $data['Name'];
$isChild = $data['isChild'];
if ($isChild === 'no') {
$area = new Area();
$area->Name = $name;
$area->ParentID = 0;
$area->write();
}
elseif ($isChild === 'yes') {
$area = new Area();
$area->Name = $name;
$area->ParentID = $data['ParentSelect'];
$area->write();
}
$this->redirectBack();
}
When ever I try to save my object by submitting the form, it gives me the same message:
Please select a value within the list provided. x is not a valid option
The values are being populated correctly. I can see them in the browser by inspecting the element. Yet if I select ID 1 for example it says "1 is not a valid option" etc for each Area object. It gets stuck at validation, doesn't even go to the action. I've done similar things in other parts of the site/other sites and they work fine.
Why is this validation incorrectly blocking the form submission and how do we fix this?
Seems like you just need to create an Array of your Map object.
if ($val =='yes') {
$areas = Area::get()->filter('ParentID', '0');
return $areas->map('ID', 'Name')->toArray();
}
Normally you could just use the Map object as the source for a DropdownField. But I think the DependentDropdownField has a little trouble with the Map object.

Getting the rowid after adding an item with CI cart?

On the codeigniter website it says the the insert() method will return a $rowid of the latest inserted product. However How exactly do I grab it?
$data = array();
$insert = $this->cart->insert($data);
I tried $insert['rowid'] and $insert->rowid but neither seem to work.
Thank you!
introducing: insert_id()
like this
$id = $this->db->insert_id();
return $id;
in your model, lets call it friend_model
function insertRow()
{
// Prepare data, normally you would pass this in
$data = array(
'first' => 'john',
'last' => 'smith'
);
// insert data
$this->db->insert( 'friends', $data );
// confirm insert
if ( $this->db->affected_rows() == '1' )
// return new ID
{ $id = $this->db->insert_id();
return $id; }
// else did not insert, return false
else {return FALSE;}
}
in your controller, check if you got an id back from model
if(! $id = $this->friend_model->insertRow() )
// it no work
{ // some error method
}
else
{ // success !
}

Returning NULL from query for datatables

I'm wondering what would be best to do. Right now I have running a query to see if I have any results returned and if none are returned I return NULL.
On my controller I send that resultset whether it be an object or NULL to my table and it echos the rows on the view page.
For my tables I am using the jquery datatables plugin. I'm trying to figure out how I can have it handle the data when the sent value is NULL that way it doesn't show me an error when it hits my foreach loop.
Controller:
$news_articles = $this->news_model->get_news_articles();
$this->data['news_articles'] = $news_articles;
Model:
/**
* Get news articles
*
* #return object
*/
function get_news_articles()
{
$query = $this->db->get($this->news_articles_table);
if ($query->num_rows() > 0) return $query->result();
return NULL;
}
View:
$tmpl = array ( 'table_open' => '<table class="table" id="newsarticles-table">' );
$data = array('name' => 'newsarticles', 'class' => 'selectall');
$this->table->set_heading(form_checkbox($data), 'ID', 'Date', 'Title');
$this->table->set_template($tmpl);
foreach ($news_articles as $row)
{
$checkbox_data = array(
'name' => 'newsarticles',
'id' => $row->id
);
$this->table->add_row(form_checkbox($checkbox_data), $row->id, $row->date_posted, $row->article_title);
}
echo $this->table->generate();
I typically respond using JSON and then add a "success" type boolean and then check that value before trying to process any data. It also allows for an easy way to place an error message in the response if something goes wrong.
Just another idea
Model
function get_news_articles()
{
$query = $this->db->get($this->news_articles_table);
if ($query->num_rows() > 0) return $query->result();
return FALSE;
}
Controller
$news_articles = $this->news_model->get_news_articles();
if(!$news_articles) $this->data['success'] = FALSE;
else
{
$this->data['news_articles'] = $news_articles;
$this->data['success'] = TRUE;
}
In the view
if($success)
{
foreach ($news_articles as $row)
{
//....
}
}
else echo "No results found !";
Just return an empty array from the model, if there are not results. That way your foreach won't break. It just won't loop over anything.

Categories