I have inherited an application that is not doing what it's supposed to do. I have isolated the problem to the database not being properly attached. The programmer wrote this function that seemingly is suppose to evaluate whether the database is attached, calling the "attachPaymentDatabase()" function to attach it if it's not.
function attachPaymentDatabaseIfNotDoneAlready()
{
global $db;
global $hasPaymentDatabaseAttached;
// Determine if we have attached the payment tables, and if not, add them.
$hasPaymentDatabaseAttached = false;
try {
// this new way should work the best-- looking for PAY.
$alldb = queryall($db, "PRAGMA database_list;");
for ($i = 0; $i < count($alldb); $i++)
{
$alldb[$i] = array_change_key_case($alldb[$i], CASE_LOWER);
if (strtolower($alldb[$i]['name']) == 'pay')
{
debugEmail("condition 1 worked.");
$hasPaymentDatabaseAttached = true;
break;
}
}
// if its name changed this will also work
if (!$hasPaymentDatabaseAttached)
{
$r = #$db->querySingle("SELECT * FROM PAY_PARAMETER;");
$hasPaymentDatabaseAttached = true;
debugEmail("condition 2 worked.");
}
}
catch(Exception $e)
{
}
if (!$hasPaymentDatabaseAttached)
{
debugEmail("nothing worked.");
attachPaymentDatabase();
}
}
I have written a debugEmail() function that emails me a defined message with a timestamp as used above. When executing the code from the application, I can see that "condition 2 worked." is being called one second before "nothing worked.".
I don't understand how this can be. If debugEmail("condition 2 worked."); is executing, then so should too $hasPaymentDatabaseAttached = true; in which case this should not execute:
if (!$hasPaymentDatabaseAttached)
{
debugEmail("nothing worked.");
attachPaymentDatabase();
}
But it clearly is.
What is going on here?!?!?!?
No it shouldn't, because $hasPaymentDatabaseAttached is set to true in the first condition. In still nonsense at all, but it works as described.
Related
i dont understand how the if statement works and the function is called, why i am getting "He has more strength", i know because the strength is greater, but what i am getting there, is it a boolean? can i dump it, it shows me NULL if i put this inside the if statement
edit:i have added the return.
<?php
class Ship
{
public $name;
public $strength = 0;
public function doesGivenShipHaveMoreStrength($givenShip)
{
return $givenShip->strength > $this->strength;
}
}
$myShip = new Ship();
$myShip->name = 'TIE Fighter';
$myShip->strength = 150;
$otherShip = new Ship();
$otherShip->name = 'Imperial Shuttle';
$otherShip->strength = 50;
if ($myShip->doesGivenShipHaveMoreStrength($otherShip)) {
echo $otherShip->name.' He has more strength';
} else {
echo $myShip->name.' She has more strength';
}
?>
If statements evaluates whatever inside it's braces () . if true or 1 the block or statement will be executed. your function returned a value , and that returned value is later evaluated by the if statement. these are examples that might help you understand how if statements work. the same goes with almost every other programming language.
//example 1
if(true){
// will be executed
}else{
// will not executed
}
//example 2
if(false){
// will not executed
}else{
// will be executed
}
//example 3
if( 2 > 1){
// will be executed
}else{
// will not executed
}
//example 4
if(1){
// will be executed
}else{
// will not executed
}
//example 5
if(0){
// will not executed
}else{
// will be executed
}
//example 5
if(myFunction()){
// will be executed
}else{
// will not executed
}
function myFunction()
{
return true;
}
Your class is not written properly, it should be :
class Ship
{
public $name;
public $strength = 0;
public function doesGivenShipHaveMoreStrength($givenShip)
{
return ($givenShip->strength > $this->strength);
}
}
Then it will work as expected :) In your version, the function does return nothing, as a result when you use it, it evaluates to NULL, which is equivalent to false, and your test block fails !
I would add one more point to the recently answers.
You must add return.
Even you add the return, you shall hit your block containing "He has more strength".
Reason: you are comparing with this->strength which is 0 and your both objects have strength set to 150 & 50 accordingly. It's going to be always true.
I would suggest to compare object level values if you are really want to achieve the same functionality.
Revised Answer: You may need to adjust/fix your condition.
as per your code snippet at here
Your value of given ship shall be printed as 50 and current object value is 150 . your function is checking if 50 > 150? answer would be false and you shall hit your else.
Hope this helps
there is two ways or more i can make that function
one why is using more returns and return every time i do not need continue with the function and another way is using
more ifs,else ifs, elses,
function getCountOfWhatEverMethodType1
{
$return = false;
// ----
if($user->isLogged)
{
if(getDBOBlaBla->equal(1))
{
$return = 2;
}
else if(getDBOBlaBla->equal(2))
{
$return = 3;
}
else
{
$return = 1;
}
}
// ----
return $return;
}
function getCountOfWhatEverMethodType2
{
if(!$user->isLogged)
{
return false;
}
$return = 1;
// ----
if(getDBOBlaBla->equal(1))
{
$return = 2;
}
else if(getDBOBlaBla->equal(2))
{
$return = 3;
}
// ----
return $return;
}
with one i should use and why?
If you want to return something, usually the better option is to return something when the condition is met.
I would do it this way:
function getCountOfWhatEverMethodType3()
{
if(!$user->isLogged)
{
return false;
}
// ----
if(getDBOBlaBla->equal(1))
{
return 2;
}
if(getDBOBlaBla->equal(2))
{
return 3;
}
return 1;
}
For me this style is better for 2 reasons:
You can remove some if/else statments so you can code faster and there's less code in case you need to modify or analyze that
You don't create temporary variables because you don't need them.
In fact each person has it's own coding preferences in such statements and if all work you can use any of them. But even look at your previous code - you made some mistakes (used null that was unnecessary) and using the above version it would be harder to do such mistake
I would like to do these actions step by step:
first DB update
copy file
unlink file
second DB update
It is working, but I don't know if my code is correct/valid:
$update1 = $DB->query("UPDATE...");
if ($update1)
{
if (copy("..."))
{
if (unlink("..."))
{
$update2 = $DB->query("UPDATE ...");
}
}
}
Is it possible to use if statement this way?
I found that it is usually used with PHP operators and PHP MySQL select, for example:
$select = $DB->row("SELECT number...");
if ($select->number == 2) {
...
}
Sure, your ifs work fine. What would look and flow better would be using a function like this:
function processThings() {
// make sure anything you use in here is either passed in or global
if(!$update1)
return false;
if(!$copy)
return false;
if(!$unlink)
return false;
if(!$update2)
return false;
// you made it!
return true;
}
make sure you call $DB as a global variable, plus pass in whatever strings you need etc etc
I have tested each method individually with default values and it all seems to work. There is something going on when they are all mixed together.
Here is the code and i'll do my best to write it in an easy to follow way:
Starting with the controller:
if ($active['newcliq'])
{
$newcliqid = $this->create_m->create_keyword($cliq, $cliqid);
if (!$newcliqid) {
echo json_encode(array('success' => false));
} else {
$this->logic_m->change_active($newcliqid, $cliq);
}
}
$active['newcliq'] is true or false and pulled from userdata('active')
Of course, the next thing it runs is create_keyword($cliq, $cliqid) seen below:
$this->db->insert('cliq', $insert);
$newcliqid = $this->db->insert_id();
if ($newcliqid) {
return $newcliqid;
} else {
return false;
}
Again, I have checked it all manually, and I know that $newcliqid is returning the correct insert_id and the overall function is returning the correct value.
So $newcliqid is returned to the controller and goes runs logic_m->change_active seen below:
if (!$this->logic_m->cliqidcheck($cliqid)){
$cliqid = 6;
}
The above line is what is giving me problems. No matter what value, $cliqid is ALWAYS set to 6. Whether cliqidcheck returns true or false.
Here is cliqidcheck($cliqid)
public function cliqidcheck($cliqid)
{
if ((ctype_digit($cliqid)) AND ($this->checkcliqidexist($cliqid)))
{
return true;
} else {
return false;
}
}
I have tested cliqidcheck with manually entered values and it always returns the correct value. In addition, i've flat out removed the cliqidcheck from the change_active model and it works perfectly.
I also echo'ed the variable $newcliqid in the controller and found the correct value.
I am hoping this is just a simple problem that I'm overlooking. Thanks for the help! Please let me know if more info is required.
Instead of verbal explanations, wouldn't be it better to post either the debugging code
var_dump($cliqid);
$tmp = $this->logic_m->cliqidcheck($cliqid);
if (!$tmp) {
$cliqid = 6;
}
var_dump($tmp, $cliqid);
die;
and it's output.
Even without posting it here it will convince you that if statement actually never "running regardless of true false"
Setting full error reporting also helps (with finding typos and such)
ini_set('display_errors',1);
error_reporting(E_ALL);
Also a note on excessive code. This statement
if (condition)
{
return true;
} else {
return false;
}
can (and should, in my opinion) be shortened to
return (condition);
Same goes for insert id. Why not to make it just
return $this->db->insert_id();
without all that windy
if ($newcliqid) {
return $newcliqid;
} else {
return false;
}
which is actually a mere tautology
Inherited an old CakePHP site and I'm trying to figure out what some functions do. I have several functions that have the same name as another function but with an underscore first, e.g. save() and _save(). However the function _save() is never called in any context, though save() is.
I read this question and it looks like it's from an old worst-practices exercise, but that doesn't really explain why it's in my code; you still have to call function _save() as _save() right? If there's no calls to _save() is it safe to remove?
I want it gone, even the save() function wasn't supposed to be there, rewriting perfectly good framework functionality. It looks like an older version of the same function, but there's no comments and I don't know if there's some weird context in which php/Cake will fall back to the underscored function name.
Here's the code for the curious. On closer inspection it appears the underscored functions were old versions of a function left in for some reason. At least one was a "private" method being called (from a public function of the same name, minus the underscore...):
function __save() {
$user = $this->redirectWithoutPermission('product.manage','/',true);
if ($this->data) {
$this->Prod->data = $this->data;
$saved_okay = false;
if ($this->Prod->validates()) {
if ($this->Prod->save()) $saved_okay = true;
}
if ($saved_okay) {
$product_id = ($this->data['Prod']['id']) ? $this->data['Prod']['id'] : $this->Prod->getLastInsertId();
if ($this->data['Plant']['id']) {
$this->data['Prod']['id'] = $product_id;
$this->Prod->data = $this->data;
$this->Prod->save_plants();
$this->redirect('/plant/products/'.$this->data['Plant']['id']);
} else {
$this->redirect('/product/view/'.$product_id);
}
die();
} else {
die('did not save properly');
}
} else {
die('whoops');
}
}
function save() {
$user = $this->redirectWithoutPermission('product.manage','/products',true);
if ($this->data) {
$this->Prod->data = $this->data;
if ($this->Prod->validates()) {
$this->Prod->save();
$gotoURL = isset($this->data['Navigation']['goto'])?$this->data['Navigation']['goto']:'/';
$gotoURL = str_replace('%%Prod.id%%', $this->data['Prod']['id'], $gotoURL);
if (isset($this->data['Navigation']['flash'])) {
$this->Session->setFlash($this->data['Navigation']['flash']);
}
if (isset($this->params['url']['ext']) && $this->params['url']['ext']=='ajax') {
$value = array(
'success'=>true
,'redirect'=>$gotoURL
);
print $this->Json->encode($value);
} else {
$this->redirect($gotoURL);
}
} else {
$value = array(
'success'=>false
,'message'=>"You have invalid fields."
,'reason'=>'invalid_fields'
,'fields'=>array(
'Prod'=>$this->Prod->invalidFields()
)
);
print $this->Json->encode($value);
}
} else {
$this->redirect('/products');
}
die();
}
I had hoped to learn whether or not some convention applied to this situation, but from testing I've found the functions are not called which is really the answer to the question I asked.