Related
//This is my php for the registration: <?php
/* Program name: checkBlankOnly_2.php
* Description: Program displays the blank form and checks
* all the form fields for blank fields.
*/
if(isset($_POST['submitted']) and $_POST['submitted'] == "yes")
{
foreach($_POST as $field => $value)
{
if(empty($value))
{
if($field != "firstname")
{
$blank_array[] = $field;
}
}
else
{
$good_data[$field] = strip_tags(trim($value));
}
}
if($blank_array > 0)
{
$message = "<p style='color: red; margin-bottom: 0;
font-weight: bold'>
You didn't fill in one or more required fields.
You must enter:
<ul style='color: red; margin-top: 0;
list-style: none' >";
/* display list of missing information */
foreach($blank_array as $value)
{
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($good_data);
include("logic.inc");
exit();
}
foreach($_POST as $field => $value)
{
if(!empty($value))
{
$name_patt2 = "/^[a-z]\w{2,23}[^_]$/i";
$name_patt = "/^[A-Za-z' -]{1,50}$/";
$pass_patt = "/^[a-zA-Z][0-9a-zA-Z_!$##^&]{5,20}$/";
$phone_patt = "/^[0-9)(xX -]{7,20}$/";
$addr_patt = "/^[A-Za-z0-9 .,'-]{1,50}$/";
$zip_patt = "/^[0-9]{5}(\-[0-9]{4})?$/";
$postal_patt = "/^[A-Za-z0-9]{6}$/";
$email_patt = "/^.+#.+\\..+$/";
$radio_patt = "/Canada|USA/";
if(preg_match("/uname/i",$field))
if(!preg_match($name_patt2,$value))
{
$error_array [] = "$value is not a valid username";
}
if(preg_match("/name/i",$field))
{
if(!preg_match($name_patt,$value))
{
$error_array[] = "$value is not a valid name";
}
}
if(preg_match("/phone/i",$field))
{
if(!preg_match($phone_patt,$value))
{
$error_array[] = "$value is not a valid phone number";
}
} // endif phone format check
if(preg_match("/country/i",$field))
{
if(!preg_match($radio_patt,$value))
{
$error_array[] = "$value is not a valid status";
}
}
}
$clean_data[$field] = strip_tags(trim($value));
}
if($error_array > 0)
{
$message = "<ul style='color: red; list-style: none' >";
foreach($error_array as $value)
{
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($clean_data);
include("logic.inc");
exit();
}
else
{
$cxn = mysqli_connect($host,$user,$passwd,$dbname)
or die("Couldn't Connect to Server");
foreach($clean_data as $field => $value)
{
$clean_data[$field] = mysqli_real_escape_string($cxn,$value);
}
$sql = "INSERT INTO users (uname,password,lastname,firstname,city,address,state_province,country,phone,email,date) VALUES ('$clean_data[uname]','$clean_data[password]','$clean_data[lastname]','$clean_data[firstname]','$clean_data[city]','$clean_data[address]','$clean_data[state_province]','$clean_data[country]','$clean_data[phone]','$clean_data[email]','$clean_data[date]')";
$result = mysqli_query($cxn,$sql)
or die("Couldn't Execute Query");
include("stored.inc");
}
}
else
{
include("logic.inc");
}
?>
\\ This is my HTML code:
<!doctype html>
<?php
ini_set("display_errors","on");
error_reporting(E_ALL | E_STRICT);
ini_set("include_path","./includes");
include("dbinfo.inc");
?>
<?php
/* Program Name: logic.inc
* Created by: Clayton Korth
* Created On: 2022-05-20
* Description: Defines a form that collects a user's information */
$labels = array ("uname" => "Username","firstname" => "First Name","lastname" => "Last Name","address" => "Address","city" => "City","zip_postal" => "Zip Code","phone" => "Phone","email" => "Email");
$country = array("Canada","US");
$submit = "Submit Information";
$empty_array = array();
$blank_array = array();
?>
<?php
$cxn = mysqli_connect($host,$user,$passwd,$dbname)
or die ("Couldn't Connect to Server");
$query = "SELECT DISTINCT name FROM states ORDER BY `id` ASC";
$result = mysqli_query($cxn,$query) or die ("Couldn't Execute Query.")
?>
<html>
<head>
<style type='text/css'>
<!--
form {
margin: 1.5em 0 0 0;
padding: 0;
align-content: center;
}
.field {padding-bottom: 1em;}
h1 {text-align: center;}
label {
font-weight: bold;
float: left;
width: 20%;
margin-right: 1em;
text-align: right;
}
#submit {margin-left: 35%}
--></style>
<meta charset="utf-8">
<title>Form Script</title>
</head>
<body>
<?php
/* loop that displays the form */
echo "<div class='row'><div class='col-lg-6>'";
echo "<h3>Sign Up Form</h3>";
echo "<form id='sForm' form action='checkBlankOnly2.php' method='post'>";
foreach ( $labels as $field => $label)
{
echo "<div class='field'>
<label for='$field' style='font-weight: bold;'>$label</label>
<input id='$field' name='$field' type='text' placeholder='$label'
size='42' /></div>";
if($field == "uname")
{
echo "<div class='field'><label for='password'>Password</label><input id='password' placeholder='Password' name='password' type='password' size='42'></div>";
}
if($field == "city")
{
echo "<form action='checkBlankOnly2.php' method='POST' style='margin-left: 3em'>
<label for'name' style='font-weight: bold'>State/Province:</label>
<select id='name' name='name' style='margin-top: 3em'>";
while($row = mysqli_fetch_assoc($result))
{
extract($row);
echo "<option value='$name'>$name</option>";
}
echo "</select>";
echo "<div class='field'><label for='country'>Country</label><input type='radio' name='country' checked='checked' value='Canada' >$country[0]
<input type='radio' name='country' value='US' style='margin-left: 1.5em'>$country[1]</div>";
}
}
echo "<div class='field'><input type='hidden' name='submitted' value='yes'</div>";
echo "<div id='submit'><input type='submit' value='$submit'></div>";
echo "</div></div>"
?>
</body>
</html>
Above is my code for my registration.php as I am tasked to create an Login Application. What happens is that when I submit the form it validates everything except the username causing it to be validated by using name instead of username. I am wondering if I had done something wrong with my code. I am fairly new to PHP and Dynamic Web Design
You'll probably want to read up on regular expressions, which is what preg_match() uses.
https://www.php.net/manual/en/function.preg-match.php
The following code will first get a positive match of uname against /uname/i, and then compare the value against $name_patt2, but then it will also get a positive match of uname against /name/i, because the pattern isn't anchored to the beginning with ^.
if(preg_match("/uname/i",$field))
{
if(!preg_match($name_patt2,$value))
{
$error_array [] = "$value is not a valid username";
}
}
if(preg_match("/name/i",$field))
{
if(!preg_match($name_patt,$value))
{
$error_array[] = "$value is not a valid name";
}
}
You can go one of 3 ways, if you're leaving the rest of the program alone:
One is to replace the $field checks with anchored regexes, like this:
if(preg_match("/^uname/i", $field))
...
A second option is to elseif so you won't check the other patterns for $field if the first one already matched:
if(preg_match("/uname/i",$field))
{
if(!preg_match($name_patt2,$value))
{
$error_array [] = "$value is not a valid username";
}
}
elseif(preg_match("/name/i",$field))
{
if(!preg_match($name_patt,$value))
{
$error_array[] = "$value is not a valid name";
}
}
The third option (depending on what the field naming actually looks like), would be to use exact string matches instead of regex matches:
if($field == "uname")
{
if(!preg_match($name_patt2,$value))
{
$error_array [] = "$value is not a valid username";
}
}
if($field == "name")
{
if(!preg_match($name_patt,$value))
{
$error_array[] = "$value is not a valid name";
}
}
These are the working codes that i have done. the program is about accessing information in an xml file such as student's name,id and marks based on group and team number submitted from a form. there are 2 submit buttons if one button is clicked, it will display with an additional element (pic) and the other one without it. so far so good.
but looking at the php codes, i know that i will be facing problems if there are numerous groups and team numbers. there would be a lot of if-else statements and the codes would be very long. i have tried using foreach but i'm not getting the result that i want. are there anyways to simplify this? i have been searching on the web but it seems that i just don't know how to implement them. quite new to this.
<html><style>
.datagrid table { border-collapse: collapse; text-align: center; width: 100%; }
.datagrid {font: normal 12px/150% Arial, Helvetica, sans-serif;
background: #fff;
overflow: hidden;
border: 4px solid #006699;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
border-radius: 20px; }
.datagrid table td, .datagrid table th { padding: 7px 20px; }
.datagrid table thead th {background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );
background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% ); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');
background-color:#006699; color:#FFFFFF; font-size:15px; font-weight:bold;
border-left: 1px solid #0070A8; }
.datagrid table thead th:first-child { border: none; }
.datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4;font-size: 13px;font-weight: normal; }
.datagrid table tbody .alt td { background: #E1EEF4; color: #00496B; }
.datagrid table tbody td:first-child { border-left: none; }
.datagrid table tbody tr:last-child td { border-bottom: none; }
</style>
<center>
<form action="" method="post" >
<select name="group">
<option value="csa">CSA</option>
<option value="csb">CSB</option>
</select>
Enter team number:<input type="text" name="teamnum" value="">
<input type="submit" name="submit1" value="With Photo">
<input type="submit" name="submit2" value="Without Photo">
</form>
<form action="index.php">
<input type="submit" value="main">
</form>
</center>
</html>
<?php
if (isset($_POST['submit1']) != '') {
$file = "student.xml";
$xml = simplexml_load_file($file) or die("Unable to load XML file!");
if (isset($_POST['group']) && isset($_POST['teamnum']) != '') {
$teamnum = $_POST['teamnum'];
$group = $_POST['group'];
if ($group == 'csa' && $teamnum == '1') {
$name = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/name');
$id = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/id');
$total = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/total');
//$photo =$xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/pic');
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Photo</th><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
while ((list(, $node) = each($name)) && (list(, $node1) = each($id)) && (list(, $node2) = each($total))) {
echo "<tbody><tr class='alt'>";
echo "<td>1</td>";
echo "<td>$node</td>";
echo "<td>$node1</td>";
echo "<td>$node2</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}
else if ($group == 'csa' && $teamnum == '2') {
$name = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/name');
$id = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/id');
$total = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/total');
//$photo =$xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/pic');
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Photo</th><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
while ((list(, $node) = each($name)) && (list(, $node1) = each($id)) && (list(, $node2) = each($total))) {
echo "<tbody><tr class='alt'>";
echo "<td>1</td>";
echo "<td>$node</td>";
echo "<td>$node1</td>";
echo "<td>$node2</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}
else if (isset($_POST['submit2']) != '') {
$file = "student.xml";
$xml = simplexml_load_file($file) or die("Unable to load XML file!");
if (isset($_POST['group']) && isset($_POST['teamnum']) != '') {
$teamnum = $_POST['teamnum'];
$group = $_POST['group'];
if ($group == 'csa' && $teamnum == '1') {
$name = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/name');
$id = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/id');
$total = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/total');
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
while ((list(, $node) = each($name)) && (list(, $node1) = each($id)) && (list(, $node2) = each($total))) {
echo "<tbody><tr class='alt'>";
echo "<td>$node</td>";
echo "<td>$node1</td>";
echo "<td>$node2</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}
else if ($group == 'csa' && $teamnum == '2') {
$name = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/name');
$id = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/id');
$total = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/total');
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
while ((list(, $node) = each($name)) && (list(, $node1) = each($id)) && (list(, $node2)= each($total))) {
echo "<tbody><tr class='alt'>";
echo "<td>$node</td>";
echo "<td>$node1</td>";
echo "<td>$node2</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}
?>
i have found the way to solve this by using foreach
<?php
if (isset($_POST['submit1']) != '') {
$file = "student.xml";
$xml = simplexml_load_file($file) or die("Unable to load XML file!");
if (isset($_POST['group']) && isset($_POST['teamnum']) != '') {
$teamnum = $_POST['teamnum'];
$group = $_POST['group'];
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Photo</th><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
echo "<tbody>";
foreach ($xml->xpath("//student[contains(teamNum, $teamnum) and contains(group, $group)]") as $student) {
echo "<tr class='alt'>";
echo "<td>".$student->picture."</td>";
echo "<td>".$student->name."</td>";
echo "<td>".$student->id."</td>";
echo "<td>".$student->total."</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}else echo 'no data';
} else {
echo "enter a team's number";
}
?>
the trick is in the xpath. it selects all students that contains submitted values. after that it will be as $student and i will be able to output the element values from there.
I'm taking a course called "Dynamic Web Development with PHP" and after getting an F for an exercise, I wish if you could help me with the following.
I have a php file and an inc file (that shows the form).
What I can't figure out how to resolve is the drop-down lists of the country and state / province, which should work like this:
If country USA is selected populate US states.
If country CAN is selected populate Canadian provinces.
I've made to array's one is states_list (USA) and province_list (CAN)
My teacher asking me to use the if statement to show the drop-down field.
Exemple:
foreach($labels as $field => $label)
{
if($field == "state")
{
echo html code for the drop-down list
}
else
{
echo html code for a text field
}
}
My inc file:
<?php
/* Program name: form_data.inc
* Description: Defines the form that collects a user's
* personal information.
*/
$labels = array( "firstName" => "First Name",
"lastName" => "Last Name",
"street" => "Street",
"city" => "City",
"zip" => "Postal Code",
"country" => "Country",
"state" => "State",
"email" => "E-mail",
"phone" => "Phone",);
$country_list = array("USA" => "United States",
"CAN" => "Canada",);
$state_list = array( "AL"=>"AL",
"AK"=>"AK",
"AZ"=>"AZ",
"AR"=>"AR",
"CA"=>"CA",
"CO"=>"CO",
"CT"=>"CT",
"DE"=>"DE",
"DC"=>"DC",
"FL"=>"FL",
"GA"=>"GA",
"HI"=>"HI",
"ID"=>"ID",
"IL"=>"IL",
"IN"=>"IN",
"IA"=>"IA",
"KS"=>"KS",
"KY"=>"KY",
"LA"=>"LA",
"ME"=>"ME",
"MD"=>"MD",
"MA"=>"MA",
"MI"=>"MI",
"MN"=>"MN",
"MS"=>"MS",
"MO"=>"MO",
"MT"=>"MT",
"NE"=>"NE",
"NV"=>"NV",
"NH"=>"NH",
"NJ"=>"NJ",
"NM"=>"NM",
"NY"=>"NY",
"NC"=>"NC",
"ND"=>"ND",
"OH"=>"OH",
"OK"=>"OK",
"OR"=>"OR",
"PA"=>"PA",
"RI"=>"RI",
"SC"=>"SC",
"SD"=>"SD",
"TN"=>"TN",
"TX"=>"TX",
"UT"=>"UT",
"VT"=>"VT",
"VA"=>"VA",
"WA"=>"WA",
"WV"=>"WV",
"WI"=>"WI",
"WY"=>"WY");
$province_list = array( "AB"=>"AB",
"BC"=>"BC",
"MB"=>"MB",
"NB"=>"NB",
"NL"=>"NL",
"NS"=>"NS",
"NT"=>"NT",
"NU"=>"NU",
"ON"=>"ON",
"PE"=>"PE",
"QC"=>"QC",
"SK"=>"SK",
"YT"=>"YT");
$radios = array( "New", "Changed");
$submit = "Submit Data";
?>
<html>
<head>
<title>Form</title>
<style type='text/css'>
<!--
body {
background: #242523;
font-family: Tahoma, Geneva, sans-serif;
}
form {
width: 500px;
margin: auto;
padding: 10px 0 25px 0;
-webkit-border-radius: 7px/9px;
-moz-border-radius: 7px/9px;
border-radius: 7px/9px;
background-color: #fff;
}
.field {padding-bottom: 1em;
font-weight: normal;
font-size:14px;
}
label {
font-weight: normal;
font-size:14px;
float: left;
width: 20%;
margin-right: 1em;
text-align: right;
}
input {
}
h3 {
color:#C00;
text-align: center;
font-size:20px;
padding-bottom: 10px;
}
#submit {
margin-left: 22%;
}
-->
</style>
</head>
<body>
<br>
<?php
/* loop that displays the form */
echo "<form action='$_SERVER[PHP_SELF]' method='POST'>";
echo "<h3>Personal information</h3>";
foreach($labels as $field => $label)
{
echo "<div class='field'><label for='$field'>$label</label>
<input id='$field' name='$field' type='text' value='".#$$field."'
size='50%' maxlength='50' /></div>\n";
}
echo "<div class='field'>
<input type='radio' name='status' checked='checked'
value='new' style='margin-left: 25%'/>$radios[0]
<input type='radio' name='status'
value='changed' style='margin-left: 25%' />$radios[1]</div>\n";
echo "<div class='field'>
<input type='hidden' name='submitted' value='yes' /></div>\n";
echo "<div id='submit'>
<input type='submit' name='submitButton' value='$submit'></div>";
?>
</form>
</body>
</html>
My PHP file:
<?php
/* Program name: checkBlank.php
* Description: Program displays the blank form and checks
* all the form fields for blank fields.
*/
if(isset($_POST['submitted']) and $_POST['submitted'] == "yes")
{
foreach($_POST as $field => $value)
{
if(empty($value))
{
if($field != "firstName")
{
$blank_array[] = $field;
}
}
else
{
$good_data[$field] = strip_tags(trim($value));
}
}
if(#sizeof($blank_array) > 0)
{
$message = "<p style='color: white; margin-bottom: 0;
font-weight: bold'>
You didn't fill in one or more required fields.
You must enter:
<ul style='color: red; margin-top: 0;
list-style: none' >";
/* display list of missing information */
foreach($blank_array as $value)
{
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($good_data);
include("form_data.inc");
exit();
} // endif missing information
/* format check */
foreach($_POST as $field => $value)
{
if(!empty($value))
{
$name_patt = "/^[A-Za-z' -]{1,50}$/";
$addr_patt = "/^[A-Za-z0-9 .,'-]{1,50}$/";
$city_patt = "/^[A-Za-z' -]{1,50}$/";
$postal_patt = "/^[A-Za-z0-9-]{1,10}$/";
$state_patt = "/^[A-Za-z]{2}$/";
$province_patt = "/^[A-Za-z]{2}$/";
$country_patt = "/^[A-Za-z' -]{1,50}$/";
$email_patt = "/^.+#.+\\..+$/";
$phone_patt = "/^[0-9)(xX -]{7,20}$/";
$radio_patt = "/(new|changed)/";
/* Checks first and last names */
if(preg_match("/name/i",$field))
{
if(!preg_match($name_patt,$value))
{
$error_array[] = "$value is not a valid name";
}
}
/* Checks address */
if(preg_match("/street/i",$field))
{
if(!preg_match($addr_patt,$value))
{
$error_array[] = "$value is not a valid address";
}
}
/* Checks city */
if(preg_match("/city/i",$field))
{
if(!preg_match($city_patt,$value))
{
$error_array[] = "$value is not a valid city name";
}
}
/* Checks postal code */
if(preg_match("/zip/i",$field))
{
if(!preg_match($postal_patt,$value))
{
$error_array[] = "$value is not a valid potal code";
}
}
/* Checks country names*/
if(preg_match("/country/i",$field))
{
if(!preg_match($country_patt,$value))
{
$error_array[] = "$value is not a valid country";
}
}
/* Checks state and province names */
if(preg_match("/state/i",$field))
{
if(!preg_match($state_patt,$value))
{
$error_array[] = "$value is not a valid state";
}
}
if(preg_match("/province/i",$field))
{
if(!preg_match($province_patt,$value))
{
$error_array[] = "$value is not a valid province";
}
}
/* Checks email address */
if(preg_match("/email/i",$field))
{
if(!preg_match($email_patt,$value))
{
$error_array[] = "$value is not a valid e-mail address";
}
}
/* Checks phone number */
if(preg_match("/phone/i",$field))
{
if(!preg_match($phone_patt,$value))
{
$error_array[] = "$value is not a valid phone number";
}
} // endif formats check
if(preg_match("/status/i",$field))
{
if(!preg_match($radio_patt,$value))
{
$error_array[] = "$value is not a valid status";
}
}
}
$clean_data[$field] = strip_tags(trim($value));
}
if(#sizeof($error_array) > 0)
{
$message = "<ul style='color: red; list-style: none' >";
foreach($error_array as $value)
{
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($clean_data);
include("form_data.inc");
exit();
}
else
{
echo "Data is all okay";
}
/* displays all the information passed from a form */
echo "<ol>";
foreach($_POST as $field => $value)
{
echo "<li> $field = $value</li>";
}
echo "</ol>";
}
else
{
include("form_data.inc");
}
?>
you can make two drop down list one for country and two for states.
first drop down list will have three items
select country (as selected)
USA
CAN
second drop down list will be empty and it reload by using ajax only if you select a country ( USA - CAN )
else second down list will return empty again
With such a small amount of data, it doesn't really even need to be an Ajax call to fetch the state/province list. Just simply load them into the page as a JSON object and swap the list.
This is a rough draft, not finished or polished code:
<script src="path/to/jquery.js"></script>
<script>
var stateMap = {
"USA": [ { "AL" : "AL"} .....],
"CAN": [ { "AB" : "AB" }, .... ]
};
function setStates(country) {
var newOptions = stateMap[country];
var states = $('#states');
states.empty();
$.each(newOptions, function(key, value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
}
}
// initialise on document load...
$(function() {
setStates( "USA");
});
// set state list on country change....
$('#country').change( function() {
var country = $( this ).val();
setStates( country);
}
</script>
<body>
<select id="country">
<option value="USA">USA</option>
<option value="CAN">Canada</option>
</select>
<select id="states">
</select>
</body>
I have an inc file (test_form4.inc) which defines the form that collects a user's name and phone number.
<!doctype html>
<?php
/* Program name: form_test4.inc
* Description: Defines a form that collects a user's
* name and phone number.
*/
$labels = array( "first_name" => "First Name",
"middle_name" => "Middle Name",
"last_name" => "Last Name",
"phone" => "Phone");
$radios = array( "New", "Changed");
$submit = "Submit Phone Number";
?>
<html>
<head>
<title>Form 2</title>
<style type='text/css'>
<!--
form {
margin: 1.5em 0 0 0;
padding: 0;
}
.field {padding-bottom: 1em;}
label {
font-weight: bold;
float: left;
width: 20%;
margin-right: 1em;
text-align: right;
}
.submit {
margin-left: 35%;
}
-->
</style>
</head>
<body>
<h3>Please enter your phone number below</h3>
<?php
/* loop that displays the form */
echo "<form action='$_SERVER[PHP_SELF]' method='POST'>";
foreach($labels as $field => $label)
{
echo "<div class='field'><label for='$field'>$label</label>
<input id='$field' name='$field' type='text' value='".#$$field."'
size='50%' maxlength='65' /></div>\n";
}
echo "<div class='field'>
<input type='radio' name='status' checked='checked'
value='new' style='margin-left: 25%'/>$radios[0]
<input type='radio' name='status'
value='changed' style='margin-left: 1em' />$radios[1]</div>\n";
echo "<div><input type='hidden' name='submitted' value='yes' /></div>\n";
echo "<div class='submit'>
<input type='submit' name='phoneButton' value='$submit'></div>";
?>
</form>
</body>
</html>
... and a php file which checks for blanks or validates the form called (checkBlankOnly2.php)
<?php
/* Program name: checkBlankOnly_2.php
* Description: Program displays the blank form and checks
* all the form fields for blank fields.
*/
if(isset($_POST['submitted']) and $_POST['submitted'] == "yes")
{
foreach($_POST as $field => $value)
{
if(empty($value))
{
if($field != "middle_name")
{
$blank_array[] = $field;
}
}
else
{
$good_data[$field] = strip_tags(trim($value));
}
}
if(#sizeof($blank_array) > 0)
{
$message = "<p style='color: red; margin-bottom: 0;
font-weight: bold'>
You didn't fill in one or more required fields.
You must enter:
<ul style='color: red; margin-top: 0;
list-style: none' >";
/* display list of missing information */
foreach($blank_array as $value)
{
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($good_data);
include("form_test4.inc");
exit();
}
foreach($_POST as $field => $value)
{
if(!empty($value))
{
$name_patt = "/^[A-Za-z' -]{1,50}$/";
$phone_patt = "/^[0-9)(xX -]{7,20}$/";
$radio_patt = "/(new|changed)/";
if(preg_match("/name/i",$field))
{
if(!preg_match($name_patt,$value))
{
$error_array[] = "$value is not a valid name";
}
}
if(preg_match("/phone/i",$field))
{
if(!preg_match($phone_patt,$value))
{
$error_array[] = "$value is not a valid phone number";
}
} // endif phone format check
if(preg_match("/status/i",$field))
{
if(!preg_match($radio_patt,$value))
{
$error_array[] = "$value is not a valid status";
}
}
}
$clean_data[$field] = strip_tags(trim($value));
}
if(#sizeof($error_array) > 0)
{
$message = "<ul style='color: red; list-style: none' >";
foreach($error_array as $value)
{
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($clean_data);
include("form_test4.inc");
exit();
}
else
{
echo "Data is all okay";
}
}
else
{
include("form_test4.inc");
}
?>
I can not figure out where my error comes, which I'm certain the problem is with the phone number. My lesson said that the phone number preg_match is for the numbers formats 555-5555 or (888) 555-5555, still when I insert all my data like: first name, last name and phone number in these formats I got the error "not a valid phone number".
Please help me, I can't figure it out.
Thanks.
The field phoneButton is seen as a phone number because it passes your condition if (preg_match("/phone/i",$field)), it's value "Submit Phone Number" then gets validated as a phone number, thus generating the error "Submit Phone Number is not a valid phone number".
Rename your "phoneButton" field to, for example, "submitButton" and you should be fine.
Replace
$phone_patt = "/^[0-9)(xX -]{7,20}$/";
with
$phone_patt = "/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/";
I have two rank in my forum Admin = 1 and User = 0 Then this code is doing so the admin get red name.
if($info['rank'] == 1) { $x= "<a class='admin'>".$last_user."</a>";
} else { $x= "<a class='user'>".$last_user."</a>"; }
But everyone is getting red name..
use the $x where you want to wish.
<?PHP
if (mysql_num_rows($res) > 0) {
while ($row = mysql_fetch_assoc($res)) {
if($info[rank] == 1) { $x= "<div class='admin'>".$last_user."</div>"; } else { $x="<div>".$last_user."</div>"; }
$tid = $row['id'];
$cid = $row['category_id'];
$title = $row['topic_title'];
$views = $row['topic_views'];
$date = $row['topic_date'];
$creator = $row['topic_creator'];
if ($row['topic_last_user']== "") { $last_user = getusername($row['topic_creator']); } else { $last_user = getusername($row['topic_last_user']); }
if ($row['topic_last_user']== "") { $last2_user = 'Started by'; } else { $last2_user = 'Most recent by'; }
$topics .="
<li class='category'><div class='left_cat'>
<a class='underline' href='view_topic.php?cid=".$cid."&tid=".$tid."'>
<div class='title'><i class='icon-comment'></i> ".$title."</div></a>
<div class='info'><i class='icon-comments icon-1'></i> ".topicreplies($cid, $tid)." Comments <i class='icon-user icon-1'>
</i>".$last2_user."
$x
<i class='icon-calendar'> </i> ".convertdate($date)."</div>
</div>";
$topics .= "<div class='right_cat'>
<div class='face'>
<img class='img_face' src='https://minotar.net/avatar/".getusername($creator)."/40.png'></div>
<div class='comments_cat'>
<div class='comments_top'>Comments</div>
<div class='comments'>".topicreplies($cid, $tid)."</div></div>
<div class='views_cat'>
<div class='views_top'>Views</div>
<div class='views'>".$views."</div></div>
</div></li>";
}
echo $topics;
} else {
echo "<div class='alert alert-danger text5'>There are no topics available yet.</div>";
}
?>
I have make the variable for you in the top.
Hope it work
if (mysql_num_rows($res) > 0) {
while ($row = mysql_fetch_assoc($res)) {
$tid = $row['id'];
$cid = $row['category_id'];
$title = $row['topic_title'];
$views = $row['topic_views'];
$date = $row['topic_date'];
$creator = $row['topic_creator'];
if ($row['topic_last_user']== "") { $last_user = getusername($row['topic_creator']); } else { $last_user = getusername($row['topic_last_user']); }
if ($row['topic_last_user']== "") { $last2_user = 'Started by'; } else { $last2_user = 'Most recent by'; }
$topics .= "<li class='category'><div class='left_cat'>
<a class='underline' href='view_topic.php?cid=".$cid."&tid=".$tid."'><div class='title'><i class='icon-comment'></i> ".$title."</div></a>
<div class='info'><i class='icon-comments icon-1'></i> ".topicreplies($cid, $tid)." Comments <i class='icon-user icon-1'>
</i>".$last2_user." ";
Syntax error is there at last line i.e ".$last2_user."
Just close the quote at " ";
This will solve your problem.
It looks like you are trying to insert an if statement inside the string you are creating. You can't do that as far as I know. However, the solution is easy. You end the string, insert your if statement, then append the rest of what you wanted. Like this:
if (mysql_num_rows($res) > 0) {
while ($row = mysql_fetch_assoc($res))
{
$tid = $row['id'];
$cid = $row['category_id'];
$title = $row['topic_title'];
$views = $row['topic_views'];
$date = $row['topic_date'];
$creator = $row['topic_creator'];
if ($row['topic_last_user']== "")
{ $last_user = getusername($row['topic_creator']); }
else
{ $last_user = getusername($row['topic_last_user']); }
if ($row['topic_last_user']== "")
{ $last2_user = 'Started by'; }
else
{ $last2_user = 'Most recent by'; }
$topics .= "<li class='category'><div class='left_cat'>
<a class='underline' href='view_topic.php?cid=".$cid."&tid=".$tid."'>
<div class='title'><i class='icon-comment'></i> ".$title."</div></a>
<div class='info'>
<i class='icon-comments icon-1'></i> ".topicreplies($cid, $tid)."
Comments <i class='icon-user icon-1'>
</i>".$last2_user." ";
// The string above is ended - and you insert your if statement.
// I changed the echo to an append to the string btw.
if ($info['rank'] == 1) { $topics .= "<div class='admin'>".$last_user."</div>"; } else { $topics .= "<div>".$last_user."</div>"; }
// Now you get to continue appending to the string.
$topics .= " <i class='icon-calendar'> </i> ".convertdate($date)."</div>
</div>";
$topics .= "<div class='right_cat'>
<div class='face'>
<img class='img_face' src='https://minotar.net/avatar/".getusername($creator)."/40.png'></div>
<div class='comments_cat'>
<div class='comments_top'>Comments</div>
<div class='comments'>".topicreplies($cid, $tid)."</div></div>
<div class='views_cat'>
<div class='views_top'>Views</div>
<div class='views'>".$views."</div></div>
</div></li>";
}
echo $topics;
} else {
echo "<div class='alert alert-danger text5'>There are no topics available yet.</div>";
}
The following code is what I have in the example provided above, and Here
<style type="text/css">
.user { font-weight:900; color: #000; text-decoration: none !important; }
.admin { font-weight:900; color: #F00; text-decoration: none !important; }
</style>
<form action="" method="POST">
Input number and press enter:
</br>User = 0 Admin = 1</br>
<input name="rank" id="rank" type="text" />
</form>
<?php
if (isset($_POST['rank'])) {
$info['rank'] = $_POST['rank'];
if($info['rank'] == 1) { $x= "<a class='admin'>Admin</a>"; }
else { $x= "<a class='user'>User</a>"; }
echo $x;
}
?>
As I mentioned in my comment above your code works fine, unless there is something going on elsewhere that we cant see with what you have given us.
And without a form.
<style type="text/css">
.user { font-weight:900; color: #000; text-decoration: none !important; }
.admin { font-weight:900; color: #F00; text-decoration: none !important; }
</style>
<?php
$info['rank'] = 1;
if($info['rank'] == 1) { $x= "<a class='admin'>Admin</a>"; }
else { $x= "<a class='user'>User</a>"; }
echo $x;
?>