I'm trying to convert some old code by converting to mysqli. Unfortunately I can't figure out what part of the code is trying to do, so I don't know how to change it. It seems to be a standard safety check that everyone who uses the original mysql extension used, but I can't find anyone who explains why. Here is the original code:
function query($query = "", $transaction = FALSE)
{
//
// Remove any pre-existing queries
//
unset($this->query_result);
if( $query != "" )
{
$this->num_queries++;
if( $transaction == BEGIN_TRANSACTION && !$this->in_transaction )
{
$result = mysql_query("BEGIN", $this->db_connect_id);
if(!$result)
{
return false;
}
$this->in_transaction = TRUE;
}
$this->query_result = mysql_query($query, $this->db_connect_id);
}
else
{
if( $transaction == END_TRANSACTION && $this->in_transaction )
{
$result = mysql_query("COMMIT", $this->db_connect_id);
}
}
if( $this->query_result )
{
unset($this->row[$this->query_result]);
unset($this->rowset[$this->query_result]);
if( $transaction == END_TRANSACTION && $this->in_transaction )
{
$this->in_transaction = FALSE;
if ( !mysql_query("COMMIT", $this->db_connect_id) )
{
mysql_query("ROLLBACK", $this->db_connect_id);
return false;
}
}
return $this->query_result;
}
else
{
if( $this->in_transaction )
{
mysql_query("ROLLBACK", $this->db_connect_id);
$this->in_transaction = FALSE;
}
return false;
}
}
I can't figure out what they're doing with
if( $transaction == BEGIN_TRANSACTION && !$this->in_transaction )
Can anybody explain this to me?
The tokens BEGIN_TRANSACTION and END_TRANSACTION are arbitrary constants defined eslewhere to make the code more readable. Basically, this entire function is an implementation of MySQL Transactions in mysql, which doesn't directly support them. Much of the code is there just to work out whether or not a transaction has been started, and whether to commit it, or roll it back.
You can supprt the same functionality by using mysqli::begin_transaction(), mysqli::commit(), and mysqli::rollback()
The PHP reference ishere
Related
I have this code:
function saveField($field, $id, $module, $value)
{
$bean = BeanFactory::getBean($module, $id);
if (is_object($bean) && $bean->id != "") {
if ($bean->field_defs[$field]['type'] == "multienum") {
$bean->$field = encodeMultienumValue($value);
}else if ($bean->field_defs[$field]['type'] == "relate" || $bean->field_defs[$field]['type'] == 'parent'){
$save_field = $bean->field_defs[$field]['id_name'];
$bean->$save_field = $value;
if ($bean->field_defs[$field]['type'] == 'parent') {
$bean->parent_type = $_REQUEST['parent_type'];
$bean->fill_in_additional_parent_fields(); // get up to date parent info as need it to display name
}
}else{
$bean->$field = $value;
}
//return here will work
$bean->save(); //this works
//nothing works here
return getDisplayValue($bean, $field);
} else {
return false;
}
}
The problem here is that anything under
$bean->save()
will not work. But I know that save is working as the values are being updated. So how can I debug this problem?
I already tried:
return var_dump($bean->save());
return print_r($bean->save());
if($bean->save()){
return "1";
}else{
return "2";
}
And none of those in the above worked I still get nothing in my return.
There is likely something such as an after_save logic hook that is executing and either causing a fatal error or doing an exit.
Try using xdebug, it should allow you to investigate further into the save method that fails.
I have written a ternary function in PHP and it seems to work, although I am not sure if it is correct, can someone take a look and tell me if it is right?
I have added the ternary and the if of what should be happening.
//Foreach Loop
foreach ($post as $item) {
//If of what should occur
if ($passed == true) {
if (is_numeric($item)) {
if ($item > 0) {
$passed = true;
}
else {
$passed = false;
}
}
else {
if ($item != "") {
$passed = true;
}
else {
$passed = false;
}
}
//Ternary operator.
$passed = (is_numeric($item) ? ($item > 0 ? true : false) : ($item != "" ? true : false));
}
else {
return $passed;
}
}
please have a look on corrected code
$passed = (is_numeric($item))?($item>0?true:false):($item !="" ? true:false);
Honestly I do not really understand why you do not use a
if (!empty($item)) {
$passed = true;
} else {
return false;
}
In any case, ternaries are less readable than if /elseif / else, they are also slower (note that it is not an universal truth but a more general use case thing http://fabien.potencier.org/the-php-ternary-operator-fast-or-not.html).
I would recommend, if you really need all these if and elses to keep them rather than using ternaries (for readability's purpose).
I have a method that can return 3 different cases
public function check_verification_status($user_id) {
global $db;
$sql = "SELECT * FROM `users`
WHERE `id` = ".clean($user_id)."
AND `type_id` = 1";
$result = #mysql_query($sql,$db); check_sql(mysql_error(), $sql, 0);
$list = mysql_fetch_array($result);
if ($list['verification_key'] == '' && !$list['verified']) {
//No key or verified
return 0;
} elseif ($list['verification_key'] != '' && !$list['verified']) {
//key exists but not verified = email sent
return 2;
} elseif ($list['verification_key'] != '' && $list['verified']) {
//verified
return 1;
}
}
A form / message is output depending on the return value from this
I would have used bool for return values when comparing 2 cases, what is the proper way of handling more than 2 cases and what would the ideal return value be.
The way i call this:
$v_status = $ver->check_verification_status($user_id);
if ($v_status === 0) {
//do something
} elseif ($v_status === 1) {
//do something else
} elseif ($v_status === 2) {
//do something totally different
}
I want to learn the right way of handling such cases as I run into them often.
note: I know I need to upgrage to mysqli or PDO, its coming soon
What you have is fine, but you can also use a switch statement:
$v_status = $ver->check_verification_status($user_id);
switch ($v_status) {
case 0: {
//do something
break;
}
case 1: {
//do something else
break;
}
case 2: {
//do something totally different
break;
}
}
What's the best way to write this in PHP, so I know which condition fails and is easy to maintain? Without resorting to multiple if else statements...
if ((!$titleBlockPresent || !$leadBlock || ($allDoubleBlockCount !=2 || $allDoubleBlockCount!=1) ||$countFirstSmallShowBlocks !=2 ||$countSecondSmallShowBlocks !=2 ) && !$contentNotAvailableMessage)
{
$this->fail("Block missing in the horizontal list of blocks on the non live carousel");
}
try this
$shouldFail = FALSE;
switch(TRUE){
case !titleBlockPresent:
echo "No title block present<br/>";
$shouldFail = TRUE;
case !$leadBlock:
echo "No lead block<br/>";
// the rest of the code
}
If you move that check into the function, it'll be clear for you and anyone else looking at your code, and very easy to maintain, for example:
function tester($var1, $var2, $var3)
{
if (!$var1)
{
$this->fail("error1");
return FALSE;
}
if (!$var2)
{
$this->fail("error2");
return FALSE;
}
if (!$var3)
{
$this->fail("error3");
return FALSE;
}
return TRUE;
}
You could also add a comment to each if that needs further clarification.
I just come up with this, but noticed that it is very similar to GeoPhoenix's answer, just the other way around, may be worth checking this out, as well:
$bFail = false;
if(!$bFail && $contentNotAvailableMessage) $bFail = true;
if(!$bFail && !$titleBlockPresent ) $bFail = true;
if(!$bFail && !$leadBlock ) $bFail = true;
if(!$bFail && $allDoubleBlockCount != 2) $bFail = true;
if(!$bFail && $allDoubleBlockCount != 1) $bFail = true;
if(!$bFail && $countFirstSmallShowBlocks != 2) $bFail = true;
if(!$bFail && $countSecondSmallShowBlocks != 2) $bFail = true;
if($bFail) $this->fail("Block missing in the horizontal list of blocks on the non live carousel");
I've got a small snippet of code below and I was curious what types of things you would change with regards to best practices/code maintainablity and so on.
function _setAccountStatus($Username, $AccountStatus)
{
if ($Username == '' || ($AccountStatus != 'Active' || $AccountStatus != 'Banned' || $AccountStatus != 'Suspended')) {
// TODO: throw error here.
}
$c1 = new Criteria();
$c1->add(UsersPeer::USERNAME,$Username);
$rs = UsersPeer::doSelect($c1);
if (count($rs) > 0) {
$UserRow = array_pop($rs);
$UserRow->setAccountStatus($AccountStatus);
try {
$UserRow->save();
} catch ( PropelException $e ) {
return false;
}
return true;
}
return false;
}
I would use the empty() instead of $Username == '' in your if statement. I haven't used propel before, but I would prefer to have this method be on my User object itself with the fetching and saving of the user object performed by a seperate object. Pseudo code would be something like this.
$user = userManager->getUser($username);
$user->setAccountStatus($accountStatus);
$userManager->saveUser($user);
An else clause before the last return false would be prefererred, just to make the code more readable.