PHP - Determining Day Of Week Then Subtract 1 Day
I have a PHP script that downloads a file from a remote server but in order to download the correct file it has to subtract 1 day of the week. It used to work quite some time ago so I dont know what is going on now. The section of the script goes like this....
$days = array("sun","mon","tue","wed","thu","fri","sat"); $today = date("w"); $yesterday = $days[$today - 1];Then it joins the 3 letter version of the day of week with a file name to grab the correct file download. $yesterday is not returning the correct value instead I am getting an error... # ./update.php PHP Notice: Undefined offset: -1 in /root/fcc/work/update.php on line 6 fetching l_am_.zip ncftpget: server said: l_am_.zip: No such file or directory. PHP Warning: unlink(counts): No such file or directory in /root/fcc/work/update.php on line 23 data set empty nothing to process Sun, 01 February, 2015 6:29:06 PMSo in the above error I can see that $yesterday is "Undefined offset" and because of that the file it tries to download is incorrect, it should have tried to download l_am_sat.zip and it left out the 3 letter date code. Edited by chadrt, 01 February 2015 - 09:48 PM. Similar TutorialsHere is the scenario: Members of my group turn in/donate uniform items they don't need to me...stuff that can be passed on to other members that need it. I post these items onto our website. A member, who needs an item, visits the site, and picks the items that they need. After selecting everything they need, they provide only their name and maybe some comments, and submit the request. An e-mail is generated and sent to me, listing out all the items the member has requested. I gather the items, and bring them to the member at the next meeting. My original plans were to use a shopping cart type script; however, I have since found out that I am not allowed a MySQL database on the server I am using! I've seen some shopping carts out there that use php & excel, not requiring a database, but they are all trial, and have limitations of only like 10 items. Does anyone have any ideas on the best way to handle this scenario? I was thinking an html form of some type with check boxes next to each item; then, upon pressing submit, a php script sends me an e-mail listing the boxes they have checked. Only problem with that is, having to update the php script each time I add/delete an item and it's checkbox (would have to add/delete that checkbox's name to the script each time...correct?). Thanks for any suggestions, - Jason With this code I can determine the fieldname and the value. They are $col_key and $col_value respectively: Code: [Select] $sql = "SELECT * FROM $tbl "; $result = mysql_query($sql) while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { if ($row == 1) { foreach ($line as $col_key => $col_value) { But how do I determine the field TYPE (i.e. varchar, text, date etc)? Hi Guys Quick question. I am just starting an application that enables users to upload files - specifically image files. As one of the validation/security steps I want to run a check on file type and file size. As far as i can see you do this one of two ways: 1) using the $_FILES array - i.e. $_FILES[name][type] and $_FILES[name][size] or 2) using the getimagesize() function. What i want to know is whether one of these methods is preferable for security or do they both suffer the same inherent flaws - because lots of post online seem to suggest filetype can be faked. advice would be appreciated Hey, I have a search feature that searches for words in my database. I am currently storing all searches that users make in a table called `search`. I need to list the top 10 words that are searched for the most, excluding common words like "the, and, or, etc". Because the searches users make are stored into a table, it should be fairly easy. Could anyone give an example of how to do this? Here's how my sql table looks: table name: search columns: id (autoincrement) phrase date resultsfound ip Could someone please advise the best way to determine the average of a DATE field in a SELECT query?
Hi, I found a tutorial online for a form which used PHP/MySQL and JQuery to submit data. I am making some modifications and the form no-longer submits the data. The problem I have is no errors display so I am not sure where the problem lies. I need to be able to display a success or failure message on the form itself, but this is either not there or not working. The code is below. Code: [Select] <form id="ContactForm" action=""> <p> <label>First Name</label> <input id="FirstName" name="FirstName" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span> </p> <p> <label>Last Name</label> <input id="LastName" name="LastName" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span> </p> <p> <label>User Name</label> <input id="UserName" name="UserName" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span> </p> <p> <label>Email</label> <input id="email" name="email" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span> </p> <p> <label>Website<span>(optional)</span></label> <input id="website" name="website" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> </p> <p> <label>Your message<br /> <span>300 characters allowed</span></label> <textarea id="message" name="message" class="inplaceError" cols="6" rows="5" autocomplete="off"></textarea> <span class="error" style="display:none;"></span> </p> <p class="submit"> <input id="send" type="button" value="Submit"/> <span id="loader" class="loader" style="display:none;"></span> <span id="success_message" class="success"></span> </p> <input id="newcontact" name="newcontact" type="hidden" value="1"></input> </form> <?php require_once("config.php"); /* Configuration File */ class DB{ private $link; public function __construct(){ $this->link = mysqli_connect(DB_SERVER, DB_USER, DB_PASS,DB_NAME); if (mysqli_connect_errno()) exit(); } public function __destruct() { mysqli_close($this->link); } public function dbNewMessage($email,$FirstName,$LastName,$website,$message){ $email = mysqli_real_escape_string($this->link,$email); $FirstName = mysqli_real_escape_string($this->link,$FirstName); $LastName = mysqli_real_escape_string($this->link,$LastName); $UserName = mysqli_real_escape_string($this->link,$UserName); $website = mysqli_real_escape_string($this->link,$website); $message = mysqli_real_escape_string($this->link,$message); mysqli_autocommit($this->link,FALSE); $query = "INSERT INTO contact_me(pk_contact,FirstName,LastName,UserName,email,website,message) VALUES('NULL','$FirstName','$LastName','$UserName','$email','$website','$message')"; mysqli_query($this->link,$query); if(mysqli_errno($this->link)) return -1; else{ mysqli_commit($this->link); return 1; } } }; ?> <?php require_once("db.php"); /* Database Class */ require_once('utils/is_email.php'); /* Email Validation Script */ /* Handle Ajax Request */ if(isset($_POST['newcontact'])){ $contact = new Contact(); unset($contact); } else{ header('Location: /'); } /* Class Contact */ class Contact{ private $db; /* the database obj */ private $errors = array(); /* holds error messages */ private $num_errors; /* number of errors in submitted form */ public function __construct(){ $this->db = new DB(); if(isset($_POST['newcontact'])) $this->processNewMessage(); else header("Location: /"); } public function processNewMessage(){ $email = $_POST['email']; $FirstName = $_POST['FirstName']; $LastName = $_POST['LastName']; $UserName = $_POST['UserName']; $website = $_POST['website']; $message = $_POST['message']; /* Server Side Data Validation */ /* Email Validation */ if(!$email || mb_strlen($email = trim($email)) == 0) $this->setError('email','required field'); else{ if(!is_email($email)) $this->setError('email', 'invalid email'); else if(mb_strlen($email) > 120) $this->setError('email', 'too long! 120'); } /* FirstName Validation */ if(!$FirstName || mb_strlen($FirstName = trim($FirstName)) == 0) $this->setError('FirstName', 'required field'); else if(mb_strlen(trim($FirstName)) > 120) $this->setError('FirstName', 'too long! 120 characters'); /* LastName Validation */ if(!$LastName || mb_strlen($LastName = trim($LastName)) == 0) $this->setError('LastName', 'required field'); else if(mb_strlen(trim($LastName)) > 120) $this->setError('LastName', 'too long! 120 characters'); /* UserName Validation */ if(!$UserName || mb_strlen($UserName = trim($UserName)) == 0) $this->setError('UserName', 'required field'); else if(mb_strlen(trim($UserName)) > 120) $this->setError('UserName', 'too long! 120 characters'); /* Website Validation */ if(!mb_eregi("^[a-zA-Z0-9-#_.+!*'(),/&:;=?@]*$", $website)) $this->setError('website', 'invalid website'); elseif(mb_strlen(trim($website)) > 120) $this->setError('website', 'too long! 120 characters'); /* Message Validation */ $message = trim($message); if(!$message || mb_strlen($message = trim($message)) == 0) $this->setError('message','required field'); elseif(mb_strlen($message) > 300) $this->setError('message', 'too long! 300 characters'); /* Errors exist */ if($this->countErrors() > 0){ $json = array( 'result' => -1, 'errors' => array( array('name' => 'email' ,'value' => $this->error_value('email')), array('name' => 'FirstName' ,'value' => $this->error_value('FirstName')), array('name' => 'LastName' ,'value' => $this->error_value('LastName')), array('name' => 'UserName' ,'value' => $this->error_value('UserName')), array('name' => 'website' ,'value' => $this->error_value('website')), array('name' => 'message' ,'value' => $this->error_value('message')) ) ); $encoded = json_encode($json); echo $encoded; unset($encoded); } /* No errors, insert in db*/ else{ if(($ret = $this->db->dbNewMessage($email, $FirstName, $LastName,$UserName, $website, $message)) > 0){ $json = array('result' => 1); if(SEND_EMAIL) $this->sendEmail($email,$name,$website,$message); } else $json = array('result' => -2); /* something went wrong in database insertion */ $encoded = json_encode($json); echo $encoded; unset($encoded); } } public function sendEmail($email,$name,$website,$message){ /* Just format the email text the way you want ... */ $message_body = "Hi, ".$name."(".$email." - ".$website.") sent you a message from yoursite.com\n" ."email: ".$email."\n" ."message: "."\n" .$message; $headers = "From: ".EMAIL_FROM_NAME." <".EMAIL_FROM_ADDR.">"; return mail(EMAIL_TO,MESSAGE_SUBJECT,$message_body,$headers); } public function setError($field, $errmsg){ $this->errors[$field] = $errmsg; $this->num_errors = count($this->errors); } public function error_value($field){ if(array_key_exists($field,$this->errors)) return $this->errors[$field]; else return ''; } public function countErrors(){ return $this->num_errors; } }; ?> and the JQuery Code: [Select] $(document).ready(function() { contact.initEventHandlers(); }); var contact = { initEventHandlers : function() { /* clicking the submit form */ $('#send').bind('click',function(event){ $('#loader').show(); setTimeout('contact.ContactFormSubmit()',500); }); /* remove messages when user wants to correct (focus on the input) */ $('.inplaceError',$('#ContactForm')).bind('focus',function(){ var $this = $(this); var $error_elem = $this.next(); if($error_elem.length) $error_elem.fadeOut(function(){$(this).empty()}); $('#success_message').empty(); }); /* user presses enter - submits form */ $('#ContactForm input,#ContactForm textarea').keypress(function (e) { if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) { $("#send").click(); return false; } else return true; }); }, ContactFormSubmit : function() { $.ajax({ type : 'POST', url : 'php/contact.php?ts='+new Date().getTime(), dataType : 'json', data : $('#ContactForm').serialize(), success : function(data,textStatus){ //hide the ajax loader $('#loader').hide(); if(data.result == '1'){ //show success message $('#success_message').empty().html('Message sent'); //reset all form fields $('#ContactForm')[0].reset(); //envelope animation $('#envelope').stop().show().animate({'marginTop':'-175px','marginLeft':'-246px','width':'492px','height':'350px','opacity':'0'},function(){ $(this).css({'width':'246px','height':'175px','margin-left':'-123px','margin-top':'-88px','opacity':'1','display':'none'}); }); } else if(data.result == '-1'){ for(var i=0; i < data.errors.length; ++i ){ if(data.errors[i].value!='') $("#"+data.errors[i].name).next().html('<span>'+data.errors[i].value+'</span>').fadeIn(); } } }, error : function(data,textStatus){} }); } }; I'm using a time stamp where I'm getting the date and time from the database server rather than using a unix time stamp. Because I'm in a different time zone as the server, my time was always off by 1 hour. I fixed that problem by writing some code to adjust the hour of the time and the date depending on what time it was. It was working fine until a few weeks ago when I had to adjust my clock for daylight savings time... now the time is off by 2 hours because of that. Well, I fixed that and now it's working fine again. My question is does anyone know of a way to automatically determine whether or not I should be in daylight savings time or not so I can just use an if/else statement to keep the time adjusted properly rather than having to do it manually every time the time changes? Basically, I would like to do it something like the following: Code: [Select] <?php if ($daylightsavings = "y") { (adjust time/date for 1 hour difference); } else { (adjust time/date for 2 hour difference); } ?> Anyone have any ideas? When a user logs on, I authenticate them with a session. How do I use php to determine the time until the session will expire? I realize I could go into the ini file but is there a php code that can query this info and echo it back? I am trying to write a script that runs through a CSV file and inserts unique values in a mysql database and spits the duplicate out into a new CSV. I can find the duplicates when I load it into an array, but when I insert them into a MySQL database, I cannot determine if they are duplicates. If I use INSERT IGNORE, it will run the whole file, and reject the duplicates. This is fine, except I need to create a file of the duplicate entries. What is the best way to determine if the insert attempt was rejected? I could do a select to see if the row is there, spit it out...insert if not, but I was thinking there should be a way for MySQL to talk back to me to cut the queries in half... Any ideas? Thanks Say I already have the two example arrays below ($arrayA and $arrayB). What is the proper way to cycle through these arrays to ultimately create a single array ($arrayC) that only has the items that are in Array B but are NOT in Array A? Basically subtracting the first array from the second array... Array A: 1-dog 2-cat 4-fish 7-monkey 9-bird Array B: 1-dog 2-cat 3-elephant 4-fish 5-whale 6-dolphin 7-monkey 8-aardvark 9-bird 10-stingray So again, I want the end result to be this array... Array C: 3-elephant 5-whale 6-dolphin 8-aardvark 10-stingray Can anyone help? Ok, i have setup a page to add points to a member using 2 tables as i have said in one of my older posts, now i am wanting to subtract an entered amount of points... removepoints.php Code: [Select] <body> <form method="post" name="memberadd" action="points_remove_complete.php"> <label>Name:</label> <select name="memberid"> <?php $con = mysql_connect("localhost","slay2day_User","slay2day"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("slay2day_database",$con); $sqlquery="SELECT * FROM `members` Order By name"; $result=mysql_query($sqlquery,$con); while($row=mysql_fetch_array($result)) { echo "<option value='".$row['id']."'>".$row['name']."</option>"; } ?> </select> <br> <label>Points:</label> <input type="text" name="points" id="points" size="5"><br> <input type="submit" value="submit" /> </form> </body> points_remove_complete.php: Code: [Select] <?php $id=$_POST['memberid']; $points=$_POST['points']; $con = mysql_connect("localhost","slay2day_User","slay2day"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("slay2day_database",$con); $sql="INSERT INTO slay2day_database.`points` VALUES (NULL,'$memberid','$points')"; if(mysql_query($sql,$con)) { echo 'Points removed.<br /><a href="../index.php">Return To Points List</a><br /><a href="removepoints.php">Remove More Points!</a>'; } else { die('Could not submit: ' . mysql_error()); } mysql_close($con); ?> Hello I have 2 datetimes...both are inside a database. The datetimes are not unix time they are regular date\times. So for instance...in the database I have a field called Login_time which is 2012-01-30 02:43:13 I am taking the current time in the same format with the following code Code: [Select] $curDate = date("Y-m-d H:i:s", time()); The problem is that I can't figure out how to tell the exact minutes for the 2 date\time intervals. Code: [Select] //find out if the ip address is inside the database $doesIpExsist = mysql_query("Select * from login_information where IP_Address like '$ip'", $link); $num_rows = mysql_num_rows($doesIpExsist); echo "$num_rows Rows\n"; if ($num_rows == 0) { //create the field inside the database $ip_query = "INSERT INTO login_information (IP_address, `Login_attempts`, Login_time, Total_login_attempts) VALUES ('$ip', '1', NOW(), '1')"; $ip_result = mysql_query($ip_query, $link) or die (mysql_error()); } else //the fields alaready exsist { $curDate = date("Y-m-d H:i:s", time()); echo $curDate; include ('timefunction.php'); echo "<br>"; echo "IP ".$ip; echo "<br>"; $select_ip_id = "SELECT ID from login_information where IP_address like '127.0.0.1'"; //$select_ip_id = "SELECT ID from login_information where IP_address like '$ip'"; echo $select_ip_id; $ip_error = mysql_query($select_ip_id, $link) or die (mysql_error()); foreach ($row = mysql_fetch_array($ip_error, MYSQL_ASSOC) as $key => $value) { echo dateDiff('$curDate', '$get_ip_error') . "<br>"; echo dateDiff('$get_ip_error', '$curDate') . "<br>"; echo "HIoROW " . $value. "<br>"; } $get_ip_time = "Select Login_time from login_information where IP_address like '$ip'"; $get_ip_error = mysql_query($get_ip_time, $link) or die (mysql_error()); //echo $get_ip_error; /*while ($row = mysql_fetch_array($get_ip_error, MYSQL_ASSOC)) //while($row=mysql_fetch_array($get_ip_error)) { echo $row; } */ echo "HI"; echo $curDate; echo "<br>"; echo $get_ip_error; echo "<br>"; echo dateDiff('$curDate', '$get_ip_error') . "<br>"; echo dateDiff('$get_ip_error', '$curDate') . "<br>"; echo "<br>"; //$datetime1 = date_create($curDate); //$datetime2 = date_create($get_ip_error); //$interval = date_diff($datetime1, $datetime2); //echo $interval->format('%R%a days'); //$dt1 = new DateTime($get_ip_error); //$dt2 = new DateTime($curDate); //$dtdiff = $dt1->diff($dt2); //print $dtdiff->format('%h hours, %i minutes'); //echo "<br>"; //$timeDifference = time_diff ($get_p_error, $curDate); //echo $timeDifference; //$timeDifference = $get_ip_error - $curDate; //echo "<br>"; //echo $timeDifference; //mysql_query("UPDATE Persons SET Age = '36' WHERE FirstName = 'Peter' AND LastName = 'Griffin'"); //$ip_query = "UPDATE INTO login_information (IP_address, `Login_attempts`, Login_time, Total_login_attempts) VALUES ('$ip', '1', NOW(), '1')"; echo "So far so good"; } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Untitled Document</title> </head> <body> </body> </html> Currently it doesn't work to the minutes. Can you tell me what i am doing wrong on this issue. Gud Pm! Im trying to display a list of years (last year, current year and next year) with these simple code i made.. It displays the current and next year correctly except last year, which gives me "1970". I don't get why it gives me that since may next year works properly.. Code: [Select] $currentyear = date('Y'); $subtract_year = strtotime(date('Y', strtotime($currentyear)) . '-1 year'); $lastyear = date('Y', $subtract_year); $addyear = strtotime(date('Y', strtotime($currentyear)) . '+1 year'); $newyear = date('Y', $addyear); $year_array = array($lastyear, $currentyear, $newyear); foreach($year_array as $year) { echo "<option value='{$year}'>"; echo $year; echo "</option>"; } I'm not familiar with dates yet.. so i'm gonna read the manual while w8ting for your kind replies. I have the following code: Code: [Select] //DETERMINES ASL POLICY if ($perfRow['ASL']=='ToArrange'){ $ASLdate = $perfRow['startDateTime']; $ASLconfirm = strtotime($ASLdate-'21 days'); echo "<!--[ASL=ToARRANGE--><p>An ASL Interpreted performance of this event is offered on".date("l, F j",strtotime($perfRow['startDateTime']))." at ".date("g:i a",strtotime($perfRow['startDateTime'])).".<br />Please contact me by ".date("l, F j",strtotime($ASLconfirm))." to confirm this service.</p>"; }What I need is that if the ASL is "To be Arranged" there is a date that lists for $ASLconfirm that is three weeks prior to $ASLdate. The code above gives me the following: Quote An ASL Interpreted performance of this event is offered on Friday, September 28 at 7:30 pm. Please contact me by Wednesday, December 31 to confirm this service. As you can see from the output the December date is NOT three weeks prior to the September date. Where did I go wrong in my coding? Hello this may sound a little confusing.
I recently made a fake website using this phpacademy tutorial I found. Anyways it has an quantity stock what I mean by this is let's I have 3 copies of a video game an a person set they quantity for 2 of the 3 copies and proceed to the checkout through paypal payment successful okay. My question is: How can I go about sending the quantity stock back to the database to subtract 2 from 3 to be left with 1 copy of the game in the quantity section after a successful purchase? Code is below in case I confused someone ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////// Maximumize / calling the quantity from Database ///////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if(isset($_GET['add'])){ $quantity = mysqli_query($db_conx,'SELECT id, quantity FROM products WHERE id='.mysqli_real_escape_string($db_conx,(int)$_GET['add'])); while ($row = mysqli_fetch_assoc($quantity)){ if ($row['quantity']!=$_SESSION['cart_'.(int)$_GET['add']]) { $_SESSION['cart_'.(int)$_GET['add']]+='1'; } } header('Location: '.$page); } if(isset($_GET['remove'])){ $_SESSION['cart_'.(int)$_GET['remove']]--; header('Location:' .$page); } if(isset($_GET['delete'])){ $_SESSION['cart_'.(int)$_GET['delete']]='0'; header('Location:' .$page); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////// Calling all products from Database ///////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function products($db_conx){ $get = mysqli_query($db_conx,"SELECT id, name, description, price FROM products WHERE quantity > 0 ORDER BY id DESC"); if (mysqli_num_rows($get) ==0){ echo "There are no products to display"; } else { while ($row = mysqli_fetch_assoc ($get)){ echo '<p>'.$row ['name']. '<br/> <br/>' .$row ['description']. '<br/> <br/>' .'$'.number_format($row['price'], 2).' <a href="cart.php?add='.$row ['id'].'">Add</a></p>'; } } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////// Paypal Checkout ///////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function paypal_items($db_conx){ $num = 0; foreach($_SESSION as $name => $value){ if ($value != 0){ if(substr($name, 0, 5)=='cart_'){ $id = substr($name, 5, strlen($name) -5); $row = mysqli_query($db_conx,'SELECT id, name, price, shipping FROM products WHERE id ='.mysqli_real_escape_string($db_conx,(int)$id)); while ($query = mysqli_fetch_assoc($row)){ $num++; echo '<input type="hidden" name="item_number_'.$num.'" value="'.$id.'">'; echo '<input type="hidden" name="item_name_'.$num.'" value=" '.$query['name'].' ">'; echo '<input type="hidden" name="amount_'.$num.'" value=" '.$query['price'].' ">'; echo '<input type="hidden" name="shipping_'.$num.'" value=" '.$query['shipping'].' ">'; echo '<input type="hidden" name="quantity_'.$num.'" value=" '.$value.' ">'; } } } } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////// Shopping Cart View ///////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function cart($db_conx) { foreach($_SESSION as $name => $value) { if ($value > 0) { if(substr($name,0 ,5) . 'cart_'){ $id = substr($name, 5, (strlen($name) -5)); $row = mysqli_query($db_conx,'SELECT id, name, price FROM products WHERE id=' .mysqli_real_escape_string ($db_conx,(int)$id)); while ($query = mysqli_fetch_assoc($row)){ $sub = $query['price']*$value; echo $query['name'].' x ' .$value. ' @ $' .number_format ($query['price'], 2). ' = $'.number_format($sub, 2). '<a href="cart.php?remove='.$id.'">[-]</a> <a href="cart.php?add='.$id.'">[+]</a> <a href="cart.php?delete='.$id.'">[Delete]</a> <br/> <br/> '; } } $total += $sub + $shipping; } } if ($total ==0) { echo "Your cart is empty."; } else { echo 'Total: $' .number_format($total, 2); ?> <form action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_cart"> <input type="hidden" name="upload" value="1"> <input type="hidden" name="business" value="youremail@outlook.com"> <?php paypal_items($db_conx); ?> <input type="hidden" name="currency_code" value="USD"> <input type="hidden" name="amount" value="<?php echo $total ;?>"> <input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but03.gif" name="submit" alt="Make payments with PayPal - it's fast, free and secure!"> </form> <?php } } ?> Edited by mac_gyver, 09 September 2014 - 08:06 PM. code tags please Hi if i have $date = "12-08-2018" or "2018-08-12" Need to subtract a month. Could this be done for day and year even? TIA Desmond. P.S. What I want to do is clear out a database table with records over a month old so today is 27th Jan 2018. I would like to create a date “2018-12-01” I can then use this in an SQL to delete all before “2018-12-01” Edited January 27, 2019 by Paul-DHello, I am learning php in a class for school and I was hoping I could get some help with some code. I am trying to make a game life counter. I just want it to have simple +1, -1 and reset buttons. I have gotten it to add and subtract the first time, but it will not continue adding/subtracting. Thank you for any help you can give. Here is the code I'm having issues with: <?php session_start(); ?> <form method="post" action =""> <input type="submit" name="name" value="Add"/> <input type="submit" name="name" value="Minus"/> <input type="submit" name="name" value="Reset"/> </form> <? lifeTotal(); function lifeTotal() { $_SESSION['total']=20; if($_POST["name"] == 'Add') { $_SESSION['total']++; echo $_SESSION['total']; } else if($_POST["name"] =='Minus') { $_SESSION['total']--; echo $_SESSION['total']; } } ?> Hey, I have a minigame on my website and when you bet 1 It says you lost and you lose your point but it doesn't remove it, Same with if you win it says you gain the point but doesn't add it.... Code: [Select] function bet ($bet){ sleep(2); $user1 = mysql_query("SELECT * FROM `users` WHERE `id`='" . $_SESSION['id'] . "'"); $user = mysql_fetch_object($user1); $chance = rand (1, 2); $bet = round ($bet); $betPretty = number_format ($bet); if ($bet == 0) { $echo = "You did not bet anything!"; $chance = 0; } if ($bet < 0) { $echo = "You cannot bet a negative number."; $chance = 0; } if ($bet > $user->minigame_points) { $echo = "This is more minigame points than you have!"; $chance = 0; } if ($user->minigame_points == 0) { $echo = "You do not have any minigame points."; $chance = 0; } if ($chance == 1) { //Win $money = $user->minigame_points+$bet; $times_bet = $user->times_bet+1; mysql_query ("UPDATE `users` SET `minigame_points`='" . $money . "', `times_bet`='" . $new_bet . "' WHERE `username`='" . $user->username . "'"); $money = number_format($money); $echo = "You won $betPretty minigame points!<br /><b>Current Minigame Points:</b> $money"; } if ($chance == 2) { //Lose $money = $user->minigame_points-$bet; $times_bet = $user->times_bet+1; mysql_query ("UPDATE `users` SET `minigame_points`='" . $money . "', `times_bet`='" . $new_bet . "' WHERE `username`='" . $user->username . "'"); $money = number_format($money); $echo = "You lost $bet minigame points.<br /><b>Current Minigame Points:</b> $money"; } return $echo; Hello, I am trying to subtract the current time from a list of times in a mysql database. The first page inserts the time into mysql.
<?php $var_Time = date("h:i:s"); $mysqli = new mysqli('localhost','root','blah','test'); if ($mysqli->connect_error) { die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error); } $insert_row = $mysqli->query("REPLACE INTO test_table (id, time) Values(NULL, '$var_Time')"); if($insert_row){ while (false); }else{ die('Error : ('. $mysqli->errno .') '. $mysqli->error); } $mysqli->close(); ?>The second page is supposed to iterate through all of the times in the database and subtract the current time, but i cant figure out how to do it. <?php $mysqli = new mysqli('localhost','root','blah','test'); if ($mysqli->connect_error) { die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error); } $query = "SELECT * FROM `test_table`"; $result = $mysqli->query($query) or die($mysqli->error.__LINE__); $var_set_time = stripslashes($row['time']); $var_current_time = date("h:i:s"); $diff = strtotime( $var_current_time .' UTC' ) - strtotime( $var_set_time .' UTC'); echo $diff; ?> Edited by Ch0cu3r, 09 October 2014 - 01:40 PM. Added code tags Code: [Select] $startdt = $_POST['startdt'].":".$_POST['starttmh'].":".$_POST['starttmm'].":".$_POST['sAMPM']; // 09/08/2011:11:35:AM $enddt = $_POST['enddt'].":".$_POST['endtmh'].":".$_POST['endtmm'].":".$_POST['eAMPM']; //09/09/2011:11:35:AM From the code above I want to subtract 09/08/2011:11:35:AM from 09/09/2011:11:35:AM and get the total number of hours. A simple solution would be highly appreciated: thanks in advance: |