PHP - Make All Variables Equal To Zero?
is there an easy way to make all variables equal to zero (as opposed to empty) at the end of a loop?
rather than
$a =0;
$b=0;
etc etc
as i have hundreds and hundreds of the things and need to reset them all to equal a value of zero.
thank you in advance.
Similar TutorialsProblem: I've echoed out all the variables and they all come up and the while loop works too but I want to delete a row from a table where the $session and $row['product_code'] variables match. Result: The row does not get deleted. while ($row = mysql_fetch_array($result)) { if (isset($row['product_code']) > 0) { $ans = $row['quantity'] - $row['qty']; if ($ans<= 0) { $query1 = 'DELETE FROM ecomm_temp_cart WHERE session = "' . $session . ' AND product_code = ' . $row['product_code'] . '"'; mysql_query($query, $db) or (mysql_error($db)); echo 'This ' .$row['product_code'] . ' is sold out.'; } } } Any help appreciated. I need to create a loop where I can cycle through three variables and determine the maximum output. Here is an example... First loop $var_one = .01 $var_two = .01 $var_three = .98 run calculation for vars Second Loop $var_one = .02 $var_two = .01 $var_three = .97 run calculation for vars This loop would run through ALL possible values making sure that the total of all variables would always equal 1. There could be more than three variables so this will be dynamic. I have no idea how to make this. Any thoughts? Hello, to start off I am very new to this and trying to learn as I go by using sample code and putting things together as I need them. I am working on a basic database editor that will make a select able list from a sql table. In this case, "Employees". Then, after I select a name from that list it gives me the option to alter that information and save it. What I am missing however, is the option to pre-fill what the database already has while in the edit part. The drop down menu only shows the Employee name. So when I select the name, only the EmpID variable is transferred to the next part. I want all fields pre-filled out by defining variables from the SQL table.
So I cant figure out how to call the database, then the table, Find the PRIMARY KEY (which is the EmpID) and create variables from (FirstName, LastName and Pay), but only for the EmpID that was slected before hand. How can I do this? Once I can make those variables, I can use them to pre-fill the text areas..
Thank you in advance. Also if needed I will post the code I have so far.
<html> <head> <title>Edit Employee</title> </head> <body> <?php $dbhost = 'localhost'; $dbuser = 'Labor'; $dbpass = '***********'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); // Check connection if(! $conn ) { die('Could not connect: ' . mysql_error()); } if(isset($_POST['save'])) { $EmpID = $_POST['EmpID']; $FirstName = $_POST['FirstName']; $LastName = $_POST['LastName']; $Pay = $_POST['Pay']; $OrgEmpID = $_POST['OrgEmpID']; $sql = "UPDATE Employees SET EmpID='$EmpID', FirstName='$FirstName', LastName='$LastName', Pay='$Pay' WHERE EmpID='$OrgEmpID'"; mysql_select_db('Labor'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not update data: ' . mysql_error()); } echo "Updated data successfully\n"; } else { if(isset($_POST['select'])) { $EmpID = $_POST['EmpID']; $FirstName = $_POST['FirstName']; $LastName = $_POST['LastName']; $Pay = $_POST['Pay']; $OrgEmpID = $_POST['EmpID']; echo ' Update Employee <form method="post" action="'.$_PHP_SELF.'"> <table width="400" border="0" cellspacing="1" cellpadding="2"> <tr> <td width="100">Employee ID: </td> <td><input name="EmpID" type="text" id="EmpID" value="'.$EmpID.'"></td> </tr> <tr> <td width="100">First Name: </td> <td><input name="FirstName" type="text" id="FirstName" value="'.$FirstName.'"></td> </tr> <tr> <td width="100">Last Name: </td> <td><input name="LastName" type="text" id="LastName" value="'.$LastName.'"></td> </tr> <tr> <td width="100">Hourly Pay: </td> <td><input name="Pay" type="text" id="Pay" value="'.$Pay.'"></td> </tr> <tr> <td width="100"> </td> <td> </td> </tr> <tr> <td width="100"> </td> <td> <input type="hidden" name="OrgEmpID" value="'.$OrgEmpID.'"> <input name="save" type="submit" id="save" value="Save"> </td> </tr> </table> </form> '; } else { ?> <form method="post" action="<?php $_PHP_SELF ?>"> <table width="400" border="0" cellspacing="1" cellpadding="2"> <tr> <td width="100">Select Employee to Edit</td> <td></td> </tr> <tr> <td width="100"> <select name="EmpID" id="EmpID"> <option value='EmpID' disabled='disabled' selected='selected'>Please select a name</option> <? mysql_select_db('Labor'); $result = mysql_query('SELECT EmpID, FirstName, LastName, Pay FROM Employees'); while ($row = mysql_fetch_array($result)) { echo '<option value="'.$row{"EmpID"}.'">'.$row{"FirstName"}.' '.$row{"LastName"}.'</option>'; } ?> </select> </td> <td> </td> </tr> <tr> <td width="100"> </td> <td> <input name="select" type="submit" id="select" value="Select"> </td> </tr> </table> </form> <?php } } ?> <br> <a href="index.php">Home</a> </body> </html> Hello folks, well what I mean by temporary variables are variables like error messages or success messages that appear after a form has been submitted. I want to be able to kill these variables when the page is refreshed and return the page to its defualt state. For example, I'm making this simple page which is basically a form that ask users for some information, then upon submit, stores the in a database and prints a success message. If the form is filled out incorrectly or some form fields are left blank, then error messages are printed. What I really want is for these messages to disappear when the page is refreshed. My current model uses a second page to handle the form, and then upon succes or upon encountering an error, redirects to the form page, passing the error or success variables via the url to the form page where they are printed out. What can I do differently to achieve what I want (ie kill variables upon page refresh)? Below are the form page, and the page that handles the form respectively. Code: [Select] <form method="post" action="send_email.php"> <div id="contact_form"> <div align="left" class="green18">Contact Us</div> <br/> <br/> <label>Your Name:</label> <input class="texta" name ="name" size="20" maxlength="49"/> <br/> <br/> <div class ="error" style="position:relative;bottom:40px;left:128px" > <?php //Retrieve the encoded errors string from send_email.php page $errors_string=$_GET['errors_string']; //Explode the decoded errors string back to an array. $errors = explode(",", $errors_string); echo $errors[0];?> </div> <label>Your Company Name:</label> <input class="texta" name ="company" size="30" maxlength="66"/> <br/> <br/> <div class ="error" style="position:relative;bottom:40px;left:128px" > <?php //Retrieve the encoded errors string from send_email.php page $errors_string=$_GET['errors_string']; //Explode the decoded errors string back to an array. $errors = explode(",", $errors_string); echo $errors[1];?> </div> <label>Subject(Optional):</label> <input class="texta" name ="subject" size="20" maxlength="49"/> <br/> <br/> <label>Email:</label> <input class="texta" name ="email" size="20" maxlength="49"/> <br/> <br/> <div class ="error" style="position:relative;bottom:40px;left:128px" > <?php //Retrieve the encoded errors string from send_email.php page $errors_string=$_GET['errors_string']; //Explode the decoded errors string back to an array. $errors = explode(",", $errors_string); echo $errors[2];?> </div> <label>Message:</label> <textarea style="float:left" class="" name ="message" cols="40" rows="3"> </textarea> <br/> <br/> <div class ="error" style="position:relative;bottom:-19px;left:-260px" > <?php //Retrieve the encoded errors string from send_email.php page $errors_string=$_GET['errors_string']; //Explode the decoded errors string back to an array. $errors = explode(",", $errors_string); echo $errors[3];?> </div> <button class="button" type ="submit" name ="submit">Submit</button> <br/> <div id ="sent" > <?php //Retrieve the user id from send_email.php page $sent=$_GET['sent']; $send_msg = urldecode($sent); echo $send_msg; ?> </div> <!--closes sent--> </div> </form> Code: [Select] <?php //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); if (isset($_POST['submit'])) { $errors = array(); // Connect to the database. require('config/config.php'); //Check for errors. //Check to make sure they entered their name and it's of the right format. if (eregi ("^([[:alpha:]]|-|')+$", $_POST['name'])) { $a = TRUE; } else { $a = FALSE; $errors[0] = '*Please enter a valid name.'; } //Check to make sure they entered their company name. if (!empty ( $_POST['company'])) { $b = TRUE; } else { $b = FALSE; $errors[1] = '*Please enter company name.'; } //Check to make sure email is valid. if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST['email'])) { $c = TRUE; }else { $c = FALSE; $errors[2] = '*Please enter a valid email address.'; } //Check to make sure they entered their message. if (!empty ( $_POST['message'])) { $d = TRUE; } else { $d = FALSE; $errors[3] = '*Please enter your message.'; } //If no errors if (empty($errors)) { //Create variables for all the post values. $name = $_POST['name']; $company = $_POST['company']; $email = $_POST['email']; $message = $_POST['message']; $ip = $_SERVER[REMOTE_ADDR]; $date = (date("Y/m/d:G:i:s")); $timestamp = ( mktime(date(H), date(i), date(s), date(m) , date(d) , date(Y))); //Formulate the insert query. $query = "INSERT INTO emails ( email_id, name, company, email, message, ip, date,timestamp) VALUES ( 0, '$name','$company','email', '$message', '$ip' , '$date', '$timestamp' )"; $result = mysql_query($query) or die("Data could not be inserted into table because: " .mysql_error()); if (mysql_affected_rows() == 1) { // Display success message $sent_msg = "Your email has been sent. We will get back to you shortly."; $sent = urlencode($sent_msg); // Display contact page header("Location: contact_page.php?sent=$sent"); exit(); }else{die("There was a problem: " . mysql_error());} //Display error messages. } else {// if errors array is not empty //Confer the errors array into a string $errors_string = implode(",", $errors); //Encode the imploded string. $error_message = urlencode($errors_string); // Display page header("Location: contact_page.php?errors_string=$errors_string"); exit(); }//End of if there are errors. }//End of if submit. ?> Also, another problem I just noticed is that, the errors[3] variable isn't getting passed back to the form page. I don't know if it's because the url can only pass so much info to a second page. The page in question can be located he http://creativewizz.com/contact_page.php .= I am wondering why sometime it is require to add a dot before the equal in php? I'm trying to set up my home page so that when the server loads index.php it that loads home.php but all the information for home.php is stored in the database under ID 13. So how can I say at the top of my home page that if if (!isset($_GET['id'])) { $id == 13; } (this doesn't seem to work) so that all my variables are populated with the information for the home page? Thanks. hey gys im trying to build a permissions system based on the users group. Groups can be 1, 2, or 3. Here is the code im using: <?php mysql_connect("localhost", "root", "") or die(mysql_error()); mysql_select_db("chat") or die(mysql_error()); $result = mysql_query("SELECT * FROM `members` WHERE username='".$_SESSION['username']."'") or die(mysql_error()); if($result["group"]==1){ echo 'yes'; } else { echo 'no'; } ?> And here is how my db looks like: The thing is, when Im logged in with the user test and run that script, its saying no as the group im in isnt 1. Why is this happening? Can someone help me fix my code. I introduce if condition when a string is empty as Code: [Select] if (empty($string)) { How I can add the condition for a certain value too. If empty or equal to "word1". Hi: I am working with a little bit of code, but not certain if my syntax is correct. Doesn't seem to be doing what I need it to do: Code: [Select] <?php if (date <= "4/8/2011") echo "Event Details"; else echo "Default Text"; ?> Basically, I want to show "Event Details" if the date is before or on 4/8/2011. If it is after 4/8/2011, I want to show "Default Text" It seems to be doing the opposite. What am I missing? how do i make a leaderboard that is capable of handling equal scores from a particular result? we use following points allocations: winner: 5pts second: 3pts third: 2pts fourth: 1pt however, if 2nd and 3rd have tied scores, i would like to combine their point allocations together and divide by 2, i.e. (3+2)/2=2.5points each. initial query for competition ranking: $q_lastcomp = "SELECT p.p_id, p.p_surname, p.p_forename, p.p_handicap, r.r_id, rp.rp_score, rp.rp_handicap, (rp.rp_score-rp.rp_handicap) as net_score "; $q_lastcomp .= "FROM dan_roundplayed rp, dan_round r, dan_player p "; $q_lastcomp .= "WHERE r.r_id = rp.rp_rid "; $q_lastcomp .= "AND p.p_id = rp.rp_pid "; $q_lastcomp .= "AND r.r_id = 6 "; $q_lastcomp .= "ORDER BY net_score"; $r_lastcomp = mysql_query($q_lastcomp) or die(mysql_error()); i then loop through this resultset in this order (top down), and do some more calculations to adjust the players golf handicaps based on these results too. basically, if there are 4 players, the winner has beaten 3 others, second has beaten 2 others, down to last place who has beaten no-one. the number of players you have beaten is multiplied by 10% of their handicap (not precisely this value, but something like it and makes easier to explain), then this adjustment is subtracted from the handicap to make a new handicap for the next comp. this works fine, so long as no-one is tied. but if 2nd and 3rd tie, then both players have effectively only beaten 1 other player (last placed). so i would want both to do "hcap - (1*(hcap*0.1))" for their handicap adjustment calculations. in my current code, even though they were tied, 2nd would have: "hcap - (2*(hcap*0.1))" 3rd would have: "hcap - (1*(hcap*0.1))" my current loop code is: $total_players = mysql_num_rows($r_lastcomp); $i = 1; while($row = mysql_fetch_array($r_lastcomp)){ echo "<br>"; $round_hcap = round($row[p_handicap]); SWITCH ($round_hcap){ CASE $round_hcap >= 0 AND $round_hcap <= 19: $multiplier = 0.1; break; CASE $round_hcap >= 20 AND $round_hcap <= 29: $multiplier = 0.2; break; CASE $round_hcap >= 30 AND $round_hcap <= 39: $multiplier = 0.3; break; CASE $round_hcap >= 40 AND $round_hcap <= 49: $multiplier = 0.4; break; } $hcap_reduce = ($total_players-$i)*$multiplier; $new_hcap = $row[p_handicap]-(($total_players-$i)*$multiplier); $sqlstr = "INSERT INTO dan_handicap VALUES (". $row[p_id]. ",". $row[r_id]. ",". $row[p_handicap]. ",". $i. ","; $sqlstr .= $total_players. ",". $hcap_reduce. ",". $new_hcap. ");"; $sqlstr2 = "UPDATE dan_player SET p_handicap = ". $new_hcap. " WHERE p_id = ". $row[p_id]. ";"; echo $sqlstr. "<br>"; echo $sqlstr2. "<br>"; $i++; } can anyone help with this please? my initial thoughts are i am going to need a drastic adjustment to the initial query add in position number in the comp, i.e. this would produce posn | name | score 1 | winner | 10 2 | tied 2nd | 8 2 | tied 2nd | 8 4 | last place | 5 the second section of code could then use this "position number" for the multiplier part of the calculations. apologies for the length of the post, but this covers the whole requirements. regards jingo_man Hi, i am trying to write a part of script for google shopping export, and all i want is that in this line, everything that is 0 or smaller, the line "pre-order" krijgt and everything that is 1 or greater the line "in stock" This is what i've got now, but it doesn't work I removed the rest of the long code. Code: [Select] $patterns = array(); $patterns[0] = '=<0'; $patterns[1] = '=>1'; $replacements = array(); $replacements[0] = 'vooraf bestellen'; $replacements[1] = 'op voorraad'; if(OPTIONS_TONEN_FEED_AVAILABILITY == 1) $output .= "~" . preg_replace($patterns, $replacements, $row->quantity); I have put together a new website and I am having a problem that is frustrating me to no end so I am here looking for expert help.
In my "content" column, I am trying to have the article I have written. This content is going to change from page to page depending on the amount of content. At the bottom of the "content" I am trying to add a comments section.
To the right of the "content" column I have a "sidebar" and the problem I am having is as the "content" column grows or shrinks, it is effecting the positioning of the "sidebar" and moves the content of the "sidebar" up or down.
I have tried to investigate how to correct this and what I have read makes absolutely no sense to me so the only way I can figure out to fix this (keeping in mind that I am in the process of teaching myself CSS and I use the trial and error method of learning) is to set the height of the "content" column to a fixed number and then force the "sidebar" to move up or down by using something like 'margin-top: -1200px". The problem with this is when comments are added, the content of the "sidebar" moves down.
My question is, does anyone know of a way to get both columns to adjust to equal heights that won't cause me to pull what little hair I have left out? Would that anyone be willing to explain to me why your method should work?
I know that I should include the code for the page I am having the problem with, but it is (in my opinion) pretty extensive and if someone is willing to try to tackle this it might be easier to just bring up the source code.
Just FYI . . . the page in question can be seen at http://pickmysmoker....ne_smokers.php/
Thanks in advance . . .
Hi guys, Probably going to be a very basic question but i'm lost, i'm trying to figure out how to display an image if the value returned is equal to or greater than a certain number, more of a hypothetical question at the moment, Thanks in advance Code: [Select] function choose_numbers($number,$max) { global $ibforums,$std; srand( (double)microtime() * 1000000 ); $array = array(); $i = 0; while($i!=$number) { $array[] = mt_rand(1,$max); $i++; } $c = count($array); while($c != $number) { $array[] = mt_rand(1,$max); $c = count($array); if($c == $number) { $array = array_unique($array); $c = count($array); } } return $array; } $newnumbers = $this->choose_numbers(3,36); echo "{$newnumbers['0']}|{$newnumbers['1']}|{$newnumbers['2']}"; This echo's out my lottery balls 0|32|22 or technically RANDNuMbER|RANDNUMBER|RANDNUMBER up to 36 is the highest number. Now my issue is, I don't want 2 numbers of the same Value, EVER. Sometimes it does 2|3|2 which is BAD (for my lottery system) is there anyway I can make it so it never will echo out 2 (OR 3) of the same number? Hi Guys what I need to do is display data from two different tables that equal the same value in a specific field Table one has ID Title Course content table two has ID Title Start date End date I need a query that says if title from table one matches title from table 2 then will display the start and end date from table two sorry if this is really simple I am a newbie thanks inadvance I'm trying to achieve that my script checks in the database if the user has submitted the data twice. The script takes the user submission and checks it with the column in the database with != and == But it ALWAYS sees it as UNEQUAL even if the data is EQUAL. Here's the script <?php $con_submit = $_POST['submit']; $user_id = $_SESSION['user_id']; if ($con_submit && isset($user_id)){ // Connect to the database $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); // Grab the score data from the POST $knuffix_name = strip_tags(trim($_POST['knuffix_name'])); $knuffix_contribution = $_POST['knuffix_contribution']; $knuffix_category = strip_tags(trim($_POST['sort_category'])); $query = "SELECT contribution FROM con WHERE user_id = '$user_id'"; $query_run = mysqli_query ($dbc, $query) or die (mysqli_error ($dbc)); $assoc = mysqli_fetch_assoc ($query_run) or die (mysqli_error ($dbc)); $db_user_con = $assoc['contribution']; $num_rows = mysqli_num_rows ($query_run) or die (mysqli_erro ($dbc)); if ($knuffix_contribution != $db_user_con) { $query = "SELECT contribution FROM con"; $query_run = mysqli_query ($dbc, $query); $assoc = mysqli_fetch_assoc ($query_run); $db_con = $assoc['contribution']; if ($knuffix_contribution != $db_con) { if (!empty($knuffix_name) && !empty($knuffix_category) && !empty($knuffix_contribution)) { // Write the data into the database $query = sprintf("INSERT INTO con (user_id, name, contribution, category, contributed_date) VALUES ('$user_id', '%s', '%s', '%s', now())", mysqli_real_escape_string($dbc, $knuffix_name), mysqli_real_escape_string($dbc, $knuffix_contribution), mysqli_real_escape_string($dbc, $knuffix_category)); mysqli_query($dbc, $query) or die (mysqli_error($dbc)); mysqli_close($dbc); } else { echo "<p class='error'>Please enter all of the information to add your contribution.</p>"; } } else { echo "You have to be signed-in to do a contribution."; } } else { echo "This contribution already exists in the database. To keep this place clean we do not allow duplicate submissions."; } } else { echo "You cannot make the same submission twice."; } ?> Where is the problem? I'm surely doing something wrong here, but I just cannot see it. Any assistance will be greatly appreciated. In a login script I read the following two variables from an SQL database. Both fields are defined as int. $this->ScheduleA = $rs->fetchCol('ScheduleA'); $this->SchedConst = $rs->fetchCol('SchedConstant'); Later, I retrieve these variables and attempt to compare them. $schA = $sess['ScheduleA']; $schC = $sess['SchedConst']; if ($schA == $schC) { require('Testing.php'); } else { require('NotAllowed.php'); } They never compare as equal, even though they contain the same value. What, pray tell, am I missing? Hi, I am a newbie in PHP (about week and a half). I'm writing a website for myself right now. I've got a problem that I cannot solve. The website is about buying files with website custom balance. What I want to do is disable buy button if user bought this file b4. The is a table user_files that stores user id and file id. And another table that stores files data, ID name who uploaded date time ect.... What I'm trying to do, is disabling buy button if the user has already the file. This is what I've done : while ($row = $rocket->fetch()) { ?> <tr> <td><?php echo $row['id']; ?></td> <td><?php echo $row['name']; ?></td> <td><?php echo $row['uploader']; ?></td> <td><?php echo $row['uploadtime']; ?></td> <td><button <?php // Echo "disabled" if $row['id'] id is present in row2['file_id'] <<<<<<< Need to do this in a while. ?> ><a href="download.php?id=<?php echo $row['id']; ?>"></a><?php echo $row['price'] . "D$" ?></button></td> </tr> <?php } ?> What I can't do is check if the file id ($row['id']) is present in ($row2['file_id']), if yes echo "disabled";
Hello,
I am trying to check whether the values in rows are equal or same?
I have two tables orders and line_items. I will store more than 1 line items in line_items table with the same order_id getting from orders table. In line items if i have 3 line items for same order_id, when each line items gets dispatched i will set the status to 'Dispatched' in line_items table. When all the 3 becomes 'Dispatched', i will update the order status as 'Completed' in orders table.
Now i am not getting how to check whether all the 3 line items status id 'Dispatched'.
I tried doing like this
$q1 = "select orders.order_id, orders.item_status as istatus, orders.status as ostatus, orders.authorise, line_items.order_id, line_items.status as bstatus, COUNT(line_items.id) as bid from orders inner join line_items on orders.order_id=line_items.order_id where line_items.order_id=".$id." AND line_items.id<>'Dispatched'"; $q2 = mysql_query($q1); while($q3 = mysql_fetch_array($q2)) { echo $q3['bstatus']; if($q3['bstatus']==''); { echo "HELLLOOOO"; } }But its not working. It goes into if loop even if a single value is 'Dispatched' Please help me. Here's what I'm wanting to do: Number = 100 In a for loop take that number, 100, and break it down into 5 random numbers to equal 100. So the for loop would output something like this: 1. 32 2. 5 3. 18 4. 9 5. 36 Total = 100 Everytime the numbers would be different. I hope that explains it Thanks! |