Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    PHP




Avoiding Endless Conditional Statements


Here is my problem. I want to make a webapp that will basically take
the work out of finding what tool works for what situation. There are
5 factors that go into tool selection. 1)Material Group, 2)Insert
Radius, 3)Insert Type and Size, and 2 others that I can't remember
off-hand. There are probably about 1000 different scenarios that I
have to code for..(there are several blank table cells and it's not
setup as you might imagine, there is a lot of overlapping), and I
desperately want to avoid making a gigantic conditional statement. I'm
afraid that I really have to provide a picture of what I'm doing here,
so I will do that. Here is the link.
You only see 3 of the 5
factors on this page, and the other 2 have to do with whether this
table or one of many other tables (not pictured) will be used.

So, now that I've confused everyone. That's my table. What's a good
way to go about programming that sucker in so that people don't have to
do all the "work" involved to figure out what tools they need. They
should just be able to choose selections from 5 dropdown boxes and get
one tool back. A tool is something like "10.655.600".




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Conditional Statements And Loops
Not long ago I was asked to give PHP lections to some private IT
school. I'm on second lection now, and will be teaching my :) students
conditional statements (if..else and switch) and loops (while and for).
That was my story, now the question.

Can you give me an advise on some geeky use of those statements to stir
up some enthusiasm in students.

Question On Conditional Statements
I'm a perl programmer and am trying to learn PHP.

So far I have figured out most of the differences, but have not been able to
find out how to do the following:

When running through a loop, how can you test two separate conditions
against the same $element of an array. For example, this is how I thought it
would be done (similar to Perl), but it did not work:

