Can anyone tell me why $Role is being ignored?
I am trying to pass an argument and it is always getting a null value, however, when I call the method the var_dump shows that the $Role is 2.
When I use the var_dump inside getListFromDB the $Role is being set to null.
Method getListFromDB()
function getListFromDB($tableName, $orderBy = 'Description', $where = null, $Role = null) {
DO_Common::debugLevel(0);
if (empty($tableName) || empty($orderBy))
throw new Exception("tableName and orderBy cannot be left empty");
var_dump($Role);
if (!empty($Role))
{
echo "here";
if ($Role === 2)
{
if ($tableName == 'AssetTypes')
{
$params = array('tableName' => 'AssetTypes',
'orderBy' => $orderBy,
'whereAdd' => 'Restricted = 1');
}
var_dump($params);
}
else
{
$params = array('tableName' => $tableName,
'orderBy' => $orderBy);
var_dump($params);
}
}
else
{
$params = array('tableName' => $tableName,
'orderBy' => $orderBy);
//var_dump($params);
}
if (!empty($where) && $table != 'AssetTypes') {
if (strpos(strtolower($where), 'flag') === false)
$where .= " AND Flag != " . fDELETED;
$params += array('whereAdd' => $where);
}
return DO_Common::toAssocArray($params);
}
How the method is being called:
$AssetTypesOptions = getListFromDB('AssetTypes', $Role);
Is there something I am missing here?
$Role is the fourth argument for the function but you are sending it as the second argument:
$AssetTypesOptions = getListFromDB('AssetTypes', 'Description', null, $Role);
You should call it as the fourth argument, like so:
getListFromDB("tablename", "some fancy description", "here", $Role);
I made them up obviously...
Related
I want to call my function but when I call it I have a problem with curly Brackets at the end of my code and i have this error Error SYMFONY ( {} ) in my Controller.
I have no idea where to put them for my code to work. I have this problem when I add my function that allows me to retrieve the
history of the action. The mentioned function goes as this:
$this->logHistory->addHistoryConnection($project->getId(), $user->getId(), 'Delete Local Suf', $sf_code);
Function Supp Suf
/**
* #Route("/creation/suf/supp", name="suf_supp")
*/
public function suf(
Request $request,
ShapesRepository $shapesRepository
) {
$params = $this->requestStack->getSession();
$projet = $params->get('projet');
$modules = $params->get('modules');
$fonctionnalites = $params->get('fonctionnalites');
$user = $this->getUser()->getUserEntity();
$manager = $this->graceManager;
$mapManager = $this->mapManager;
$countElements = $mapManager->getCount();
$shapes = $shapesRepository->findBy(array('projet' => $projet->getId()));
$adresseWeb = $this->getParameter('adresse_web');
$carto = $params->get('paramCarto');
$centrage = $params->get('centrage');
$cableColor = $params->get('cableColor');
$sf_code = '';
if ($request->get('suf') != '') {
$sf_code = $request->get('suf');
}
$suf = $manager->getSuf($sf_code);
$success = '';
$error = '';
$warning = '';
if ($request->query->get('success')) {
$success = $request->query->get('success');
} elseif ($request->query->get('error')) {
$error = $request->query->get('error');
} elseif ($request->query->get('warning')) {
$warning = $request->query->get('warning');
}
if ($request->isMethod('POST')) {
if ($request->request->get('sf_code') != '') {
$sf_code = $request->request->get('sf_code');
}
if ($request->get('val') != '') {
$val = $request->get('val');
}
$dir = $this->getparameter('client_directory');
$dossier = str_replace(' ', '_', $projet->getProjet());
$dir = $dir . $dossier . '/documents/';
$cable = $val[0];
$chem = $val[1];
$t_suf = $this->graceCreator->supprimeSuf($sf_code, $cable, $chem);
if ($t_suf[0][0] == '00000') {
$this->logHistorique->addHistoryConnection($projet->getId(), $user->getId(), 'Suppression Suf Local', $sf_code);
// $creator->delDirObjet( $st_code, $dir );
$data = new JsonResponse(array("success" => "create!"));
return $data;
} else {
$data = new JsonResponse(array("error" => "Error : " . $t_suf));
return $data;
}
return $this->render('Modifications/supSuf.html.twig', array(
'user' => $user,
'paramCarto' => $carto,
'cableColor' => $cableColor,
'suf' => $suf,
'adresseWeb' => $adresseWeb,
'centrage' => $centrage,
'shapes' => $shapes,
'projet' => $projet,
'modules' => $modules,
'fonctionnalites' => $fonctionnalites,
'countElements' => $countElements
));
}
}
Your only return statement is inside of an if condition. If the code does not pass the condition, it has nothing to return. The code must return something in all possible cases. If you are not still used to these practices, an IDE might guide you until it becomes a routine. PHPStorm is my personal preference.
BTW, I recommend you to switch from the array() syntax to the more globally accepted [] although you must be in PHP 5.4 or higher.
I have to make filtering by date in reqest. I know about existing yii\data\DataFilter class, so I used it to solve the issue.
Actual request URL(example): https://api.site.com/module/post?filter[from_date][>=]=100
Don't worry about value 100, we use UNIX in our policy.
I use yii\rest\ActiveController to perform actions, so I defined dataFilter property in [[actions()]]:
public function actions()
{
$actions = parent::actions();
$actions['index']['dataFilter'] = [
'class' => DataFilter::class,
'attributeMap' => [
'from_date' => 'date_success',
'to_date' => 'date_success',
],
'searchModel' => function () {
return (new DynamicModel(['from_date', 'to_date']))
->addRule(['from_date', 'to_date'], 'integer', ['min' => 0]);
},
];
return $actions;
}
After the query is completed, an empty array is returned []. I traced SQL queries:
As you can see there is "EQUALS" operand instead ">", which defined in query-string ?filter[from_date][>]=100.
By default in yii\rest\IndexAction variable $query calls method where($filter):
/*
After successful filter build $filter variable becomes:
$filter = [
'date_success' => [
'>' => 100,
],
]
*/
$query = $modelClass::find();
if (!empty($filter)) {
$query->andWhere($filter);
}
Why it's happens? I debugged the code, and I find one interesting feature! In yii\db\conditions\HashConditionBuilder:
public function build(ExpressionInterface $expression, array &$params = [])
{
$hash = $expression->getHash();
$parts = [];
foreach ($hash as $column => $value) {
if (ArrayHelper::isTraversable($value) || $value instanceof Query) {
// IN condition
// Executing will be here.
// Yii2 thinks thats 'IN' condition, and builds as 'IN'.
$parts[] = $this->queryBuilder->buildCondition(new InCondition($column, 'IN', $value), $params);
} else {
if (strpos($column, '(') === false) {
$column = $this->queryBuilder->db->quoteColumnName($column);
}
if ($value === null) {
$parts[] = "$column IS NULL";
} elseif ($value instanceof ExpressionInterface) {
$parts[] = "$column=" . $this->queryBuilder->buildExpression($value, $params);
} else {
$phName = $this->queryBuilder->bindParam($value, $params);
$parts[] = "$column=$phName";
}
}
}
return count($parts) === 1 ? $parts[0] : '(' . implode(') AND (', $parts) . ')';
}
This problem repeats with different 'conditionOperators', the result absolutely same.
filter[from_date][=]=100
filter[from_date][<]=100
filter[from_date][gt]=100
filter[from_date][gte]=100
There were one sticky difference between ActiveDataFilter and DataFilter. It concluse in method [[buildInternal()]].
DataFilter method:
protected function buildInternal()
{
return $this->normalize(false);
}
ActiveDataFilter method:
protected function buildInternal()
{
$filter = $this->normalize(false);
if (empty($filter)) {
return [];
}
return $this->buildCondition($filter);
}
By calling $this->buildCondition($filter) ActiveDataFilter passes $filter variable and then applyes QueryBilders, so $filter variable becomes:
$filter = ['>', 'date_success', 100];
I want to include like clause in the case of last_name.This is my controller code used for search box.I want to compare form value last_name with db value family_name.
public function filtered_volunteer_details()
{
$user_data = $this->session->userdata("logged_user");
$tab_result = array();
if (is_array($user_data) && $user_data["user_role"] == "staff")
{
if ($this->input->method() == "post")
{
$condition = array();
$data = $this->input->post();
if(isset($data["membership_number"]) && $data["membership_number"]!= "")
{
$condition["membership_number"]=trim($data["membership_number"]);
}
if(isset($data["last_name"]) && $data["last_name"]!= "")
{
$condition["family_name "]=trim($data["last_name"]);
}
$this->load->model(array(
"Users"));
$result = $this->Users->get_volunteers("*",$condition);
$volunteer_tbl_list=array();
foreach($result as $volunteer_results)
{
$volunteer_tbl_list[] = $this->load->view("staff/manage_volunteer/volunteer_list_tbl_row", $volunteer_results, TRUE);
}
echo json_encode(array(
"status" => "success",
"volunteer_tbl_list" => $volunteer_tbl_list));
return;
}
}
echo json_encode(array(
"error" => "true",
"msg" => "Invalid Access."));
return;
}
This is my model code
public function get_volunteers($fields = "*",$condition=array())
{
$condition["staff"]="N";
$this->db->select($fields);
$query = $this->db->get_where(self::$tbl_name, $condition);
//var_dump($this->db->last_query());
return( $query->result() );
}
Try adding a $this->db->like() to the query in get_volunteers(). documentation
public function get_volunteers($fields = "*",$condition=array())
{
$condition["staff"]="N";
$this->db->select($fields);
$this->db->like($condition);
$this->db->from(self::$tbl_name);
return( $query->result() );
}
I have 100 tables or can be more than that,I always need to fetch the record all the time in my application from various table.So writing functions for each and every query its not good coding standard.
$this->db->select();
$this->db->from("table1");
$query = $this->db->get();
return $query->result_array();
$this->db->select();
$this->db->from("table2");
$query = $this->db->get();
return $query->result_array();
$this->db->select();
$this->db->from("table1");
$this->db->where("id",10);
$query = $this->db->get();
return $query->result_array();
I want the good coding standard for this.
Write this code in controller.
$data = $this->common_model->getRecords("table_name", "*", array("field1" => $this->input->post('user_name')));
This will be your function in model (that is common_model).
public function getRecords($table, $fields = '', $condition = '', $order_by = '', $limit = '', $debug = 0) {
$str_sql = '';
if (is_array($fields)) { #$fields passed as array
$str_sql.=implode(",", $fields);
} elseif ($fields != "") { #$fields passed as string
$str_sql .= $fields;
} else {
$str_sql .= '*'; #$fields passed blank
}
$this->db->select($str_sql, FALSE);
if (is_array($condition)) { #$condition passed as array
if (count($condition) > 0) {
foreach ($condition as $field_name => $field_value) {
if ($field_name != '' && $field_value != '') {
$this->db->where($field_name, $field_value);
}
}
}
} else if ($condition != "") { #$condition passed as string
$this->db->where($condition);
}
if ($limit != "")
$this->db->limit($limit);#limit is not blank
if (is_array($order_by)) {
$this->db->order_by($order_by[0], $order_by[1]); #$order_by is not blank
} else if ($order_by != "") {
$this->db->order_by($order_by); #$order_by is not blank
}
$this->db->from($table); #getting record from table name passed
$query = $this->db->get();
if ($debug) {
die($this->db->last_query());
}
$error = $this->db->_error_message();
$error_number = $this->db->_error_number();
if ($error) {
$controller = $this->router->fetch_class();
$method = $this->router->fetch_method();
$error_details = array(
'error_name' => $error,
'error_number' => $error_number,
'model_name' => 'common_model',
'model_method_name' => 'getRecords',
'controller_name' => $controller,
'controller_method_name' => $method
);
$this->common_model->errorSendEmail($error_details);
redirect(base_url() . 'page-not-found');
}
return $query->result_array();
}
I used this code for fetching the record. you just need to pass the table name ,fields name ,the condition and limit.
your codes can actually be in 1 line
$query= $this->db->get('table1')->result_array();
$query= $this->db->get_where('table1', array('id'=>3,'name'=>'tom'))->result_array();
or if you really want a function
function getData($table){
$query=$this->db->get($table)->result_array();
return $query;
}
$data= getData('table1');
how to get function return value without execute it again?
i used this but this execute function again
my function:
function article()
{
if($_GET['action'] == "article" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$article = array();
$selectArticle = mysql_query("SELECT * FROM articles WHERE id='$id'");
$rowArticle = mysql_fetch_array($selectArticle);
$id = $rowArticle['id'];
$title = stripcslashes($rowArticle['title']);
$category = stripcslashes($rowArticle['category']);
$image = stripcslashes($rowArticle['image']);
$description = stripcslashes($rowArticle['description']);
$full_description = stripcslashes($rowArticle['full_description']);
$keywords = stripcslashes($rowArticle['keywords']);
$url = "/article/" . $rowArticle['id'] . "/" . str_replace(" ","-",stripcslashes($rowArticle['title']));
$article = array('id' => $id, 'title' => $title, 'category' => $category, 'image' => $image, 'description' => $description, 'full_description' => $full_description, 'keywords' => $keywords, 'url' => $url);
mysql_query("UPDATE articles SET visits=visits+1 WHERE id='$id'");
}
return $article;
}
how to check it
if (article() != null)
{
$article = article();
return $article['title'];
}
This should do what you want
if (null !== ($article = article())) {
return $article['title'];
}
This does a 'simultaneous' assignment AND comparison.
First, this part is evaluated: ($article = article()). It yields a null value or an array which is stored in $article.
Its result (null or array) is then evaluated by the if structure: if (null !== $article) and normal flow resumes.
like so
$article_var = article();
if ($article_var!=null)
{
//do stuff
//return $article['title'] // etc
}
Modify the check a little bit.
$article = article();
return $article != null ? $article['title'] : null;