I am trying to display all of the years from current year back to the user's birth year.
Instead of displaying all of the years in one line it prints the user's info multiple times depending on how many years it needs to go back.
if($_POST['Name'] == NULL || $_POST['Year'] == NULL || $_POST['Address'] == NULL ){
printf("<br><div style='color:red'>Please enter the required fields</div><br>");
} else {
$name = $_POST['Name'];
$year = $_POST['Year'];
$address = $_POST['Address'];
$state = $_POST['State'];
$sex = $_POST['Sex'];
for ($nYear = $year; $nYear <= date('Y'); $nYear++) {
if($sex == "Male"){
printf("<div style='background-color:#A9D0F5'>"
."Name: $name<br>"
."Year: $nYear<br>"
."Address: $address<br>"
."State: $state<br>"
."Sex: $sex<br>"
."</div>");
}else if($sex == "Female"){
printf("<div style='background-color:#F5A9F2'>"
."Name: $name<br>"
."Age: $age<br>"
."Address: $address<br>"
."State: $state<br>"
."Sex: $sex<br>"
."</div>");
}
}
}
Try putting float left in the containing div.
You are printing for every iteration of the loop. If you want to just print all the lines together, concatenate a string in the loop and print the built string after the loop has finished.
I used GET instead of POST in my example for easy testing, replace accordingly.
<?php
if(!isset($_GET['Name']) || !isset($_GET['Year']) || !isset($_GET['Address'])){
printf("<br><div style='color:red'>Please enter the required fields</div> <br>");
}
else {
$name = $_GET['Name'];
$year = $_GET['Year'];
$address = $_GET['Address'];
$state = $_GET['State'];
$sex = $_GET['Sex'];
$yearsText = '';
for ($nYear = $year; $nYear <= date('Y'); $nYear++) {
$yearsText .= $nYear . ' ';
}
$yearsText = trim($yearsText);
echo $yearsText;
}
?>
Bear with me on this. It sounds like you want to have an output like this on the page:
name: john name: john name: john
year: 2014 year: 2015 year: 2016
... ... ...
But instead you're getting something like this:
name: john
year: 2014
...
name: john
year: 2015
...
name: john
year: 2016
...
If that's the case then you've got a couple options. In both cases you're going to need to use CSS. Option one is to use a css tag.
...
echo "<style>.info {
float: left;
padding: 10px;
background: #A9D0F5;
#some other stuff to make it pretty
} </style>";
for ($nYear = $year; $nYear <= date('Y'); $nYear++) {
if($sex == "Male"){
printf("<div class='info'>
...
or you could just throw it inline with your other stylings:
...
printf("<div style='background-color:#A9D0F5; float: left; padding: 10px;'>"
...