Search not working as intended - php

Why won't my search function ever execute the "else" (else should echo a text when no resulsts haved been found)? I also have some problems when trying to show all results (with no search criterias selected, just by pressing the search button). I'll upload the whole code of the page because I don't know if you need the HTML part as well or not to figure out the problem. I know it's a big chunk of code but please help out if you can. Thanks!
Here's a link to my code: http://pastebin.com/BXe1C0dr

This is not yet the answer, just a brief code structure of Matei Panchios code. Because it is hard to make sense of long code, so I try to simplify it so that other people might be able to help.
$termeni = mysql_real_escape_string($_POST['termeni']);
$tip=$_POST['tip'];
$judet=$_POST['judet'];
if((!empty($termeni)) and (isset($tip)) and (isset($judet))) {
$query = "SELECT * FROM oferte WHERE localitate LIKE '%$termeni%' AND
tip_locatie='$tip' AND judet='$judet'";
// do the query and write some HTML
} elseif (isset($tip)) {
$query = "SELECT * FROM oferte WHERE tip_locatie='$tip'";
// do the query and write some HTML
} elseif (isset($judet)) {
$query = "SELECT * FROM oferte WHERE judet='$judet'";
// do the query and write some HTML
} elseif (!empty($termeni)) {
...
} elseif (!empty($termeni) AND (isset($judet))) {
...
} elseif (!empty($termeni) AND (isset($tip))) {
...
} elseif ((isset($judet)) AND (isset($tip))) {
...
} elseif ((!isset($judet)) AND (!isset($tip)) AND (empty($termeni))) {
...
} else {
// I believe this where it does not get executed.
}
Well, it makes sense why it does not get executed because there is other way that the elseif does not cover. If you look from this point of view
If three variable is set
if((!empty($termeni)) and (isset($tip)) and (isset($judet))) {
If two variables is set
elseif (!empty($termeni) AND (isset($judet)))
elseif (!empty($termeni) AND (isset($tip)))
elseif (!empty($termeni) AND (isset($tip)))
elseif (!empty($termeni) AND (isset($tip)))
If one variable is set
elseif (isset($tip))
elseif (isset($judet))
elseif (!empty($termeni))
When no variable is set
elseif ((!isset($judet)) AND (!isset($tip)) AND (empty($termeni)))
which leave else condition with nothing to cover.
If I were you, I would structure the code as following.
if (!empty($termeni) and isset($tip) and isset($judet)) {
query = '....';
} elseif (!empty($termeni) and isset($judet) {
query = '....';
} // .... the rest of the condition
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
// write HTML table
} else {
// write message that there is no result found
}
This will reduce the size of your code by 6 times.

Related

If statement inside another one is false, return to the else of original if statement

Is there any way in PHP to return at else of first statement, if the second statement which is inside of first, is false
if($first == true) {
//other code which is not necessary to mention here!
if($second == true){
// do smth
}
else{
return to the else of $first statement
}
//other code which is not necessary to mention here!
}
else{
//do smth else
}
Yes, there are multiple ways. For starters, just combine both the statements and give another condition:
if ($first == true && $second == true) {
// do smth
} elseif ($first == true && $second == false) {
// else of$first statement
} else {
//do smth else
}
This can be used as a guidance to get an idea to start. But if you can get a real world example, there can be conditions grouped, tailored to your requirement.
While there is no native way to jump to outer elses from an inner else, but you can set a flag for later processing:
$do_else = false;
if($first == true) {
//other code which is not necessary to mention here!
if($second == true){
// do smth
}
else{
$do_else = true;
}
//other code which is not necessary to mention here!
}
else{
$do_else = true;
//do smth else
}
if($do_else){
//do smth else
}
If the answers above doesn t help you in the real situation, you can create a function for execute in 'else' statements to avoid code duplication

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

Working with multiple rows from a MySQL query

Before I begin, I want to point out that I can solve my problem. I've rehearsed enough in PHP to be able to get a workaround to what I'm trying to do. However I want to make it modular; without going too much into detail to further confuse my problem, I will simplify what I am trying to do so that way it does not detract from the purpose of what I'm doing. Keep that in mind.
I am developing a simple CMS to manage a user database and edit their information. It features pagination (which works), and a button to the left that you click to open up a form to edit their information and submit it to the database (which also works).
What does not work is displaying each row from MySQL in a table using a very basic script which I won't get into too much detail on how it works. But it basically does a database query with this:
SELECT * FROM users OFFSET (insert offset here) LIMIT (insert limit here)
Essentially, with pagination, it tells what number to offset, and the limit is how many users to display per page. These are set, defined, and tested to be accurate and they do work. However, I am not too familiar how to handle these results.
Here is an example query on page 2 for this CMS:
SELECT * FROM users OFFSET 10 LIMIT 10
This should return 10 rows, 10 users down in the database. And it does, when I try this command in command prompt, it gives me what I need:
But when I try to handle this data in PHP like this:
<?php
while ($row = $db->query($pagination->get_content(), "row")) {
print_r($row);
}
?>
$db->query method is:
public function query($sql, $type = "assoc") {
$this->last_query = $sql;
$result = mysql_query($sql, $this->connection);
$this->confirm_query($result);
if ($type == "row") {
return mysql_fetch_row($result);
} elseif ($type == "assoc" || true) {
return mysql_fetch_assoc($result);
} elseif ($type == "array") {
return mysql_fetch_array($result);
} elseif ($type == false) {
return $result;
}
}
$pagination->get_content method is:
public function get_content() {
global $db;
$query = $this->base_sql;
if (!isset($_GET["page"])) {
$query .= " LIMIT {$this->default_limit}";
return $query;
} elseif (isset($_GET["page"]) && $_GET["page"] == 1) {
$query .= " LIMIT {$this->default_limit}";
return $query;
} elseif (isset($_GET["page"])) {
$query .= " LIMIT {$this->default_limit}";
$query .= " OFFSET " . (($_GET["page"] * $this->default_limit) - 10);
return $query;
}
}
And my results from the while loop (which should print out each row of the database, no?) gives me the same row everytime, continuously until PHP hits the memory limit/timeout limit.
Forgive me if its something simple. I rarely ever handle database data in this manner. What I want it to do is show the 10 users I requested. Feel free to ask any questions.
AFTER SOME COMMENTS, I'VE DECIDED TO SWITCH TO MYSQLI FUNCTIONS AND IT WORKS
// performs a query, does a number of actions dependant on $type
public function query($sql, $type = false) {
$sql = $this->escape($sql);
if ($result = $this->db->query($sql)) {
if ($type == false) {
return $result;
} elseif ($type == true || "assoc") {
if ($result->num_rows >= 2) {
$array;
$i = 1;
while ($row = $result->fetch_assoc()) {
$array[$i] = $row;
$i++;
}
return $array;
} elseif ($result->num_rows == 1) {
return $result->fetch_assoc();
}
} elseif ($type == "array") {
if ($result->num_rows >= 2) {
$array;
$i = 1;
while ($row = $result->fetch_array()) {
$array[$i] = $row;
$i++;
}
return $array;
} elseif ($result->num_rows == 1) {
return $result->fetch_array();
}
}
} else {
die("There was an error running the query, throwing error: " . $this->db->error);
}
}
Basically, in short, I took my entire database, deleted it, and remade another one based on the OOD mysqli (using the class mysqli) and reformatted it into a class that extends mysqli. A better look at the full script can be found here:
http://pastebin.com/Bc00hESn
And yes, it does what I want it to. It queries multiple rows, and I can handle them however I wish using the very same methods I planned to do them in. Thank you for the help.
I think you should be using mysql_fetch_assoc():
<?php
while ($row = $db->query($pagination->get_content())) {
print_r($row);
}
?>

PHP - else, 'escape' nesting and skip to elseif

I wasn't too sure how to title this question - Here's a snippet of what I'm doing:
<?php
if ($result_rows >= 1 && $membership = 'active') {
if ($when_next_allowed > $today_date) {
$output = 'You cannot renew your membership for another <b>' . $days_left . 'days</b>.';
}
/*
What if the membership is set to active, but it's been over a year since they
activated it? We don't have any server-side functions for determining such
at the time.
*/
else {
/* do database stuff to change the database entry to inactive */
/* skip to elseif below */
}
}
elseif (2 == 2) {
/* create new database entry for user's membership */
}
?>
If the first nested argument is false, it should move onto else which should continue from there and 'escape' the 'parent' if and move onto elseif. Other wise, if the first nested argument is true, then it should stay put.
Is that even a possible occurrence? The only thing I could think of was to add multiple continue; commands. That, of course, threw an error.
One other idea I had was setting a variable to equal continue; within the else, then set that right before the end of the parent if:
if (1 == 1) {
...
else {
$escape = 'continue;';
}
/* $escape here */
}
But I've never heard of, nor do I know of any method of using variables in a 'raw' form like that. Of course I've done research on it, though I've yet to find out how. I'm not sure if that's common knowledge or anything - But I've never heard of, or considered such a thing until now.
Solution? This is something I always thought about, though I never knew I'd have to use it.
Cleanest I could come up with:
$run = false;
if (1 == 1) {
$run = true;
if (1 == 2) {
/* Do something */
} else {
$run = false;
/* Do something else */
}
}
if (!$run && 2 == 2) {
}
Alternatively, you could use a goto between [Do something else] and the 2nd if block, but it'll be messy either way.
if (1 == 1) {
if (1 == 2) {
/* Do something */
} else {
/* Do something else */
goto 1
}
} else if (!$run && 2 == 2) {
1:
}
If I understand the problem correctly, then you could just do something like this:
if (1==1 && 1==2) {
/* ... */
}
elseif (2==2) {
$success = 'Success';
}
Obviously, I don't need to point out that 1==1 && 1==2 is completely illogical and is just used as an example of two boolean statements.
Update based on update to question:
Unless there are additional steps that you are omitting, this replicates your logic. Hard to know if this really solves your problem, because I don't know what 2==2 represents, or what other steps you might need to perform based on what other conditions.
if (($result_rows >= 1 && $membership == 'active') &&
($when_next_allowed > $today_date)) {
$output = 'You cannot renew your membership for another <b>' . $days_left . 'days</b>.';
}
elseif (2 == 2) {
/* create new database entry for user's membership */
}
This should do what you want to do.
If you have a variable to false and switch it to true if you go into the else you want, you just have to test the value of this variable right after to go into elseif you wanted to go in.
<?php
$test = false;
if (1 == 1) {
if (1 == 2) {
/* ... */
}
else {
/* Skip to elseif below */
$test = true;
}
}
if ($test == true) {
$success = 'Success';
}
echo $success;
?>
Not an easy question as it's really hard to understand what you're trying to achieve but I think this is the solution you're looking for.
<?php
$success = False;
if (1 == 1) {
if (1 == 2) {
/* ... */
} else {
$success = True;
/* True case code can go here */
}
}
echo $success;
?>
pseudo code is your friend.
Alternatively;
<?php
$success = False;
if (1 == 1) {
if (1 == 2) {
/* ... */
} else {
$success = True;
}
}
if $success == True {
/* ... */
}
echo $success;
?>
<?php
$continue = false;
if (1 == 1) {
if (1 == 2) {
/* ... */
}
else {
$continue = true;
}
}
if ($continue==true) {
$success = 'Success';
}
echo $success;
?>

elseif in while subpage

I want to create elseif´s for each row...I can´t figure out how to do it...tried to google (elseif in while)...hope someone could give me a hint to solve this...
$subgalSql = mysql_query("SELECT * FROM galerieCategories ORDER BY title ASC");
while($subgalData = mysql_fetch_array($subgalSql)){
elseif($_GET[galeriepath] == $subgalData[title]){
?>HTML HERE<?
}
}
I hope someone can see what i´m trying to do here...the elseif are going to be subpages...
Thanks for any advice :)
"elseif" is only used as a secondary "if" statement.
if (condition) {
//if condition is true
} elseif (condition2){
//otherwise, if condition 2 is true
} else {
//all else
}
Long story short: what you want is just an "if", since it's the first (and only) condition.
This should work:
$subgalSql = mysql_query("SELECT * FROM galerieCategories ORDER BY title ASC");
while($subgalData = mysql_fetch_array($subgalSql)){
if($_GET[galeriepath] == $subgalData[title]){
?>HTML HERE<?
}
}
$subgalSql = mysql_query("SELECT * FROM galerieCategories ORDER BY title ASC");
while($subgalData = mysql_fetch_array($subgalSql)){
if($_GET[galeriepath] == $subgalData[title]){
//HTML HERE
}
elseif(/*some condition here*/){
// Code if it satifies the conditon
}
}
Ref: http://php.net/manual/en/control-structures.elseif.php
you cannot place an elseif inside the primary condition, it has to follow on after its end.
// what I think your trying to do
if()
{
while()
{
elseif()
{
}
}
}
what you should do
if($x='y')
{
$elsecondtion=false;
}
else
{
$elsecondtion=true;
}
$subgalSql = mysql_query("SELECT * FROM galerieCategories ORDER BY title ASC");
while($subgalData = mysql_fetch_array($subgalSql)){
if($elsecondition && $_GET[galeriepath] == $subgalData[title]){
?>HTML HERE<?
}
}

Categories