mastwick Posted August 5, 2008 Share Posted August 5, 2008 Hi I seem to have a small problem with preg_match, I have searched through the forum for an answer but I couldn’t find anything to solve this. Here goes, I have managed to use successfully to validate numbers from a database using if (preg_match ("/^\d+$/", $code)) { My little problem is that I have another database using the same database connection, but these numbers contain at least two letters, this is where everything falls apart because when the submit button is hit the error code for invalid number is displayed. I can’t find the right expression to use, since it will be the same form field being used I just want the validation just to check if there’s at least 10 numbers and doesn’t matter if there are any letters being used or not. I am not to experienced in php since I am still learning it, but any help would be appreciated on how i could solve this. Quote Link to comment Share on other sites More sharing options...
Wuhtzu Posted August 5, 2008 Share Posted August 5, 2008 It sounds like you are looking for a regular expression to match a string containing numbers and letters... What will the string look like more specifically? Will the letters be at the beginning, the end, in the middle or spread randomly throughout the string? AB1234567890 1234567890AB 1234AB567890 12A3456B7890 or? Quote Link to comment Share on other sites More sharing options...
effigy Posted August 5, 2008 Share Posted August 5, 2008 I just want the validation just to check if there’s at least 10 numbers <pre> <?php $tests = array( '1234567890', 'A123456789', 'B1234567890', 'ABCDEFGHIJ1234567890', ); foreach ($tests as $test) { echo $test, ' => '; $numbers = 0; preg_replace('/\d/', '', $test, -1, $numbers); echo $numbers >= 10 ? 'Valid' : 'Invalid', '<hr>'; } ?> </pre> Quote Link to comment Share on other sites More sharing options...
mastwick Posted August 5, 2008 Author Share Posted August 5, 2008 Hi There thanks for the helpful replies I don’t think I was detailed enough (my fault), this is my scenario. I have this numbers draw I have done for my company, nice simple one. They give me numbers I save them csv and upload them to populate the database monthly, with me still learning php it took me a while to write this up. Now the numbers I was provided never contained letters they were always numbers. E.g. 25412659871Here is the code in action, I edited it to make it to the point and easier to follow. <? if (!isset($_POST["submit"])) { echo " Prize infomation"; } else { $code = $_POST['code']; $ans = "blank"; if ($code == null) { $message = "<font color=red><strong>Please enter your code.</strong></font>";} else { if (preg_match ("/^\d+$/", $code)) { $database = "database"; mysql_connect(); @mysql_select_db($database) or die("Unable to select database"); $query="SELECT * FROM july08 WHERE code = $code"; $result = mysql_query($query); $num=mysql_num_rows($result); mysql_close(); $name = mysql_result($result, $i, "name"); $entered = mysql_result($result, $i, "entered"); if ($entered == "yes") { $message = "<font color=red><strong>Sorry $name! <br>sorry you already entered this number this moth.</strong></font>";} else { $no="<font color=red><b>We are sorry but you are not a winner this month. Keep checking to see if you have won!</b></font>"; $yes="<font color=red>We are happy to confirm that you are a winner! You will be contacted shortly by email informing you of your prize.</font>"; $nocode="<br><br><font color=red size=3><b>Unfortunately the Number that you entered is invalid. </b></font>"; $winner = mysql_result($result, $i, "winner"); if ($code ==! mysql_result($result, $i, code)) { $message = "$nocode"; } else{ if ($winner !== "no") { if ($winner == "psp") { $prize = "a Sony PSP"; } if ($winner == "bc") { $prize = "a Baseball Cap"; } $message = "<br><br><font color=red size=3><b>Congratulations! You have won...</font><br><br> <font color=black size=3>$prize!<br><br></b></font>"; } else {$message = "$no";} } } } else { $valid="<font color=red>Please enter a valid code.</font>"; $message = "$valid"; } } Now as what is bugging me is that now I am provided with a new csv file with numbers (950 of them)that contain two lower case letters in the middle e.g. 14451gf45879, that is when my code goes straight to the error of $nocode (unfortunately wrong number), I could just get my bosses to just give me a list with only just numbers (but that wont make me look good). Thanks for taking you time to help Quote Link to comment Share on other sites More sharing options...
MadTechie Posted August 5, 2008 Share Posted August 5, 2008 I am not 100% sure what you mean, but heres 1.5 examples, if this is wrong and you give some examples what input your getting and if they should be valid or invalid (and why) <?php $var = "thisisokay"; //1 OK $var = "thiswillfail"; //2 Fail $var = "0123456789"; //3 Ok $var = "12345abc67890"; //4 Fail (uncomment replace line to make this work) $var = "abcdefghij"; //Ok //$var = preg_replace('/[^\d]/i', '', $var); //Remove letters (to make 4 work) if (preg_match('/^\w{10}$/i', $var)) { echo "Valid"; } else { echo "InValid"; } ?> Hope this helps EDIT: you could do if (preg_match('/^\w{1,10}$/i', $var)) to make numbers less than 10 characters long work (but atleast 1) Quote Link to comment Share on other sites More sharing options...
nrg_alpha Posted August 5, 2008 Share Posted August 5, 2008 Would this work? $str = array('14451gf45879', '1234x645!@879', '2231p2', '232gtrs5800433'); foreach($str as $val){ if(is_int($val) && strlen($val) == 10){ echo "Perfect! Variable $val is only made of 10 numbers <br />"; } else if(strlen($val = preg_replace('#[^0-9]#', '', $val)) == 10){ echo "Perfect! Variable $val is only made of 10 numbers <br />"; } else { echo "Error! Variable $val is not valid! <br />"; } } The idea here being that if I can check to see if a vriable is not only made of numbers but also 10 in length, no need to go through a regular expression to do useless calculations.. otherwise, chuck the variable through a preg and then see if it is 10 in total.. if so, great.. if not... invalid. Cheers, NRG Quote Link to comment Share on other sites More sharing options...
mastwick Posted August 6, 2008 Author Share Posted August 6, 2008 Hi Thanks for the help everyone, I seem to have learnt a lot from your tips, but after crazy testing I just found out that the errors I was getting weren’t really related to much to pregmatch, I decided to remove it from the time being and see whats wrong. The edited php code below works when numbers without letters are being used. I decided to use the same database using a different table and the numbers containing letters just wont get recognised the script goes straight to $nocode, I then changed that same number but removed the letters and the prize draw function properly, I can’t quite work out what’s wrong. If I can get past his bit I can go back to using better validation, since the tips here actually work <?php if (!isset($_POST["submit"])) { echo " Prize infomation"; } else { $code = $_POST['code']; $ans = "blank"; if ($code == null) { $message = "<font color=red><strong>Please enter your code.</strong></font>";} else { if ($code ==! null) { $database = "database"; mysql_connect(); @mysql_select_db($database) or die("Unable to select database"); $query="SELECT * FROM july08 WHERE code = $code"; $result = mysql_query($query); $num=mysql_num_rows($result); mysql_close(); $name = mysql_result($result, $i, "name"); $entered = mysql_result($result, $i, "entered"); if ($entered == "yes") { $message = "<font color=red><strong>Sorry $name! sorry you already entered this number this moth.</strong></font>";} else { $no="<font color=red>We are sorry but you are not a winner this month. Keep checking to see if you have won!</font>"; $yes="<font color=red>We are happy to confirm that you are a winner! You will be contacted shortly by email informing you of your prize.</font>"; $nocode=" <font color=red size=3>Unfortunately the Number that you entered is invalid. </font>"; $winner = mysql_result($result, $i, "winner"); if ($code ==! mysql_result($result, $i, code)) { $message = "$nocode"; } else{ if ($winner !== "no") { if ($winner == "psp") { $prize = "a Sony PSP"; } if ($winner == "bc") { $prize = "a Baseball Cap"; } $message = " <font color=red size=3>Congratulations! You have won...</font> <font color=black size=3>$prize! </font>"; } else {$message = "$no";} } } } else { $valid="<font color=red>Please enter a valid code.</font>"; $message = "$valid"; } }?> example number typed 61593442377 this type of number is recognised from the php code I posted earlier, works fine. Example number 61593aq42377 these are the numbers which contain letters for some reason will not get seen, when I remove the letters and use numbers, my prize draw code works. It’s an easy fix but I have 950 unique numbers and I just want my script to work with them. Thanks for the help Quote Link to comment Share on other sites More sharing options...
nrg_alpha Posted August 6, 2008 Share Posted August 6, 2008 I misread your code.. will re-examine... Quote Link to comment Share on other sites More sharing options...
nrg_alpha Posted August 6, 2008 Share Posted August 6, 2008 I am having a hard time reading your code due to poor structure.. I'm not sure if it's the way it has been pasted into your post or not.. but if this is the case, I would go through the trouble of previewing your post and making sure it is well structured.. as it is.. it's not well put together and as a result, it is hard to make out.. I am finding difficulty in knowing which closing curlybarace belongs with which if or else statement. Off the top, I am seeing lines like: if ($code == null) I'm not sure if null needs to be capitalised, but in Dreamweaver, only NULL is colour coded (thus recognized as such).. so perhaps using caps on NULL? This is not the way to write it: if ($code ==! null) { It should be written as such: if ($code != NULL) { I would repost the code snippet you just showed us with proper formatting.. ensure that if and else statements are formatted with correct curlybraces and whatnot.. as it stands.. your code is very difficult to make out what's going on. Cheers, NRG Quote Link to comment Share on other sites More sharing options...
MadTechie Posted August 6, 2008 Share Posted August 6, 2008 Not validation but the probable bug fix, change $query="SELECT * FROM july08 WHERE code = $code"; to $query="SELECT * FROM july08 WHERE code = '$code' "; Quote Link to comment Share on other sites More sharing options...
mastwick Posted August 7, 2008 Author Share Posted August 7, 2008 Hi everyone Thanks a lot or your help, I have learnt quite a nit here, especially restructuring and understanding ones code. But I am still learning. I managed to solve the problem on why the prize draw code couldn’t recognise my numbers. I would like to thank MadTechie for that, your bug fix code hint was the problem, after putting ‘code’ in single marks it now sees the database and works fine. Alas now I have two problems these should be simple for you guys to notice. First one is on topic I am still having preg_match issues I have tried the hints but I still can’t quite understand it. Ill get to the point this is what i came up with i know i have done it wrong somewhere. <?php if ( preg_match('/^[0-9]+$/',$code) ) { ?> is there a way i can word it propely so it can work with a table that contains numbers like these? 61593aa42377 61523bb86383 61523cc86383 61523xx86383 My second problem is that my code works fine (when I don’t use preg_match), but I want it to be able to check two tables in a database at the same time and then move on. I don’t know how to implement that. At the moment it connects to one database queries one table and moves on. I have another table containing different numbers these were the ones that contain letters, I want to the code two check both tables, I wan it so when someone enters a code from a table B it will check table A and B before returning any response, not check just table A with a number meant for table B and respond with number not found. here's is my normal code, its durin connetion to the database i need to implement this, but i am stuck <?php if (!isset($_POST["submit"])){ echo "Prize infomation"; } else { $code = $_POST['code']; $ans = "blank"; if ($code == null) { $message = "<font color=red><strong>Please enter your code.</strong></font>"; } else { if ($code ==! null) { $database = "database"; mysql_connect(); @mysql_select_db($database) or die("Unable to select database"); $query="SELECT * FROM dbtest8 WHERE code = $'code'"; $result = mysql_query($query); $num=mysql_num_rows($result); mysql_close(); $name = mysql_result($result, $i, "name"); $entered = mysql_result($result, $i, "entered"); if ($entered == "yes") { $message = "<font color=red><strong>Sorry $name! sorry you already entered this number this moth.</strong></font>";} else { $no="<font color=red>We are sorry but you are not a winner this month. Keep checking to see if you have won!</font>"; $yes="<font color=red>We are happy to confirm that you are a winner! You will be contacted shortly by email informing you of your prize.</font>"; $nocode="<font color=red size=3>Unfortunately the Number that you entered is invalid. </font>"; $winner = mysql_result($result, $i, "winner"); if ($code ==! mysql_result($result, $i, code)) { $message = "$nocode"; } else{ if ($winner !== "no") { if ($winner == "psp") { $prize = "a Sony PSP"; } if ($winner == "bc") { $prize = "a Baseball Cap"; } $message = "<font color=red size=3>Congratulations! You have won...</font> <font color=black size=3>$prize!</font>"; } else {$message = "$no";} } } } else { $valid="<font color=red>Please enter a valid code.</font>"; $message = "$valid"; } }?> The Reason why I am doing it this way is because I was given two different csv lists and later on I will have to put ‘if’ statements displaying different messages. E.g. when someone wins, i.e. if a number from table A is entered the winner will get “this message” if a number from table B is entered they will get “this different message” all from the same submit field. If this second question is too off topic I will post it somewhere else on the forum. thatnks for the help Quote Link to comment Share on other sites More sharing options...
mastwick Posted August 7, 2008 Author Share Posted August 7, 2008 Hi everyone After countless hours of reading and understanding preg_match I finally solved my problem. To validate numbers like 61593koo2377, 61593kjj2377, 61593bb42377 i used <?php ( preg_match('/^[0-9]+[a-z]{2}[0-9]+$/',$code) ) { ?> After researching and studying this, it makes sense and i feel like an idiot for what i posted earlier but there you go. i also managed to fix my double database connection, anyone who might find it useful here you go otherwise you can ignore, it's not structured to pro standards but thats the best i could do with my limited knowledge of php. <?php $code = $_POST['code']; if ( ! empty($code) ) { if (preg_match ("/^\d+$/", $code)) { First_DB(); }elseif (preg_match('/^[0-9]+[a-z]{2}[0-9]+$/',$code)) { SECOND_DB(); }else{ die("wrong code"); } }else{ die("Please enter your code!"); } ?> thank you all for your help, thanks madtechie for your code bug hint. look forward to posting here in future. now i need to put this as solved Quote Link to comment Share on other sites More sharing options...
MadTechie Posted August 7, 2008 Share Posted August 7, 2008 Hi everyone Thanks a lot or your help, I have learnt quite a nit here, especially restructuring and understanding ones code. But I am still learning. I managed to solve the problem on why the prize draw code couldn’t recognise my numbers. I would like to thank MadTechie for that, your bug fix code hint was the problem, after putting ‘code’ in single marks it now sees the database and works fine. Cool and your welcome Alas now I have two problems these should be simple for you guys to notice. First one is on topic I am still having preg_match issues I have tried the hints but I still can’t quite understand it. Ill get to the point this is what i came up with i know i have done it wrong somewhere. <?php if ( preg_match('/^[0-9]+$/',$code) ) { ?> is there a way i can word it propely so it can work with a table that contains numbers like these? 61593aa42377 61523bb86383 61523cc86383 61523xx86383 replace if ( preg_match('/^[0-9]+$/',$code) ) { with //remove anything thats not a number $code = preg_replace('/[^\d]/i', '', $code); //61593aa42377 becomes 6159342377 //check its valid if (preg_match('/^\d{10}$/i', $code)) { //checks code is 10 "numbers" from start to end or if you know letters are always in the same place try if (preg_match('/^\d{5}\w{2}\d{5}$/i', $code)) { My second problem is that my code works fine (when I don’t use preg_match), but I want it to be able to check two tables in a database at the same time and then move on. I don’t know how to implement that. At the moment it connects to one database queries one table and moves on. I have another table containing different numbers these were the ones that contain letters, I want to the code two check both tables, I wan it so when someone enters a code from a table B it will check table A and B before returning any response, not check just table A with a number meant for table B and respond with number not found. here's is my normal code, its durin connetion to the database i need to implement this, but i am stuck <?php if (!isset($_POST["submit"])){ echo "Prize infomation"; } else { $code = $_POST['code']; $ans = "blank"; if ($code == null) { $message = "<font color=red><strong>Please enter your code.</strong></font>"; } else { if ($code ==! null) { $database = "database"; mysql_connect(); @mysql_select_db($database) or die("Unable to select database"); $query="SELECT * FROM dbtest8 WHERE code = $'code'"; $result = mysql_query($query); $num=mysql_num_rows($result); mysql_close(); $name = mysql_result($result, $i, "name"); $entered = mysql_result($result, $i, "entered"); if ($entered == "yes") { $message = "<font color=red><strong>Sorry $name! sorry you already entered this number this moth.</strong></font>";} else { $no="<font color=red>We are sorry but you are not a winner this month. Keep checking to see if you have won!</font>"; $yes="<font color=red>We are happy to confirm that you are a winner! You will be contacted shortly by email informing you of your prize.</font>"; $nocode="<font color=red size=3>Unfortunately the Number that you entered is invalid. </font>"; $winner = mysql_result($result, $i, "winner"); if ($code ==! mysql_result($result, $i, code)) { $message = "$nocode"; } else{ if ($winner !== "no") { if ($winner == "psp") { $prize = "a Sony PSP"; } if ($winner == "bc") { $prize = "a Baseball Cap"; } $message = "<font color=red size=3>Congratulations! You have won...</font> <font color=black size=3>$prize!</font>"; } else {$message = "$no";} } } } else { $valid="<font color=red>Please enter a valid code.</font>"; $message = "$valid"; } }?> The Reason why I am doing it this way is because I was given two different csv lists and later on I will have to put ‘if’ statements displaying different messages. E.g. when someone wins, i.e. if a number from table A is entered the winner will get “this message” if a number from table B is entered they will get “this different message” all from the same submit field. If this second question is too off topic I will post it somewhere else on the forum. thatnks for the help here a revised version using 2 database <?php if (!isset($_POST["submit"])) { echo "Prize infomation"; }else{ $code = $_POST['code']; $ans = "blank"; if ($code == null) { $message = "<font color=red><strong>Please enter your code.</strong></font>"; }else { $valid="<font color=red>Please enter a valid code.</font>"; if ($code ==! null) { $database = "database"; $dbname = "database username"; $dbpass = "database password"; $link = mysql_connect($database, $dbname, $dbpass) OR die(mysql_error()); mysql_select_db($database) or die("Unable to select database"); $i = 0; //? no idea why it wasn't set! //Added protection and limited to 1 result //Database 1 $query = sprintf("SELECT * FROM dbA WHERE code = '%s' LIMIT 1", mysql_real_escape_string($code)); $result = mysql_query($query) OR die(mysql_error()); $num=mysql_num_rows($result); if($num>0) { $foundin = "A"; $sCode = mysql_result($result, $i, "code"); $sWinner = mysql_result($result, $i, "winner"); $sName = mysql_result($result, $i, "name"); $sEntered = mysql_result($result, $i, "entered"); } //Database 2 $query = sprintf("SELECT * FROM dbB WHERE code = '%s' LIMIT 1", mysql_real_escape_string($code)); $result = mysql_query($query) OR die(mysql_error()); $num=mysql_num_rows($result); if($num>0) { $foundin = "B"; $sCode = mysql_result($result, $i, "code"); $sWinner = mysql_result($result, $i, "winner"); $sName = mysql_result($result, $i, "name"); $sEntered = mysql_result($result, $i, "entered"); } //Database 3 $query = sprintf("SELECT * FROM dbC WHERE code = '%s' LIMIT 1", mysql_real_escape_string($code)); $result = mysql_query($query) OR die(mysql_error()); $num=mysql_num_rows($result); if($num>0) { $foundin = "C"; $sCode = mysql_result($result, $i, "code"); $sWinner = mysql_result($result, $i, "winner"); $sName = mysql_result($result, $i, "name"); $sEntered = mysql_result($result, $i, "entered"); } //-------------defaults--------- $Sorry = "<font color=red><strong>Sorry!<br>sorry you already entered this number this month.</strong></font>"; $no="<font color=red>We are sorry but you are not a winner this month. Keep checking to see if you have won!</font>"; $yes="<font color=red>We are happy to confirm that you are a winner! You will be contacted shortly by email informing you of your prize.</font>"; $nocode="<font color=red size=3>Unfortunately the Number that you entered is invalid. </font>"; //---------------------- switch($foundin) { case "A": $Sorry = "<font color=red><strong>Message from database A Sorry $sName!<br>sorry you already entered this number this month.</strong></font>"; break; case "B": $Sorry = "<font color=yellow><strong>Sorry $sName!<br>Message from database B sorry you already entered this number this month.</strong></font>"; break; case "C": $Sorry = "<font color=blue><strong>Sorry $sName!<br>Message from database C sorry you already entered this number this month.</strong></font>";# break; } mysql_close(); if ($sEntered == "yes") { $message = $Sorry; }else { if ($code ==! $sCode) { $message = $nocode; }else{ $prize=false; switch($sWinner) { case "psp": $prize = "a Sony PSP"; break; case "bc": $prize = "a Baseball Cap"; break; } $message = (!$prize)?"<font color=red size=3>Congratulations! You have won...</font><br><font color=black size=3>$prize!</font>":$no; } } }else{ $message = $valid; } } //Added the } below } ?> EDIT: Ahh see what you mean by searching one or the other depending on if it had letters.. (do the database use is different in mine) Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.