I am working on a school project for php I have 2 files, checkBlank.php and form.php. everything displays correctly and its submitting the form well, but its not displaying the echo $message for fields that were not filled in.
Here is the code:
if(isset($_POST['submitted']) and $_POST['submitted'] == 'yes') {
foreach($_POST as $field => $value) {
if(empty($value)) {
$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 have not filled in all the fields.
Please fill in the:
<ul style='color: red; margin-top: 0; list-style: none' >";
foreach($blank_array as $value) {
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($good_data);
include ("form.inc");
exit();
}
echo "All fields contain information";
}
else {
include("form.inc");
}
I have a php array that includes inputs for posting. It uses a counter for each array record, and this counter is applied to the name of the input to be used in performing some actions with the post - this is working great.
The issue is that I would like to keep the users' existing inputs and re-populate the input fields in the array if their post doesn't pass validation.
I have done this before with static fields, simply storing the post variable and echoing it in the "value" --- but I can't figure out how to do this when working with an array. Anyone have any ideas?
$counter = 0;
echo "<form method='post'>";
echo "<table class='mainlist' width='680'>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr height='60'>";
echo "<td class='mainlist'><input type=text name=options[$counter] autocomplete=off onclick='this.select()' class='txt'></td>";
echo "</tr>";
$counter = $counter + 1;
}
echo "</table>";
Full code per request:
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$userid = $_SESSION['login_user'];
$companyid = $_POST['companyid'];
$options = $_POST['options'];
$counter = $_POST['hiddencounter'];
$runningtotal=0;
$totaloptions = array_sum($options);
$result = mysqli_query($connection, "SELECT options_balance FROM user_options_balance WHERE user_id = '".$userid."'");
for ($i=0; $i<$counter; $i++)
{
if(empty($options[$i]))
{ /* IF NO INPUT ON OPTIONS */
/* DO NOTHING */
}
else
{
$checknewcompanies = mysqli_query($connection, "SELECT company_id FROM user_company_total_invested WHERE user_id = '".$userid."' and company_id = '" .$companyid[$i]."'");
if($checknewcompanies->num_rows == 1)
{ // do nothing
}
else
{
$runningtotal = $runningtotal + 1;
}
} /* END OF ELSE IF NOT EMPTY OPTIONS */
} /* END OF FOR LOOP */
$checkcurrentcompanies = mysqli_query($connection, "SELECT company_id FROM user_company_total_invested WHERE user_id = '".$userid."'");
$countcompanies = $checkcurrentcompanies->num_rows;
$countcheck = $runningtotal + $countcompanies;
if($countcheck <= 4)
{
while($row = mysqli_fetch_array($result))
{
$balance = $row['options_balance'];
}
if ($totaloptions>$balance)
{
$notenoughoptions= "<div style='background-color:#FF0000; border-radius: 15px; padding: 10px; color: #FFFFFF; font-size: 12px;'>Oops! You don't have enough options! Try investing less!</div>";
}
else
{
// loop through array
for ($i=0; $i<$counter; $i++)
{
if(empty($options[$i])){ /* IF NO INPUT ON OPTIONS */
/* DO NOTHING */
}
else {
if(!ctype_digit($options[$i]) or !is_numeric($options[$i])){
$charactercheck= "<div style='background-color:#FF0000; border-radius: 15px; padding: 10px; color: #FFFFFF; font-size: 12px;'>Oops! Please enter only positive numbers to invest!</div>";
}
else {
$checkcompanies = mysqli_query($connection, "SELECT company_id FROM company_main WHERE company_id = '".$companyid[$i]."'");
if($checkcompanies->num_rows != 1)
{
$companynotexist= "<div style='background-color:#FF0000; border-radius: 15px; padding: 10px; color: #FFFFFF; font-size: 12px;'>Oops! That company doesn't exist!</div>";
}
else
{
// loop through array
for ($i=0; $i<$counter; $i++)
{
if(empty($options[$i]))
{ /* IF NO INPUT ON OPTIONS */
/* DO NOTHING */
}
else
{
$query = "INSERT INTO user_company_invested(user_id, company_id, user_company_options_invested)
VALUES($userid,$companyid[$i],$options[$i])";
mysqli_query($connection, $query);
} /* END OF ELSE IF NOT EMPTY OPTIONS */
} /* END OF FOR LOOP */
$balancecheck = mysqli_query($connection, "SELECT options_balance FROM user_options_balance WHERE user_id = '".$userid."'");
while($row = mysqli_fetch_array($balancecheck))
{
$balance2 = $row['options_balance'];
}
if($balance2 > 0)
{
header('Location: user_invest.php');
}
else
{
header('Location: user_market.php');
}
} // end company check
} //end character check
} //end empty option check
} //end loop
} /* END OF NOT ENOUGH OPTIONS CHECK */
}
else
{
$toomanycompanies = "<div style='background-color:#FF0000; border-radius: 15px; padding: 10px; color: #FFFFFF; font-size: 12px;'>Oops! You can invest in a maximum of 4 companies per week. Please choose fewer companies, or invest more in some of your existing companies!</div>";
/* echo "Maximum number of companies you can invest in is 4";
echo "<br />";
echo "Companies you already are invested in: ".$countcompanies;
echo "<br />";
echo "New companies you are trying to invest in: ".$runningtotal;
echo "<br />";
echo "Total: ".$countcheck;*/
}
} /* END OF ISSET CHECK */
else
{
}
?>
<?php
$result = mysqli_query($connection,"SELECT * from company_main");
$counter=0;
echo "<form method='post'>";
echo "<table class='mainlist' width='680'>";
while($row = mysqli_fetch_array($result))
{
echo "<tr height='60'>";
echo "<td class='mainlist' width=140 align='center'>" . "<img src='".$row['company_logo']."' width='40'/>" . "</td>";
echo "<td class='mainlist' align='left' width=390 style='font-size: 15px;'>" . $row['company_name'] . "</td>";
echo "<input type=hidden name=companyid[$counter] value=" . $row['company_id'] . " />";
echo "<td class='mainlist'><input value='{$_POST['options[$counter]']}' type=text name=options[$counter] autocomplete=off onclick='this.select()' class='txt' style=' background-color: #FCFCFC;
border: solid 1px #CCCCCC;
font-size: 12px;
padding: 5px;
height: 20px;
text-align: right;'></td>";
echo "</tr>";
$counter=$counter+1;
}
echo "</table>";
echo "<input type='hidden' name='hiddencounter' value='$counter'>";
echo "
<table>
<tr>
<td width='630' height='50'></td>
<td align='right' width='60' style='color: #848580; font-size: 20px;'>Total: </td>
<td align='right' width='40' style='color: #94D90B; font-size: 20px; font-weight: bold; padding-right:20px;'><span id='sum'>0</span></td><td width='10'></td>
</tr><tr height='20px'></tr><tr>
<td width='570' align='center' style='color: #94D90B; font-size: 12px;'>";?>
<?php echo $notenoughoptions; ?>
<?php echo $charactercheck; ?>
<?php echo $toomanycompanies; ?>
<?php echo "
</td>
<td colspan='2' width='100' align='right'><input name='userinvestoptionsdynamic' type='submit' value='Invest!'></td><td width='10'></td>
</tr>
<tr height='20px'></tr>
</table>";
echo "</form>";
?>
The correct syntax is:
echo "{$arrayname($keyname)}";
So for example echo('value=' . $_POST['options'][$counter]); becomes:
echo "value={$_POST['options'][$counter]}";
I made some little translator.
And if word exist in database all is ok. But if word didnt exist in database, word isnt printed. I add some code to print if result is empty but didnt work.
Any idea why word that not exist in database isnt printed?
Here is code:
<p><form method="post" action="prevedi.php">
<textarea id="prevedi" name="prevedi" style="margin: 2px; height: 137px; width: 380px;">
<?php
echo htmlentities($_POST['prevedi']);
?>
</textarea>
<textarea id="prevod" disabled="disabled" name="prevod" style="margin: 2px; height: 137px; width: 380px; border: 0px;" readonly>
<?
if (isset($_POST['prevedi'])) {
//Kreci
$prevedi = htmlentities($_POST['prevedi']);
$prevedi = explode(" ",$prevedi);
foreach ($prevedi as $word) {
$slovo = $word[0];
$result = mysqli_query($con,"SELECT * FROM $slovo WHERE srpski='$word'");
if (!empty($result)) {
while($row = mysqli_fetch_array($result))
{
$prevod .= $row['romski']." ";
}
}
else
{
$prevod .= "".$word." ";
}
}
echo $prevod;
//Kraj isset
}
?>
</textarea><br>
<input name="translate" type="submit" value="Translate"/>
</form>
</p>
Because your result is not empty. You should check if $result number of rows is > 0
if ($result->num_rows > 0) {
while($row = mysqli_fetch_array($result)){
$prevod .= $row['romski']." ";
}
}else{
$prevod .= $word." ";
}
i think you have to initialize $prevod before assigning it the way you did.
$prevod = "";
if (!empty($result)) {
while($row = mysqli_fetch_array($result))
{
$prevod .= $row['romski']." ";
}`enter code here`
}
else
{
$prevod .= "".$word." ";
}
}
echo $prevod;
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}$/";