if (eregi("apple", $line) and (eregi("orange", $line) {

do whatever;

}

Basically testing each line of an array to see if both the words "apple" and
"orange" are present.

Also, is there any equivalent to the following from Perl while running
through a loop:

next if (whatever conditions);
last if (whatever conditions);

An Endless Loop
This is a continuation of a previous thread:"Displaying text with
include file." This is the PHP include file.

I have about googled myself out on this one. If I have found what it is
I seek , I don't recognize it.

==========#
<?php
$data = file("outing.1.php");
foreach ($data as $line) {
$line = explode("_", $line);
print $line[&#390;'];
}

?>
============#
This code does exactly as expected. It prints to the screen the first
element of the array.

The array is of unknown length. I need to print to the screen all
elements. I have been able to do this with: for loops, while loops, do
loops, and some if statements, the problem is stopping when it reached
an empty element.

Even if I chose an arbitrary number to stop at, it would print the
elements and the balance in error lines.

Mysql Query With Near/endless Loop
I'm having a loop running in the folowing Query when I run it through Mysql command line (Only 1 row returns), but when I try it through a PHP page, it gets the "endless loop"...
Code:

Endless Loop Script Crashing Apache
I'm using PHP 4.2.2 and Apache 2.0.4.0. A script running on a virtual
host had an endless loop in it that brought Apache to its knees. I have

max_execution_time=90
and memory_limit=32M

to handle larger file uploads and Gallery stuff (thumbnail processing)
but the script goes way past 90 seconds. Safe mode is off but the
script doesn't override it by using set_time_limit(). I have to restart
Apache to fix the problem. Apache Timeout is set to 300 seconds but
still goes way beyond that.

Any idea why the script might not be timing out?

Avoiding Load Time?
I have a script that takes quite a long time to load since the PHP is processing quite a lot of info. Is there any way I can initiate the script, then have it move on to another page right away so I don't have to wait for the PHP to finish processing? (having ignore_user_abort(); on so it will continue to process in the "background" - if my thinking is correct...)

Avoiding Duplicate Results??
Does anyone know if this is possible:

I'm running a query against a db and am pulling name and ticket # (for a helpdesk)...  What I'd like to do is take the results from the "Name" field, but only show EACH NAME ONCE in a table.  For example, I might get 200 results back, but only want to show the name of the person once, with how many tickets they have assigned to them.

So it would look like this:

___Name___|___Number of tickets___
___Bob____|__________3__________
___John____|_________23__________
___Mark____|_________4___________

...etc, etc...  does anyone know how to go about starting this?  I'm assuming an array of sorts. 

Avoiding Sent Mail To Spam?
Earlier this day i fixed my mail problem for account activation when someone registrates. I thougt that the mail() function didnt worked but instead it did worked by sending all the mails to my email spam. I've seen some code that avoids emails getting into spam.

Writing A Review App But Avoiding Spamming
I want to write a revie module for some listings I have but I can imagine people posting 100s of times to say how great they are and 100s of times to slate their competitors.

I figure only allowing one review per listing from a particular IP address is a good start any other suggestions?

Avoiding Duplicate Array Elements
Im having a problem with this code. Im
trying to remove duplicate elements from an array created via $_GET.
I want users to be able to click on a link which sends an email
address to an array. I just want to remove duplicate email addresses
from the array. Ive tried array_unique() on my test server but it
doesnt work. So i tried to remove duplicates myself before storing
them into the array. The script works great without the checking,

session_start();

$email = $HTTP_GET_VARS['email'];
if (isset($_SESSION['Array']))
{

$Array = $_SESSION['Array'];
$numElements = count($Array);
for($counter=0; $counter < $numElements; $counter++)
{
/* Problem is here */if ($Array[$counter] == $email)
{
exit();
}

else
{
array_push($_SESSION['Array'],$email);
$EmailArray = $_SESSION['Array'];
$_SESSION['Array'] = $EmailArray;
}
}
}

else
{
$EmailArray = array();
array_push($EmailArray,$email);
$_SESSION['Array'] = $EmailArray;
}

Using Mail() And Avoiding Spam Boxes !
Im using the mail() command to send an email to people who register on
my site, but many are ending up in people's spam boxes on hotmail.

This problem isn't true of all users - probably around 60%.

Im being as open as possible using a number of headers, but can anyone
suggest a way of getting through with less problems ?

$sender = "From: Name <email@domain.com>" . "";
$sender .= "Return-Path: email@domain.com" . "";
$sender .= "MIME-Version: 1.0" . "";
$sender .= "Content-Type: text/plain; charset=iso-8859-1" . "";
$sender .= "Content-Transfer-Encoding: 8bit" . "";
$sender .= "X-Mailer: PHP/" . phpversion();

Avoiding Php Mail() To Spam Boxes
I'm sending soliticited emails for a nonprofit and i'm finding when i use PHP's mail function, and the mail goes through my ISP's SMTP, a decent percentage of the mails go to people's spam boxes.

are there known headers or something i could add to my code to make them less spam box prone?

PHP File Writing And Avoiding A Race Condition
So, PHP has this issue where you cannot lock a file until you open it, which leaves the door open for a race condition when writing files. I wrote the following code a while back and think it should work (and in fact use it and it works), I just thought I'd post it here for an audit and in case it might be useful for someone to use or I missed something!

/**
* Write a file to the server.
*
* First open a temp file for writing and acquire a lock.
* Proceed to write, unlock and copy the file from a temp file. If the
* file size is the same, the write worked, clean up and go home. if
* not, clean up and hope it works the next time.
*/
function cms_writeFile($filename, $tempfile, $data) {
$ft = fopen($tempfile, 'w');
if(flock($ft, LOCK_EX)) {
fwrite($ft, $data);
flock($ft, LOCK_UN);
fclose($ft);
if(copy($tempfile, $filename) && filesize($tempfile) == filesize($filename)) {
unlink($tempfile);
return true;
} else { // The whole process failed.
unlink($tempfile);
unlink($filename);
return false;
}
} else return false;
}

I pass it a random tempfile name, so at that point I think we avoid any race condition issues, but to be paranoid I check the file size after the copy. If the files are of a different size, I drop them both and hope this works the next time.

An example to use the function:

if(cms_writeFile('test.php', 'randomg-temp.php', 'some data')) {
echo 'written'
} else {
echo 'notwritten'
}

Seems right, and it works, am I missing anything?

Conditional Loop
I have one table, "players" that has player info including start season (year). I then have a table for each season with player stats, i.e. games played etc called stats200X where X is the year obviously.

I have no problem with extracting data from the current year, but what I would like to do is get data from previous years too. I was thinking about doing something like:

(year) - (startyear), which for example could be 3.

I don't know where to begin, but I want to be able to loop though previous years so that, if tables exist of course, I could do

select * from stats{Y -1}
display
select * from stats{Y -2}
etc

Would I need to hard code this or is there a way of doing this though a conditional loop?


Conditional Login..
I have a form with a username & password field along with 3 radio buttons.

What I basically want to achieve is if radio button A is checked it will post the username & pass to a.php, If button B is checked it will post the username & pass to b.php and so on for button C.

Checkboxes,conditional
Basically I have what seems to be a very small problem but I am driving ny self mad trying to figure out what the problem is. Here is what I have: I have a form with two checkboxes:

<input type="checkbox" name="medicalcheck" >
<input type="checkbox" name="dentalcheck" >

the form is posting the a php file, decision.php, that simple checks to see if the boxes have been checked and performs an operation in either case. Here is the code:

Once Conditional Causes Error, The Other Doesn't...why?
There are 2 if statements at the beginning of this code snippet.  The one that is currently commented out works while the one that is not commented out yields this error

Parse error: syntax error, unexpected '{' in C:xampphtdocsench2index4.php on line 106

I am just not seeing why. Code:

Conditional Structures
I am wondering about conditional structures and the depth of nesting allowed, if at all. For example I know I can do this: Code:

Conditional Form
I want to condtionally display an HTML form. I havnt got a clue how it can be done, I suppose its the same way as putting html tables in php, but I cant get it to work. Here is the condtion:

<?php 
 if (!empty($pk))
  {    

And here is the form:

<form action="google.php" method="GET" name="deleteForm" >
<input type="hidden" name="pk" value="<? echo $pk;?>">
<input type="submit" value="Delete">
</form>

Conditional Third Expression In For Loop
Is it possible to make expr3 $i++ under one condition and $i-- under another? Instead of having the condition outside the loop and having two loops. Or I could just use a while loop, I guess.

Sessions + Conditional Include
I am having a little problem in trying to figure out why my session state is not expiring after I close the browser window. Having been used to the ASP way of doing things I am trying to get my head around this slightly different method of handling sessions in PHP....

What happens is that I log on to the site, do various things and then close it when I am finished. I return the next day to find that the 'logged in' menu is displayed first which shouldnt happen until you have logged in again.

I assumed that the session was been stored as a cookie but wasnt been released after the session terminates by default, but found I was wrong when I deleted all my internet files and went back to the site.

My code for the first page is as follows..

Conditional PHP Cookies; If Cookie = 1 Do This...
I've figured out cookies ... now I'm trying to combine them with if conditions.

For cookie 'bandwidth1' I want to echo that it is set to 1 by the cookie to confirm this in the brower through regular html.

My if/else statements don't seem to be working though...heres the code I have now.

<?php
setcookie("bandwidth1","0",time()+2592000,"/");
setcookie("bandwidth2","1",time()+2592000,"/");
setcookie("bandwidth3","2",time()+2592000,"/");
?>

<?php
if (isset($_COOKIE["bandwidth1"])=="1")
echo "Bandwidth is 1!";
else
echo "Bandwidth is unknown";
elsif
echo "Cookie was not set?";
?>

MySQL Conditional Statement
What I am trying to do is kind of like an advanced search. Basically, I have three dropdowns, for this I am going to use the example books: Three dropdowns, which are

1) Author
2) Language
3) Type (Hardback or Paperback)

Typical search: I want to get a list of all books written by STEPHEN KING, that are written in ENGLISH and that are HARDBACK ok fine, but what if I just want to search for ALL books by STEPHEN KING regardless of the language or the type of book?? Heres the SQL i would use for all 3 "search parameters": PHP Code:

Writing Conditional Statement
I'm trying write a conditional statement that updates the database in 1 of 2 ways depending on the values given. I'm only 2 weeks into learning PHP/MySQL so I realize the way I've written it out is probably sloppy and more inefficient than what it could be. I've just been winging it from examples and trial and error and have gotten everything working except for this. I'm not sure if I have my logic or syntax wrong.

Application-specific details:
This is a simple invoicing application. Every invoice is in either 1 of 3 states:

- pending (default state when a new invoice is entered)
- paid (state when invoice is paid in full)
- partial (state when only partial payments have been made on the invoice)

What I'm trying to do is this:

1. If a partial payment is made on an invoice, the status is set to 'partial' (this is working)
2. If the payment posted was the full amount of the invoice or the final amount needed to pay it in full, the status is set to 'paid' (this is not working)

My processing logic works like this:
1. There is a total invoice amount stored in the invoice table represented by $total variable (working)
2. When payments have been made to that invoice (stored in the payments table), I show the remaining balance on their invoice by calculating the sum of those payments and subtracting them from the total (this is represented by the $diff variable and is working)
3. The part not working: When the remaining balance ($diff) minus the payment amount posted ($_POST['amount']) is equal to 0, the status is set to paid. PHP Code:

Mutlipart And/or Conditional Form
I have a form that needs to have conditional statements, and I am not sure how to "fix" this. The existing form is split in two parts - the form, and the processor. I would think that I will need to combine them, but..

Anyways - what I need is somewhat simple - if a certain option (from a <select>) is chosen, force another field to be completed. I also have 2 other fields that if the radio button is set to YES, require new fields. Ideally, the optional fields would only be shown to the user IF they are required.

Conditional Select From Mysql
I have a mysql database which stores race data that I want to open up to users for viewing. I want the user to be able to select various subsets of the data according to the parameters: race, gender, age, and type (and maybe sometime, by name as well). This is BOTH a mysql question and a php one, as I ask for a more efficient solution (see bottom this post).

Here is a snippet of how I am implementing the mysql statements to select only the exact subset of data. PHP Code:

Conditional Preg Match
The following bit of code does a preg match and does something if true
(sets $browser to ppcie)

Without using if then and else's how do I code it so it does not equal
what it is testing for? So if it does not find ppc in the $agent then
it does something else/sets it to something else?

$agent = getenv("HTTP_USER_AGENT");
if (preg_match("/PPC/i", "$agent")) {
$browser = 'PPCIE'
}

Help With Posting Conditional If Statement
I've tried scaling down a script to the bare minimum and
it still is not working correctly. What I think should happen is that when
the field app_fname is blank, that $hold_chk will get set to 1 and the 1st
if statement will be executed. What actually happens is that when I hit
submit, the form stays where it is, for example if the form where the submit
button is located is on the form other.php, then when I hit submit this is
where it stays. If I then hit the submit button a 2nd time, it post to the
some.php form. I've tried this script without the conditional if(isset()
and it works. I need to have the isset() otherwise the form displays all
empty fields as soon as it loads, before the submit button is hit.

<?php

$holdchk = 0;

if (isset($_POST['B1'])) {

echo "<br><br><br>";
if (empty($_POST['app_fname'])) {
$holdchk = 1;
}

if ($holdchk == 1 ){
echo "<form method="POST" action="some.php">";

}

if ($holdchk == 0 ){
echo "<form method="POST" action="other.php">";

}
}
?>

<html>

<head>
</head>

<form method="POST" action="">

When
hit the submit button</font></b<input
type="submit" value="Submit" name="B1"></p>
</form>
</body>

</html>

Conditional List Boxes
I am attempting to create a list box that is dynamically populated based on the selection of another list box.  I am in way over my head..only way to learn I guess.  The code below has a year listbox and then based on the year selection, the page should either show another listbox (show industry selection when year <> 2005) or it should render the main form (when year=2005). I cannot get the main form to appear. Code:

Conditional Email Text To Hyperlink
I am trying to write a content management section for a web site.

I have managed so far to use htmlarea to give users a basic, but user
friendly interface by which to edit the page content.

The user can add emails by symply typing john@example.com - IE automatically
converts this to a hyperlink. The trouble is sometimes the users use plain
text. I have been using the following line to convert plain text to a
hyperlink:

$pagetext=ereg_replace('[A-Za-z0-9_]([-._]?[A-Za-z0-9])*@[A-Za-z0-9]([-.]?[A-Za-z0-9])*.[A-Za-z]+',
'<a href="mailto:?subject=Email%20from%20web%20site"></a> ',
$pagetext);

This works well - BUT it completely screws up any existing hyperlinks. Is
there a way to convert the plain text email address in to a hyperlink only
if it is NOT part of a hyperlink.

Basically I need some way of checking
* If it's plain text > convert to a hyperlink
* If it's already an email hyperlink leave it alone.

I have tried looking up and testing everything I can think of - but am
finally asking around before I go mad.

Simplifying A Basic If Statement Conditional
Is there a more efficient way to write this:
if($var=1 || $var=4 || $var=27 || $var=28 || $var=30 || $var=37||
$var=38){echo "true";}

Cascade Dropdown Or Conditional List
I would like to create a conditional cascade form.  based on the selection, it can display or not display an input form for the user to enter an string of text. then at the bottom of the page (or when a user submit) connect all the sections including the input field all together (it's like a story maker?)

Conditional Statement For Default Case
I'm trying to create a conditional statement for my menu that will check to see if the page is on the default case. Code:

Syntax Issue With Form And Conditional Statement
Is it possible for a <form ... action="program.php"> to contain a conditional statement for the action? For example, I want to call one PHP program if variable $a="screen" and another program if variable $a="download". I have been struggling with this for some time and cannot seem to get it to work.

PHP Conditional Setting Of Radio Button Default
I'm working on an edit inventory form, and I'm pulling a field from my database that's going to be a 'Y' or 'N'.  Based upon this, I want to default the 'customizable' radio button to either checked="Y" or checked="N". Code:

Make Function Equal To String In Conditional
I can usually figure something out, but I CANNOT figure this one out: This is a classified word ad script to count the words in a text area ($wrdad) and multiply it by the rate for how many times the ad will run in the newspaper.  I know my code is messy and ameture, don't be too critical, but it works - everythign except one part. We have a 15 word minimum. I have this area commented out as //Problem Area/// in the code below.

In a nutshell, I want function wordcount($wordad) to be equal to 15 if there are fewer than 15 words in the $wordad textarea. It just seems to ignore the wordcount($wordad) == 15; in my conditional. Code:

If Else Statements
I am having trouble with the else section of my if else code. In my database the email address of clients is stored as $yfemail.

The clients have listed the websites, email, etc for others in a search page like environment. Whend displaying the listings I am trying to create an if else statement that displays "no email given" if $yfemail == 'community1@blahblah.com' This is not a problem.

The problem lies in my else statement. I do not want to give the actual email address out to the general public, so I can't just add a simple else echo $yfemil type of code. We have a page on the site that allows users to e-mail the clients anonymously. This means in the else staement I need to send the user to another page on our site and pass the email address in the url. PHP Code:

For Statements
i have two values i wish to use in the one for(); Ill make an example below which will make it easier to understand what im trying to do.

<?php
$value1 = 100;
$value2 = 100;

for ($i=0;$i<???;$i++){
$value1 = $value1 - rand(0,10);
$value2 = $value2 - rand(0,10);
echo("Value1 is now $value1, And Value2 is now $value2");
if ($value1 < 0){ ???=1; }
if ($value2 < 0){ ???=1; }
}
The question marks () is the section that im not sure how to do... As i have two values that are 100 but $value1 or $value2 will reach 0 first and i wish it to stop once either have become 0.

Pagination + While Statements = ???
How would I do that? I've added pagination to some of my scripts before,, but I always used if statements for that.. how to do it in while statements?

Case Statements
I am fairly new to php and I was wondering if there was something similar to case statements in C++.

It would be a lot easier than writing about 20 if statements.

Joining WHILE Statements?
is it possible to join WHILE statements as just putting multiple WHILE statements one after another doesn't work.

Using Heredoc For SQL Statements
I've used heredocs for single SQL statements without a problem. Also,
I've tried this using the SQL form on PhpMyAdmin and it works so I
conclude it should work in PHP.

Problem: getting syntax error with following SQL statement:

$_sql = <<<SQLDOC
LOCK TABLES `table_name` WRITE;
INSERT INTO `table_name` ('col_a', 'col_b') VALUES ('value_a1',
'value_a2');
INSERT INTO `table_name` ('col_a', 'col_b') VALUES ('value_b1',
'value_b2');
UNLOCK TABLES;
SQLDOC;

Error Message:

"You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ' INSERT INTO `table_name`..."

Parsing SQL Statements
can anyone tell me whether there is a way to get SQL statements parsed. First idea that I could get out of my head is mysql's COMMIT-ROLLBACK syntax. But I am not sure about it. Actually deleting,inserting and redeleting-reinserting seems a bit unnecessary.

Two While Statements Not Working Together?
I have two while statements in a php script. However, the second one is not outputting the way it should. When I test them individually, both work. Can anyone have a look at the code and tell me what I must edit to get both working together. PHP Code:

Echo Statements
I'm trying to change the user password - how? First, the user enters his old password, enter the new password twice. If the old password does'nt match with that of in the table, displays an error message.If the new password entered twice is not the same, also displays an error message.

If the old password matches with that of in the table and the new password entered twice is same, then the password is updated.MY CODE ALSO WORKS ABSOLUTELY FINE!!!! But, I've problems in displaying these error messages - Like,

1.If the old password does'nt match with that of in the table,and the newpassword which is entered twice is same, it has to display an error message "Old password is wrong"
2.If the entered old password matches with that of in the table, and the new password which is entered twice does'nt matches, then it has to display an error message "New password does'nt match"

3.If everything goes well, it has to display "Password updated successfully" PHP Code:

Ereg Statements
Is this a good ereg statement?

if
(!ereg("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]{1,})*.([a-z]{2,}){1}$",$email_1
or $email_2))
{
unset($_GET['do']);
$message_new = "<font color='#cc0000'>$email_1 or $email_2 is not a
valid email address.
Please try again.</font>";
include("login_form.php");
exit();

I am just trying to check if the e-mail fields _1 & _2 on the form contain
valid characters, without getting to complicated. The form I am using it in
keeps returning that I am not entering a valid e-mail address, such
"chris.bolton@ntlworld.com", or "chris@myweb.co.uk",or "chris@ntlworld.com"
not sure why this is the case?

Include Statements
I am currently using a perl script to process form data. I don't want
to lose the functionality I have with this script but need to output
the data to a mysql db. Someone mentioned that I should use includes
to process the form with a php script. Can one form be processed by
two scripts at the same time. If so is this a bad idea? It sounds like
it would solve my problem if it would work. The problem is that I have
done nothing more than setup a fre script that requires no coding. I
don't even know how to implement an include statement.

IF Statements Not Working
My IF statements are not working as I need them to work. Every varible in the sub= statement has to be filled with something. If the variables are filled with nothing, then the script does not work. The variables come into the script from a form. I have fundamental errors in how I have put the IF statements together. Code:

Multiple WHERE Statements
I'm trying to run multiple WHERE statements in a single query but it's not working out. How would I do this?

$q1=("SELECT * FROM roster WHERE (Position<='4' AND Terminated='0') ORDER BY Position");


Copyright © 2005-08 www.BigResource.com, All rights reserved