multiple and or logic in php if statement not working - php

I have gone round and round with this and I can't seem to get the logic correct for what I want.
Here is the code:
function fetchFile() {
global $directory;
if (isset($_GET['id'])) {
global $sampleIssue,$freeIssue;
$id = mysql_real_escape_string($_GET['id']);
$result = mysql_query("SELECT `volume`,`number`,`EditorMessage` FROM `articles` WHERE `id`='$id';");
$article = mysql_fetch_assoc($result);
if
(($article['volume']!=$sampleIssue['vol'] || $article['number']!=$sampleIssue['no']) || ($article['EditorMessage']==='N')
&& ($article['volume']!=$freeIssue['vol'] || $article['number']!=$freeIssue['no'])){
global $needsLogin;
$needsLogin = TRUE;
}
Basically I need for the login to be true or if any of the three conditions are met:
$article['volume']!=$sampleIssue['vol'] || $article['number']!=$sampleIssue['no']
OR
$article['EditorMessage']==='N'
OR
$article['volume']!=$freeIssue['vol'] || $article['number']!=$freeIssue['no']
I have tried switch cases too and I am just not getting it.

Related

PHP compare is not working

$snumber = trim($_POST['sn']);
$site_name =strtoupper(trim($_POST['mn']));
$physical = trim($_POST['pp']);
$logical = trim($_POST['lp']);
$port_info =strtoupper(trim($_POST['ti']));
$srlt = mysql_query("select subscriber,terminationid from portinfo") or die(mysql_error());
while($wow = mysql_fetch_array($srlt)){
$suesno =trim($wow["subscriber"]);
$porting = trim($wow["terminationid"]);
if(($suesno == $snumber and $porting == $port_info )){
}
}
the comparison for $suesno and $snumber is working. $suesno is stored in the database as 6661235. but the comparison of $porting and $port_info is not working. and $porting is stored in the database as USER00301500030
try to use && instead of and in if condition

php parameters passed inside function is not working

In php/wordpress I have made a function. I want to pass some parameteres inside the function so that it will show result according to that. So far now my function code is like this
$user_id = get_current_user_id();
function check_user_access($role, $action = NULL ) {
if( $role == 'subscriber') {
if( $action = 'check_customer' ) {
$check_customer = $wpdb->get_var("SELECT COUNT(id) FROM `table1` WHERE `user_id` = $user_id");
return $check_customer;
}
if( $action = 'check_users' ) {
$check_users = $wpdb->get_var("SELECT COUNT(id) FROM `table2` WHERE `user_id` = $user_id");
return $check_users;
}
}
}
Now I am using this function like this
$role = 'subscriber';
$check_customers = check_user_access($role, $action = 'check_users' );
if( $check_users <=1 ) {
//do something;
}
if( $check_users > 1 ) {
//do something other;
}
But its showing the result of $action = 'check_customer'. Means its working for the first block condition. Can someone tell me how to solve this? Am I doing something wrong?
change your
if( $action = 'check_customer' ) {}
to
if( $action == 'check_customer' ) {}
= means Assignment Operator
== means Comparison Operator
refer - from here

Multiple part queries in PHP

I've been learning PHP for about a week, and I need some guidance as to whether or not I should be using arrays to sort my data based on multiple variables. My table contains information about operas, the composers, their nationalities, and includes a link to a relevant site.
Without being overly verbose, I need to let a user select data based on Nationality, Century it was written, and whether or not it contains a relevant link. I'd like to let them be even more specific, but my code is quickly becoming unmanageable. For 3 variables, I have eight separate queries covering each case. If I want to go to 4 variables, I will need 16 queries. I know there is a better way to do this, but I've read multiple times that arrays are more appropriate for smaller quantities, not necessarily a table that contains around 40,000 rows.
$req=$_REQUEST['nat'];
$req2=$_REQUEST['cent'];
$req3=$_REQUEST['imslp'];
if ($req!="any" && $req2!="any" && $req3=="yes") $query="SELECT * FROM operadatabase WHERE nationality='$req' AND century=$req2 AND imslplink = imslplink";
else if ($req!="any" && $req2!="any" && $req3=="no") $query="SELECT * FROM operadatabase WHERE nationality='$req' AND century=$req2";
else if ($req!="any" && $req2=="any" && $req3=="yes") $query="SELECT * FROM operadatabase WHERE nationality='$req' AND imslplink = imslplink";
else if ($req!="any" && $req2=="any" && $req3=="no") $query="SELECT * FROM operadatabase WHERE nationality='$req'";
else if($req=="any" && $req2!="any" && $req3=="yes") $query="SELECT * FROM operadatabase WHERE century=$req2 AND imslplink = imslplink";
else if($req=="any" && $req2!="any" && $req3=="no") $query="SELECT * FROM operadatabase WHERE century=$req2";
else if($req=="any" && $req2=="any" && $req3=="yes") $query="SELECT * FROM operadatabase WHERE imslplink = imslplink";
else if($req=="any" && $req2=="any" && $req3=="no") $query="SELECT * FROM operadatabase";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_query($result);
mysql_close();
$i=0;
for ($i; $i < $num; $i++){
$f12=mysql_result($result,$i,"fullname");
$f13=mysql_result($result,$i,"operatitle");
$f14=mysql_result($result,$i,"nationality");
$f15=mysql_result($result,$i,"century");
$f16=mysql_result($result,$i,"imslplink");
echo "<tr>";
echo "<td>".$f12."</td><td>".$f13."</td>";
if(strlen($f14) > 2) {
echo '<td><img src="/icons/'.$f14.'.png" width="25" height="25"></td>';
}
echo "<td>".$f15."</td>";
if(substr($f16, 0, 4) == "http") {
echo "<td>IMSLP</td>";
}
The best way I can word my questionis this: Within a query, how can I select a set of data based on one variable, then select from that set based on a second variable, then a third, etc.? Alternatively, can I nest queries?
You can create a simple class that includes returned methods for chaining. You would have to assign some if/else here and probably have to add extra variables into the class, but you get the idea.
class Combiner
{
public $base;
public function __construct($base = 'SELECT * FROM operadatabase')
{
// This saves the front of your select statement and makes it available
// for the rest of the methods. Uses in final Write() method
$this->base = $base;
}
public $vars;
public function FetchNat($value = '')
{
// This just checks your $_REQUEST value here
if(!empty($value) && $value !== 'any')
// You'll want to sanitize this value
$this->vars[] = "nationality = '".mysql_real_escape_string($value)."'";
// Returning this allows you to use this method/function
// in your chain. That is why you are returning $this
// on all your methods/functions
return $this;
}
public function FetchCent($value = '')
{
// This just checks your $_REQUEST value here
if(!empty($value) && $value !== 'any')
// You'll want to sanitize this value
$this->vars[] = "century = '".mysql_real_escape_string($value)."'";
return $this;
}
public function FetchIMSLP($value = '')
{
// This just checks your $_REQUEST value here
if(!empty($value) && $value == 'yes')
$this->vars[] = "imslplink = 'imslplink'";
return $this;
}
public $sql;
public function Write()
{
// This compiles all the variables down the line and returns a final string
$statement = (isset($this->vars) && !empty($this->vars))? " where ".implode(" and ",$this->vars):"";
$this->sql = $this->base.$statement;
return $this;
}
}
// Create new instance of your auto-fetcher
$write = new Combiner();
// This is a method chain that will return an auto-compiling string as it compiles further down the line
$test = $write->FetchCent('')->FetchNat('test')->FetchIMSLP('yes')->Write()->sql;
print_r($test);
This would write:
SELECT * FROM operadatabase where nationality = 'test' and imslplink = 'imslplink';

Function returning incorrect response

I've got an issue with a function where it's returning data from the first if() statement as opposed to the secondary if() statement in a function, please see below.
function training($type,$tid)
{
if($type = "id") {
$query = mysql_query("SELECT * FROM trainroster WHERE DATE = CURDATE()");
if (mysql_num_rows($query) == 1) {
$array = mysql_fetch_array($query);
$id=$array['TID'];
}
else { $id = "1"; }
return $id;
}
else if($type = "topic"){
$query = mysql_query("SELECT * FROM trainroster WHERE TID='$tid'");
$array = mysql_fetch_array($query);
$topic = $array['TOPIC'];
return $topic;
}
}
Which is being called like this:
$training = $connection->training("topic",$row['TID']);
When the function is called it's returning the $id as opposed to the $topic even though I'm setting the $type variable to "topic".
Any help greatly appreciated, cheers!
use '==' instead of '=' to compare
'=' is an assigning operator, if you use it to compare, it will always return true. That's why you are getting id always.
if($type == "id") {
....
if($type == "topic"){
....
if($type = "id") assigns the string "id" to $type and returns "id" which is true.
As mentioned by Harish Singh you have to write if($type == "id").
A way to prevent this error is to write if("id" == $type) which results in an error if you forget one "=".
Look at your if statements:
if($type = "id")
if($type = "topic")
You're assigning, not comparing. They should be:
if($type == "id")
if($type == "topic")

What would you change in my code for best practices/maintenance?

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.

Categories