If / else if / else with query to a database resulting false. - php

I have a select box with an option for All, and then a list of users.
What I'm struggling with is creating something like this. I have most of it except trying to query the database to for it to check if the variable is in the database.
if ($variable == 'All') { code here }
else if ($variable != 'ALL' != *[result in database]*) { code here }
else { code here }
I have most of it except trying to query the database to for it to check if the variable is in the database.
Any suggestions how I can encorporate a query of a mySQL database in my if statement.
Thanks

if ($variable == 'All') {
... do something ...
} else {
$sql = "SELECT ...";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if ($row['somefield'] == 'whatever') {
... do something else ...
} else {
... do something even "elser" ...
}
}

You can't use operators like that.
Replace:
else if ($variable != 'ALL' != *[result in database]*) { code here }
With:
else if ($variable != 'ALL' AND $variable != *[result in database]*) { code here }

Related

Advice in design about Control Structure else if, switch o a better way?

I made the script to do what is expected, so it work ok but there must be a more elegant way to achieve the same result. I know that using switch will make it look nicer but not sure if the result will be the same as the 'default:' behavior:
This is the section of the script i want to refactor:
foreach ($free_slots as $val) { // here i am looping through some time slots
$slot_out = $free_slots[$x][1];
$slot_in = $free_slots[$x][0];
$slot_hours = $slot_out - $slot_in;
// tasks
if ($slot_out != '00:00:00') {
// Here i call a function that do a mysql query and
// return the user active tasks
$result = tasks($deadline,$user);
$row_task = mysql_fetch_array($result);
// HERE IS THE UGLY PART <<<<<----------------
// the array will return a list of tasks where this current
// users involved, in some cases it may show active tasks
// for other users as the same task may be divided between
// users, like i start the task and you continue it, so for
// the records, user 1 and 2 are involved in the same task.
// The elseif conditions are to extract the info related
// to the current $user so if no condition apply i need
// to change function to return only unnasigned tasks.
// so the i need the first section of the elseif with the
// same conditions of the second section, that is where i
// actually take actions, just to be able to change of
// change of function in case no condition apply and insert
// tasks that are unassigned.
if ($row_task['condition1'] == 1 && etc...) {
} else if ($row_task['condition2'] == 1 && etc...) {
} else if ($row_task['condition3'] == 1 && etc...) {
} else if ($row_task['condition4'] == 1 && etc...) {
} else {
// in case no condition found i change function
// and overwrite the variables
$result = tasks($deadline,'');
$row_task = mysql_fetch_array($result);
}
if ($row_task['condition1'] == 1 && etc...) {
// insert into database
} else if ($row_task['condition2'] == 1 && etc...) {
// insert into database
} else if ($row_task['condition3'] == 1 && etc...) {
// insert into database
} else if ($row_task['condition4'] == 1 && etc...) {
} else {
echo 'nothing to insert</br>';
}
}
}
Basically i run the else if block twice just to be able to change of function in case nothing is found in the first loop and be able to allocate records unassigned.
I haven't changed the functionality of your code, but this is definitely a lot cleaner.
The main problem was that your logic for your if/else statements was confused. When you're writing:
if($a == 1){ } else if($b == 1){ } else if($c == 1){ }else{ //do something }
You're saying If a is 1 do nothing, if b is 1 do nothing, if c is 1 do nothing, but if all of those did nothing, do something when you can just say if a is not 1 and b is not 1 and c is not 1, do something.
I wasn't too sure on your second if statements, but generally it's not good to have an if else with no body within it. However, if the "insert into database" comment does the same thing, you can merge the 3 if statements that do the same code.
I hope i've cleared a few things up for you.
Here's what I ended up with:
foreach ($free_slots as $val) { // here i am looping through some time slots
$slot_out = $free_slots[$x][1];
$slot_in = $free_slots[$x][0];
$slot_hours = $slot_out - $slot_in;
// tasks
if ($slot_out != '00:00:00') {
$result = tasks($deadline, $user);
$row_task = mysql_fetch_array($result);
if (!($row_task['condition1'] == 1 || $row_task['condition2'] == 1 || $row_task['condition3'] == 1 || $row_task['condition4'] == 1)) {
$result = tasks($deadline,'');
$row_task = mysql_fetch_array($result);
}
if ($row_task['condition1'] == 1 && etc...) {
// insert into database
} else if ($row_task['condition2'] == 1) {
// insert into database
} else if ($row_task['condition3'] == 1) {
// insert into database
} else if ($row_task['condition4'] == 1) {
} else {
echo 'nothing to insert</br>';
}
}
}

How do I add an if / else?

I am using the following code to pass a variable. if variable = a, do nothing.
I then want to check if variable = a, do nothing, if b, do nothing, else do something
<?
if($_GET['pageid'] == 'a'){
} else {
include('header_image.php');
}
?>
Above is the code I have working correctly for one vartiable.
How do I add an if / else?
if($_GET['pageid'] != 'a' && $_GET['pageid'] != 'b'){
//do smth
}
This is a comment - i want the formatting...
To do what you want:
if ($_GET['pageid'] == 'a') {
// do nothing for now
}
elseif ($_GET['pageid'] == 'b') {
// do some more nothing...
}
else { // we do something...
include('header_image.php');
}
You could combine the 'do nothing' tests as:
if ( $_GET['pageid'] == 'a'
|| $_GET['pageid'] == 'b') {
// do nothing for now
}
else { // we do something...
include('header_image.php');
}
I agree it reads better than the 'not equal and' tests. However, that is what 'programmers' use so it is worthwhile getting used to it.

Proper way of handling multiple cases

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;
}
}

