PHP - Simple Number Check Problem
Hi,
I'm totally new to PHP and I'm afraid I don't understand a lot yet. However, I need to make this: when you fill in a number in a form, it should be displayed whether the number is odd or even. I tried the following code, which is obviously not working and I have no idea on how to fix this. Code: [Select] <?php $var = $_POST['var']; for ($i = 0; $i < $var; $i++) { if ($i % 2 == 0) { print("even"); } else { print("odd"); } } ?> Similar TutorialsHello, I'm working on an error form, and I want to check if the user inserted a number into the name field, and if so return an error. I thought this might of worked, but it doesn't: Code: [Select] if(is_int($_POST['name'])){ $arrErrors['name'] = 'Invalid name, remove numbers.'; } Many thanks Hello, I'm currently creating a little script, and want to assign a random number to a row in the MySQL table as soon as it will be inserted. But that number may not have been used before. How will I do this? I tried if else thingies, but then the code would be very long (just in case it randomly picks 10 times after each other a number that exists). $randomnumber = rand(10000000, 99999999); if(mysql_num_rows(mysql_query("SELECT * FROM table WHERE randomnumber='".$randomnumber."')) == 1) { $randomnumber = rand(10000000, 99999999); if(mysql_num_rows(mysql_query("SELECT * FROM table WHERE randomnumber='".$randomnumber."')) == 1) { $randomnumber = rand(10000000, 99999999); }else { // Insert into database } }else { // Insert into database } I hope you understand my problem. Regards, Hi Guys just need some advice really I would like to know if there is a way I can check if a number is in a times table for example if(3 is in 4 times table){ do bla bla } the result for above will be false as 4 times table does not contain 3 if(12 is in 4 times table){ do bla bla } the above would be true Thanks guys I was wondering if anyone knows a good way to check for an even number of each character in a string. For example if the string is "abbacc" then it will return true as there are two of each character. However if the string is "ababc" it will return false as there is only 1 c. Thanks for any help hi friends could someone help with this criteria? i want to restrict entry to db if the post value number was entered into db less than 31 days ago?
if($homePhone == '') { $qry = "SELECT * FROM table WHERE homePhone='$homePhone '";in db i store time in datetime current timestamp like 2013-07-13 21:19:15 could someone help me out? Edited by lovephp, 12 July 2014 - 11:36 AM. Hi, How can I check if a variable only has these characters: - number (0-9) - decimal point (.) - positive (+) - negative (-) - dollar ($) I tried is_numeric, but it doesn't like negative values... I need to add the variable value to another variable. I have to accept numbers (including negative and decimals)... ex: 0.1 = TRUE -.1 = TRUE 12 = TRUE 1000.00 = TRUE 12a = FALSE thanks E.g. 18:00 - 22:30 $a = "18:00"; $b = "22:30"; this would return 4.5 (hours) 22:00 - 01:00 would return 3 hours Hi all, i have written a fairly simple profile page that users can see once they have logged in and i have a password change feature. the user is asked to enter there current password and then enter there desired new password, then confirm there new password to make sure they match. However the users current password isn't checked as im not sure how to code it. Heres my code so far: <?PHP session_start(); //Database Information $dbhost = "localhost"; $dbname = "test"; $dbuser = "test"; $dbpass = "test"; //Connect to database $conn = mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error()); mysql_select_db($dbname, $conn) or die(mysql_error()); //Clean data $_POST = array_map('strip_tags', $_POST); $_POST = array_map('mysql_real_escape_string', $_POST); $currentpassword = $_POST['currentpassword']; $newpassword = $_POST['newpassword']; $cnewpassword = $_POST['cnewpassword']; if($newpassword == $cnewpassword) { $query = "UPDATE `users` SET `password` = '".$newpassword."' WHERE `username` = '".$_SESSION['username']."' LIMIT 1"; $run = mysql_query($query); if($run) { echo "Congratulations You have successfully changed your password"; include 'success.php'; exit(); } else { include 'password.php'; exit; } } else { echo "The new password and confirm new password fields must be the same"; include 'password.php'; exit(); } ?> I'm guessing i need a && within the if statement to check the currentpassword with what is supplied within my database, but im not sure how to code this. Lee I'm getting the dreaded " Invalid parameter number: number of bound variables does not match number of tokens" error and I've looked at this for days. Here is what my table looks like:
| id | int(4) | NO | PRI | NULL | auto_increment | | user_id | int(4) | NO | | NULL | | | recipient | varchar(30) | NO | | NULL | | | subject | varchar(25) | YES | | NULL | | | cc_email | varchar(30) | YES | | NULL | | | reply | varchar(20) | YES | | NULL | | | location | varchar(50) | YES | | NULL | | | stationery | varchar(40) | YES | | NULL | | | ink_color | varchar(12) | YES | | NULL | | | fontchosen | varchar(30) | YES | | NULL | | | message | varchar(500) | NO | | NULL | | | attachment | varchar(40) | YES | | NULL | | | messageDate | datetime | YES | | NULL |Here are my params: $params = array( ':user_id' => $userid, ':recipient' => $this->message_vars['recipient'], ':subject' => $this->message_vars['subject'], ':cc_email' => $this->message_vars['cc_email'], ':reply' => $this->message_vars['reply'], ':location' => $this->message_vars['location'], ':stationery' => $this->message_vars['stationery'], ':ink_color' => $this->message_vars['ink_color'], ':fontchosen' => $this->message_vars['fontchosen'], ':message' => $messageInput, ':attachment' => $this->message_vars['attachment'], ':messageDate' => $date );Here is my sql: $sql = "INSERT INTO messages (user_id,recipient, subject, cc_email, reply, location,stationery, ink_color, fontchosen, message,attachment) VALUES( $userid, :recipient, :subject, :cc_email, :reply, :location, :stationery, :ink_color, :fontchosen, $messageInput, :attachment, $date);"; And lastly, here is how I am calling it: $dbh = parent::$dbh; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); if (empty($dbh)) return false; $stmt = $dbh->prepare($sql); $stmt->execute($params) or die(print_r($stmt->errorInfo(), true)); if (!$stmt) { print_r($dbh->errorInfo()); }I know my userid is valid and and the date is set above (I've echo'd these out to make sure). Since the id is auto_increment, I do not put that in my sql (though I've tried that too), nor in my params (tried that too). What am I missing? I feel certain it is something small, but I have spent days checking commas, semi-colons and spelling. Can anyone see what I'm doing wrong? hi, I have a function that calculates sales tax and it should put 2 numbers after the decimal point but it 's putting 5 numbers after the decimal point. Can someone help me figure out why? Code: [Select] function TotalSalesTax($price) { $salesTax = .07; $TotalSalesTax = $price * $salesTax; number_format($TotalSalesTax, 2); return $TotalSalesTax; } hi ,,, sorry bothering you i'm new in php mysql, and i've problem in "consecutive number" then i found clue in here : http://www.phpfreaks.com/forums/index.php/topic,228984.0.html it's really working with my problem but i got the result is always "0" in the first row. here's my code : $strSQL="SELECT * FROM station order by ID"; $rs=mysql_query($strSQL); while($row=mysql_fetch_array($rs)){ . . . $wet = "SELECT @count := 0"; $wet = "SELECT @count := IF(TotRain > 0 , @Count + 1, 0) as wetcnt FROM daily_syn WHERE ID ='".$row[ID]."' AND YEAR(SynDate)=".$stryear." ORDER BY wetcnt DESC LIMIT 1 "; $wetqres = mysql_query($wet); $wetinfo = mysql_fetch_array($wetqres); . . . $disp .= "<tr><td>".$row[ID]."</td><td>".$row[Sta_Name]."</td><td style=\"text-align:right;\">".$row[Lat]."</td><td style=\"text-align:right;\">".$row[Lon]."</td><td style=\"text-align:right;\">".$suhuMaksinfo[max]."</td><td style=\"text-align:right;\">".$suhuMininfo[min]."</td><td style=\"text-align:right;\">".$hujanMaksinfo[maxR]."</td><td style=\"text-align:right;\">".$Hhujaninfo[Dr]."</td><td style=\"text-align:right;\">".$Hhujan5info[Dr5]."</td><td style=\"text-align:right;\">".$Hhujan20info[Dr20]."</td><td style=\"text-align:right;\">".$Hhujan50info[Dr50]."</td><td style=\"text-align:right;\">".$Hhujan100info[Dr100]."</td><td style=\"text-align:right;\">".$wetinfo[wetcnt]."</td><td style=\"text-align:right;\">".$dryinfo[drycnt]."</td><td style=\"text-align:right;\">".$Rdensityinfo[SumR]."</td><td style=\"text-align:right;\">".$suhuMaksAbsinfo[maxAbs]."</td><td style=\"text-align:right;\">".$suhuMinAbsinfo[minAbs]."</td><td style=\"text-align:right;\">".$hujanMaksAbsinfo[maxRAbs]."</td></tr>"; it is looking for a "wetspell" from each YEARS (as input form) and from each station to display wetspell is the maximum consecutive rainday that th rain is greater than 1 milimeter but i got the first row always 0 for each years ,,, but the nesxt rows result is correct till the end rows and the other strange the dryspell is working properly from the first row dryspell is the maximum consecutive NO RainDay $dry = "SELECT @count := 0"; $dry = "SELECT @count := IF(TotRain <= 0 OR TotRain is NULL, @Count + 1, 0) as drycnt FROM daily_syn WHERE ID ='".$row[ID]."' AND YEAR(SynDate)=".$stryear." ORDER BY drycnt DESC LIMIT 1 "; $dryqres = mysql_query($dry); $dryinfo = mysql_fetch_array($dryqres); sorry cannot show you the result now, bcouse canot reach the server i hope you got what i mean and can help me with my problem many thanks, wish somone give me a help ,,, thanks Hello, i made a text site, so you can text from a website. i was making a database of the texted numbers and i found that the mysql line is not inserting the correct number, its going to the max php one. Here the code: if (array_key_exists($carrier, $carriers)) { $correctCarrier = $carriers[$carrier]; $i = 0; while($i < $_POST['amount']){ $i++; $formatted_number = $to.$correctCarrier; $result = ("$i of Your Messages Has been sent to the number ". $_POST['to'] . ".<br>" . mail("$formatted_number", "$subject", "$message") . ""); } mysql_query("INSERT INTO `msgssent` (`number`, `numberofmsg`, `subject`, `message`) VALUES (". $_POST['to'] .", '". $i ."', '". $subject ."', '". $message ."')") Or die(mysql_error()); Echo $result; } I have a problem that occurred only recently, apparently by some change my webhost made on the server. Some time ago I wrote a script that simulates a Poedit-type editor. The script has about 1500 textareas (the translation fields) with unique names, dynamically generated. All worked fine. Now suddenly I get errors (see below) when I use more than 1000 textareas. It is not a problem of $_POST size, if happens also with empty textareas. I will show here a simple php test file that I called testta.php, which creates the same error as my much more complicated real script: Code: [Select] <?php if(isset($_POST['test'])) { echo 'The textareas were posted successfully!<br>'; } $max = 1500; echo '<form action="testta.php" method="POST">'; echo '<input type="submit" name="test" value="Submit"><br>'; for($i=0; $i < $max; $i++) { echo '<textarea name="test'.$i.'">name is test'.$i.'</textarea><br>'; } echo '</form>'; ?> The error message generated in the browser: 500 Server Error: A misconfiguration on the server caused a hiccup. Check the server logs, fix the problem, then try again. From the Apache log file: [Sat Apr 28 12:47:48 2012] [error] [client 93.172.175.50] Premature end of script headers: testta.php, referer: http://****/*****/testta.php (stars added for privacy) When $max is set to a number < 1000 it works. On the web I have only found answers that deal with max size of posts, but as I mentioned that is not my case. My webhost can't help me out either. Until last Friday all worked fine. Does anyone know what server setting could create this problem? Thanks in advance, Kathy Hello,
I have problem durring binding update query. I can't find what is causing problem.
public function Update(Entry $e) { try { $query = "update entry set string = $e->string,delimiter=$e->delimiter where entryid= $e->id"; $stmt = $this->db->mysqli->prepare($query); $stmt->bind_param('ssi',$e->string,$e->delimiter,$e->id); $stmt->close(); } catch(Exception $ex) { print 'Error: ' .$ex->getMessage(); } }When I run function update I'm getting next error:Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement Can you help me to solve this problem ? Edited by danchi, 17 October 2014 - 10:25 AM. I need to display a number(the number is retrieved from the db) in the form input field such that only the last 4 digits is visbile, the remaining can be masked as * or X or whatever is applicable. I know the last 4 can be obtained as follows: Code: [Select] $number=substr($number,-4,4); But when i hit the submit button the form validates the input field and checks if the number is a valid number of a specific format. Therefore when I click on the submit button then I should still be able to unmask the masked numbers or do something similar that would help me validate the whole number. Code: [Select] <input type="text" name="no" value="<?php if(!empty($number)){ echo $number;} ?>"> Hello guys, I have a form where you can select a score between 0 and 10(only integers).
I want to check if the value that I recive, is integer.
Im using this code(exemple):
$integer = intval($_POST["p1"]); if(is_int($integer)){ echo 'INT'; } else { echo 'NO INT'; }My problem is that if it recive letters, the conversion converts it to 0, and it says that it is integer. So with this method I should discard the 0. You guys know a method to avoid that? Thank you guys Hi Everyone, I am having problems when submitting a form that has check boxes within it (post.php). All the check boxes have a name and a checked value of 1 - the receiving page (for example submit.php) has the variables defined: $tickbox1 = $_POST['tickbox1']; The problem I am finding is that if the box isnt checked - I get an "index is not defined" error. I would suppose because there is no value. I have tried this before and it has worked, however that was on Apache and this is on IIS. Is there a work around? Thanks Matt Hey I have a string that looks like the following: Quote top-php-tutorials-2.html I have a script that cycles through each page. The 2 in the quote above is the page number. How can I extract the number between the - and the .html and replace it with another number? I've tried Code: [Select] substr($engine->selectedcaturl, 0,-6).$v.".html"But then I realised this only works for numbers that are 1 digit long Any input would be appreciated so I have an xml string the following expression $xpath = $response->xpath('/atom:feed/atom:entry/atom:content'); returns the following array SimpleXMLElement Object ( [@attributes] => Array ( [type] => application/vnd.google-earth.kml+xml ) [Placemark] => SimpleXMLElement Object ( [name] => M1 [description] => SimpleXMLElement Object ( ) [Style] => SimpleXMLElement Object ( [IconStyle] => SimpleXMLElement Object ( [Icon] => SimpleXMLElement Object ( [href] => http://maps.gstatic.com/intl/en_ALL/mapfiles/ms/micons/blue-dot.png ) ) ) [Point] => SimpleXMLElement Object ( [coordinates] => -79.395018,43.645423,0.0 ) ) ) However what I'm trying to get are the coordinates, but neither $xpath = $response->xpath('/atom:feed/atom:entry/atom:content/Placemark'); OR $xpath = $response->xpath('/atom:feed/atom:entry/atom:content/Placemark/child::*'); work I even tried just loading atom:content into an array and going from there no luck. Any ideas. Oh. BTW this might help http://code.google.com/apis/maps/documentation/mapsdata/developers_guide_protocol.html#RetrievingFeatures |