I.m trying to check if a value exists in two columns from a table. The column names are on_number and off_number.
I've tried the following in my controller. The check works however for only the off_number columns and not the on_number.
my controller.
public function check()
{
$on_number = !empty(get('on_number')) ? get('on_number') : false;
$notId = !empty($this->input->get('notId')) ? $this->input->get('notId') : 0;
if($on_number)
$exists = count($this->duty_book_model->getByWhere([
'on_number' => $on__number,
'id !=' => $notId,
])) > 0 ? true : false;
if($on_number)
$exists = count($this->duty_book_model->getByWhere([
'off_number' => $on_number,
'id !=' => $notId,
])) > 0 ? true : false;
echo $exists ? 'false' : 'true';
}
My Model
class Duty_book_model extends MY_Model {
public $table = 'tbl_duty_type';
public function __construct()
{
parent::__construct();
}
}
The extends MY_Model has:
public function getByWhere($whereArg, $args = [])
{
if(isset($args['order']))
$this->db->order_by($args['order'][0], $args['order'][1]);
return $this->db->get_where($this->table, $whereArg)->result();
}
I would like it to check both columns if the value exists.
I believe the reason it doesn't work for "off_number" is in this code
if($on_number)
$exists = count($this->duty_book_model->getByWhere([
//THE NEXT LINE IS THE PROBLEM - LOOK AT THE VALUE!!!
'off_number' => $on_number, //value should be $off_number - right?
'id !=' => $notId,])) > 0 ? true : false;
That said, I think your code is a hot mess.
I say that because to adhere to the MVC pattern a lot of your controller logic should be in the model. IMO, all of it should be.
I would replace the model function getByWhere() with one named check(). It will return true if any record where 'id != $notIdAND'on_number' = $on__number` AND off_number', $off_number. If either of the requred inputs are missing, or if no records are found it returns false.
As you look at the following code it's important to understand that $this->input->get('some_input') will return null if $_GET('some_input') is empty.
class Duty_book_model extends MY_Model
{
public $table = 'tbl_duty_type';
public function check()
{
$on_number = $this->input->get('on_number');
$notId = $this->input->get('notId');
if(empty($on_number) || empty($notId))
{
return false;
}
$query = $this->db
->select('id') //could be any field
->where('id !=', $notId)
->where('on_number', $on__number)
->where('off_number', $off_number)
->get($this->table);
//given $notId = 111 AND $on_number = 222 AND $off_number = 333
//produces the query string
//SELECT `id` FROM `tbl_duty_type` WHERE `id` != 111 AND `on_number` = 222 AND `off_number` = 333
if($query) //might be false if the query string fails to work
{
return $query->num_rows > 0; //returns boolean
}
return false;
}
}
Then all you need in the controller is
$exists = $this->duty_book_model->check();
echo $exists ? 'false' : 'true';
First of all, you have a typo in
'on_number' => $on__number,
You have doubled underscore in $on__number
The second thing - the reason why your check works only for off_number is because you use $exist variable in both cases. Doesn't matter what check result will be for on_number, because it always will be rewritten by off_number checks.
One way you can solve those is by using two different variables:
if($on_number){
$exists_on = count($this->duty_book_model->getByWhere([
'on_number' => $on_number,
'id !=' => $notId,
])) > 0 ? true : false;
$exists_off = count($this->duty_book_model->getByWhere([
'off_number' => $on_number,
'id !=' => $notId,
])) > 0 ? true : false;
}
echo (($exists_on===true)&&(exists_off===true)) ? 'false' : 'true';
It's not the best solution, but it must be most clear.
Related
I'm trying to make a Controller that will define the Default Value from query builder dynamically and directly from controller.
for example :
in table users have column 'note' that the default value is 'this is old default note'
So step 2 in blade edit general setting there's an input value for define new default value for column 'note' in table 'users', so if i input in that form with 'this is new default note'. and every users registered will have value "this is new default value".
the problem is i'm confuse the flow to implement for that function.
So this is my current code :
Code for GeneralSettingController.php :
\DB::beginTransaction();
$updated = [
'max_sequence' => $max_sequence,
'latest_version' => $latest_version,
'minimum_version' => $minimum_version,
];
$updateVersion = GeneralSetting::updateDataGeneralSettingCMS($updated);
\DB::commit();
if($updateVersion)
{
$status = "Update Succeed!";
return redirect()->route('setting.general_setting.detail')->with('error', $status);
}
else
{
$status = "No Changes!";
return redirect()->route('setting.general_setting.detail')->with('error', $status);
}
and this it the model class for: updateDataGeneralSettingCMS()
public static function updateDataGeneralSettingCMS($updated)
{
//Get the fields to be updated
$fields = [];
foreach ($updated as $column => $var) {
$value = $var;
if($value !== null)
{
$fields['general_setting.' . $column] = $value;
}
}
//Execute Update
$count = \DB::table('general_setting')
->update($fields);
return ($column > 0) ? true : false;
I'm writing a piece of code and in it I would like to know if the result of a find if empty or not. Here is my piece of code:
public function signatureAction()
{
$info = $this->session->get('current_quote');
$object_list = ApplicationSignatureFile::find(array('conditions' => 'application_id = ?1 AND quote_id = ?2',
'bind' => [
1 => $info['application_id'],
2 => $info['quote_id'],
]));
$this->view->setVar('object_list', $object_list);
if ($object_list) {
$this->view->setVar('has_files',true);
} else {
$this->view->setVar('has_files',false);
}
}
What I don't know yet if how to check if $object_list is EOF so I can set the has_files variable better. Currently it is not working. How can I do that in a controller and in a .volt view?
This is pretty strange actually. Using findFirst or any other ORM method returns false on fail, however using find does not.
A simple workaround in your case would be to use the count method on the result set:
$test = \Models\Objects::find([
'conditions' => 'is_active = 42'
]);
if ($test->count()) {
print('I have records with is_active = 42');
d($test->toArray());
} else {
print('I do not have any records with is_active = 42');
}
I'm a little bit baffled by this, so I'm hoping someone can shed some light on it for me.
I have a function which is meant to return a column Status from one of my tables, visit.
function someFunction($visitId = null) {
$visit = VisitQuery::create()
->select(array('Status'))
->findPk($visitId);
}
If I var_dump($visit), when calling the function for the first time, it outputs:
string '1' (length=1)
Subsequent, identical calls to the function however seem to return an entire object:
object(Visit)[30]
protected 'startCopy' => boolean false
protected 'id' => int 362
protected 'job_id' => int 351
protected 'company_id' => int 2
protected 'type_id' => int 1
protected 'visit_date' => string '2013-08-23 00:00:00' (length=19)
protected 'status' => string '1' (length=1)
...
I'm calling the function for the first time with an (int) $visitId passed via a posted form:
var_dump($visitId); // int 362
Subsequent calls are made with an (int) $visitId which is returned from another function, saveVisit() (which uses Propel to save the record - I believe this may have something to do with it).
$visitId = saveVisit($visitId);
var_dump($visitId); // int 362
I tried to do some debugging, and for some reason the query issued to MySQL is different between the first function call and subsequent ones:
var_dump($con->getLastExecutedQuery());
SELECT visit.STATUS AS "Status" FROM `visit` WHERE visit.ID=362 // 1st call
SELECT `ID`, `JOB_ID`, `COMPANY_ID`, `TYPE_ID`, `VISIT_DATE`, `STATUS`, `REMIND`, `PRINTED` FROM `visit` WHERE `ID` = 362 // 2nd call
SELECT `ID`, `JOB_ID`, `COMPANY_ID`, `TYPE_ID`, `VISIT_DATE`, `STATUS`, `REMIND`, `PRINTED` FROM `visit` WHERE `ID` = 362 // 3rd call
Can anyone tell me why or how this is happening?
I'm using Propel 1.6.
Propel's create() method:
public static function create($modelAlias = null, $criteria = null)
{
if ($criteria instanceof VisitQuery) {
return $criteria;
}
$query = new VisitQuery();
if (null !== $modelAlias) {
$query->setModelAlias($modelAlias);
}
if ($criteria instanceof Criteria) {
$query->mergeWith($criteria);
}
return $query;
}
Propel's findPk() method:
public function findPk($key, $con = null)
{
if ($con === null) {
$con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ);
}
// As the query uses a PK condition, no limit(1) is necessary.
$this->basePreSelect($con);
$criteria = $this->isKeepQuery() ? clone $this : $this;
$pkCols = $this->getTableMap()->getPrimaryKeyColumns();
if (count($pkCols) == 1) {
// simple primary key
$pkCol = $pkCols[0];
$criteria->add($pkCol->getFullyQualifiedName(), $key);
} else {
// composite primary key
foreach ($pkCols as $pkCol) {
$keyPart = array_shift($key);
$criteria->add($pkCol->getFullyQualifiedName(), $keyPart);
}
}
$stmt = $criteria->doSelect($con);
return $criteria->getFormatter()->init($criteria)->formatOne($stmt);
}
My function to retrieve the visit status:
function getVisitStatus($visitId = null) {
if (empty($visitId)) {
return false;
}
try {
$visit = VisitQuery::create()
->select(array('Status'))
->findPk($visitId);
} catch (Exception $e) {
echo $e->getMessage(); exit;
}
if (is_null($visit)) {
return false;
}
return $visit;
}
The function which saves a visit record:
function saveVisit($data = null) {
if (empty($data)) {
return false;
}
try {
$visit = (!empty($data['visit_id'])) ? VisitQuery::create()->findPk($data['visit_id']) : new Visit();
if (!is_object($visit)) {
return false;
}
$visitDataMap = array(
'JobId' => 'job_id',
'TypeId' => 'type_id',
'VisitDate' => 'visit_date',
'Status' => 'status',
'CompanyId' => 'engineer_id',
'Remind' => 'remind'
);
$visitData = array();
foreach ($visitDataMap as $column => $value) {
if (!empty($data[$value])) {
$visitData[$column] = $data[$value];
}
}
$visit->fromArray($visitData);
$visit->save();
return $visit->getId();
} catch (PropelException $e) {
echo $e->getMessage(); exit;
}
}
It seems that on the first call will grab your data but then put a copy of the full object in to the instance pool. I am not sure if this is a bug or valid behaviour (your code would suggest the former, but I'd love to hear from someone who knows more about Propel such as a dev) but you can stop it happening with:
VisitPeer::clearInstancePool();
Bear in mind you're losing a bit of caching from other queries you might have done here with the visit relation.
You will be able to confirm this by adding an echo in the BaseVisitPeer.php file. You will see something like this:
public static function getInstanceFromPool($key)
{
if (Propel::isInstancePoolingEnabled()) {
if (isset(VisitPeer::$instances[$key])) {
return VisitPeer::$instances[$key];
}
}
return null; // just to be explicit
}
If you add an echo somewhere inside the if (isset(VisitPeer::$instances[$key])) { statement, you should see it appear only after the second and subsequent calls. If you were to comment this whole if statement out then you would get the same result back each time - the one you correctly get back from your original call.
Hope that helps!
I'm running CodeIgniter 2.0 and I have a test controller setup with this code in the index function. It seems like no matter what I put in the "set_test_items" variable, the report never changes. It always show all of the possible information regarding the test. I feel like I must be missing something blatantly obvious here. What am I missing?
$this->unit->set_test_items(array('test_name', 'result'));
$this->_test_user_lib();
$this->_test_user_model();
echo $this->unit->report();
Also, I just tried to var_dump() on the visible items when the report is generated and the array only contains the two things I passed in, so it is being set correctly.
The set_test_items() affects only the run() methods, not report(). The following code will show only the items you specified in set_test_items():
echo $this->unit->run(1 + 1, 2, 'One plus one');
But the following will show all items:
echo $this->unit->report();
Hope this helps.
You can extend the Unit_class library to fix the run method.
Here is an example using the array helper "elements" to keep only the elements in >_test_items_visible.
Note: This way, you have to set the visible items BEFORE run the tests.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Unit_test extends CI_Unit_test
{
/**
* Llamamos al constructor del padre
*
*/
public function __construct()
{
parent::__construct();
}
/**
* Reemplazamos la función RUN
*/
function run($test, $expected = TRUE, $test_name = 'undefined', $notes = '')
{
// Sacamos la versión
$CI =& get_instance();
$CI->load->helper('array');
if ($this->active == FALSE)
{
return FALSE;
}
if (in_array($expected, array('is_object', 'is_string', 'is_bool', 'is_true', 'is_false', 'is_int', 'is_numeric', 'is_float', 'is_double', 'is_array', 'is_null'), TRUE))
{
$expected = str_replace('is_float', 'is_double', $expected);
$result = ($expected($test)) ? TRUE : FALSE;
$extype = str_replace(array('true', 'false'), 'bool', str_replace('is_', '', $expected));
}
else
{
if ($this->strict == TRUE)
$result = ($test === $expected) ? TRUE : FALSE;
else
$result = ($test == $expected) ? TRUE : FALSE;
$extype = gettype($expected);
}
$back = $this->_backtrace();
// Only visible elements
$report[] = elements
(
$this->_test_items_visible, array
(
'test_name' => $test_name,
'test_datatype' => gettype($test),
'res_datatype' => $extype,
'result' => ($result === TRUE) ? 'passed' : 'failed',
'file' => $back['file'],
'line' => $back['line'],
'notes' => $notes
)
) ;
$this->results[] = $report;
return($this->report($this->result($report)));
}
}
Instead of running the report() method
echo $this->unit->report();
you can run the result() method:
echo $this->unit->result();
This will give you just the items you have selected but in a raw data format (ie. an associative array) this is probably better because the format of the report isn't that great. You can then load them into a view and format them how you want:
$data['test_results'] = $this->unit->result();
$data['title'] = 'Pricing Test';
$this->load->view('header');
$this->load->view('tests/index', $data);
I have this PHP class, whose purpose is to fetch some configuration data from a database and store it for later use:
class GSConfig {
private $configurationData;
private $repository;
public function __construct($pRepository) {
$this->repository = $pRepository;
$this->configurationData = $this->InitializeConfiguration();
}
public function InitializeConfiguration() {
$result = $this->repository->configLoadAll();
if ( $result['data'] ) {
$conf_array = $result['data'];
foreach ( $conf_array as $row) {
$code = strtolower($row ['code']);
$value = strtolower($row ['value']);
//if ($value == "true") $value = (bool)true;
//if ($value == "false") $value = (bool)false;
$this->configurationData[$code] = $value;
}
} else {
$this->configurationData = null;
}
print_r($this->configurationData);
}
public function getConfigValue($key) {
$key = strtolower($key);
if ($this->configurationData != null) {
if( isset($this->configurationData[$key])) {
return $this->configurationData[$key];
}
} else if ($this->configurationData == null) {
// If we reach this code, something went wrong
// (TODO: throw Exception)
echo "<p>Tick</p>";
}
}
}
InitializeConfiguration gets the data and stores it as an array in the $configurationData property. This is working as expected as shown by the output of the print_r function.
However, after initializing, if i attempt to read any value from the $configurationData, i get Tick. Somehow the variable becomes null after the Initialization.
The output would be something like:
print_r output:
Array ( [show_cart] => true [order_mail] => order#shop.de [debug_mode] => true [branch_mode] => true [default_branch] => 1 [agb_file] => agb.txt [kat_order] => k_nr [show_rows] => 5 [product_order] => p_produktnr [cost_per_wu] => 0.66 [message_lang] => eng [free_shipping] => true [free_ship_amt] => 25 [special_price] => true [discounts] => true [cat_show_mode] => all [price_att] => ersatzpreis [mwst_att] => mehrwertsteuer [aktionsp_att] => aktionspreis [katalog_mode] => per_branch )
further output:
Tick
Tick
...
Tick
Anyone knows why this is happenning? Btw, my PHP version is 5.3.1
you're assigning the return value of InitializeConfiguration() but there's no return statement in this function (defaults to "return null").
I suspect it's because in your constructor, you assign $this->configurationData to the return value of InitializeConfiguration(). But it doesn't look like InitializeConfiguration() returns anything. I think the easiest way to fix this is to change:
$this->configurationData = $this->InitializeConfiguration();
to:
$this->InitializeConfiguration();
The problem is that you're assigning the return value of InitializeConfiguration to $this->configurationData inside your constructor, which will be null.
The following remains sound advice:
Strongly suspect your error is arising from your using the incorrect comparison operator.
Never, ever do this in PHP:
if ($this->configurationData == null)
When testing against null, false or 0, always use === which checks that both the values and types of each variable are the same. Simply using == will cast one side to the type of the other before the conversion.
The following are all true when using the == operator:
null == 0;
array() == null;
null == false;
false == 0;
You also shouldn't be using else if ($this->configurationData == null) in getConfigValue; use a simple else since your intent seems to be to cover all other cases.