PHP syntax explanation

How can I translate to PHP syntax something like that:
if(isset($_GET['q'])//but q=is not empty or <2 because in this case redirect to) { do this } else { do this one }
I hope it's not too massy.
Thanks.
updated question
Why this code does not redirect ?
if(isset($_GET['q']))
{
if(!empty($_GET['q']) || $_GET['q']>2)
{
$q = $_GET['q'];
$q = mysql_real_escape_string($q);
$sql = $db->prepare ('SELECT * FROM t WHERE a = :a');
$sql->bindParam(':a',$q);
$sql->execute();
}
else
{
header("Location:somepage.php");
}
} else {
$sql = $db->prepare ('SELECT * FROM t ORDER BY b');
$sql->execute();
}
Do like this
<?php
if(isset($_GET['q']))
{
if(!empty($_GET['q']) || $_GET['q']<2)
{
header("location:somepage.php");
}
else
{
echo "Cannot be redirected";
}
}
What? Do you mean the code for the "text" you have?
if(isset($_GET['q']) && (!empty($_GET['q']) || $_GET['q'] < 2)) {
// redirect here using header("location: foo.php") or some other function if you are using some framework.
}
else {
/otherwise do something else.
}
Update to your updated question:
Because $_GET['q'] isn't empty? Do a var_dump of $_GET so we, and you, know what's in there. It's impossible to tell otherwise. But I think your code is doing exactly what you have told it to do. You just don't have the complete picture of what you want to accomplish.
I assume q is a number here.
if (isset($_GET['q']) {
if (empty($_GET['q'] || $_GET['q'] < 2)) {
// do redirect here
} else {
// do mysql here
}
}

Codeigniter not properly processing a foreach loop

I've got about 10 rows in my db and 3 of which have status == to 'Pass'. The problem I've noticed with the code below is with the foreach loop. It's not wanting to work properly. I can't even get the script to send the jSON data back to the browser which means the script isn't processing past the foreach statement. Does anybody know how to fix this?
public function logsig() {
header('Content-type:application/json');
$postedUser = $this->input->post('username');
$password = $this->input->post('password');
$hashedPass = $this->encrypt->sha1($password);
$query = $this->db->query("SELECT * FROM users WHERE username = '{$postedUser}' AND password = '{$hashedPass}'");
foreach ($query->result() as $row) {
if ($row->status == "Pass") {
if ($query->num_rows() > 0) {
$this->session->set_userdata('logged', "1");
$this->session->set_userdata("username", "{$postedUser}");
echo json_encode(array('session_state' => true));
} else {
echo json_encode(array('session_state' => false));
}
} elseif ($row->status == "Fail" || "Pending") {
exit;
}
}
}
You're echoing the JSON in each iteration of the loop. This will make something like this:
{"session_state": true}{"session_state": false}
This is not valid JSON.
You need to build an array, and then echo json_encode() (just once) after the loop.
Also your elseif should be this:
elseif ($row->status == "Fail" || $row->status == "Pending")
Replace elseif ($row->status == "Fail" || "Pending") { with
elseif ($row->status == "Fail" || $row->status == "Pending") {
You are missing $row->status == in your second condition of elseif block

Categories