I want to be able to separate the birthday from the mysql data into day, year and month.
Using the 3 textbox in html. How do I separate it? I'm trying to think of what can I do with the code below to show the result that I want:
Here's the html form with the php code:
$idnum = mysql_real_escape_string($_POST['idnum']);
mysql_select_db("school", $con);
$result = mysql_query("SELECT * FROM student WHERE IDNO='$idnum'");
$month = mysql_real_escape_string($_POST['mm']);
?>
<?php while ( $row = mysql_fetch_array($result) ) { ?>
<tr>
<td width="30" height="35"><font size="2">Month:</td>
<td width="30"><input name="mo" type="text" id="mo" onkeypress="return handleEnter(this, event)" value="<?php echo $month = explode("-",$row['BIRTHDAY']);?>">
As you can see the column is the mysql database is called BIRTHDAY. With this format:
YYYY-MM-DD
How do I do it. So that the data from the single column will be divided into three parts?
Please help thanks,
You can use list and explode to get desired result
list($year,$month,$day)=explode("-", $row['birthday']);
hence $year contains year, $month contains month and $day contains Day, you can use it like this in your text boxes
<input name="mo" type="text" id="mo" value="<?php echo $month;?>">
<input name="dt" type="text" id="dt" value="<?php echo $day;?>">
<input name="yr" type="text" id="yr" value="<?php echo $year;?>">
$parts = explode('-', '1912-03-22');
$parts = split('-', '1912-03-22'); // could also use split()
echo 'Year: ' + $parts[0] . '<br />';
echo 'Month: ' + $parts[1] . '<br />';
echo 'Day: ' + $parts[2] . '<br />';
You could use php's explode function to split the date into its separate compoents:
$birthday ="1981-06-22";
list($year, $month, $day) = explode("-", $birthday);
echo "\nDay $day Month $month Year $year";
Related
i m trying to store checkbox values inside variable $days but when i store this value to database it just store the last selected checkbox inside the database... please help me to sort out the code so i can get all selected values
<?php
if (isset($_POST['days'])) {
foreach ($_POST['days'] as $day) {
$days = " " . $day;
}
} else {
$days = "not available";
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<tr>
<td>Select Days :</td>
<td>
<input type="checkbox" name="days[]" value="Sunday">Sunday
<input type="checkbox" name="days[]" value="Monday">Monday
<input type="checkbox" name="days[]" value="Tuesday">Tuesday
<input type="checkbox" name="days[]" value="Wednesday">Wednesday
<input type="checkbox" name="days[]" value="Thursday">Thursday
<input type="checkbox" name="days[]" value="Friday">Friday
<input type="checkbox" name="days[]" value="Saturday">Saturday
<input type="checkbox" name="days[]" value="All Days">All Days
</td>
<td></td>
You assign a normal string to $days and overwrite it on each iteration. You could append to it, by using the .= operator. ($days .= ' ' . $day), but maybe easier is to use implode:
if (isset($_POST['days'])) {
$days = implode(' ', $_POST['days']);
} else {
$days = "not available";
}
Note there is a small functional difference. implode will add spaces inbetween the days, while the foreach loop will also put a space at the start.
You overwrite $days with each iteration of the forech loop. Instead you want to add to it. Most likely this is what you are looking for:
if (isset($_POST['days'])) {
foreach ($_POST['days'] as $day) {
$days .= " " . $day;
}
} else {
$days = "not available";
}
If so, then you can even simplify the code and remove the loop:
if (isset($_POST['days'])) {
$days = implode(" ", $_POST['days']);
} else {
$days = "not available";
}
Use . to concatate the string
$days .= " " . $day;
You need to make $days as array and then push the values you get from checkbox into array.
$days[] = $day
inside your foreach statement
Please forgive me, I'm just beginning to study PHP, but I'm pretty well stuck on this sample project that my tutor gave me to figure out.
The goal is to first display the local time of 4 preset timezones, then allow for the user to enter a time manually and on submit, display the time for each of the 4 times relative to the time that was manually entered.
It's also important to do a check that the user input is valid and not just pass any input on regardless of what it may be.
Something is not correct with my IF statement and no input matches, but I haven't been able to see the issue..
Would appreciate if anyone could point me in the right direction. I've been reading thru the documentation on PHP.net quite extensively and have read thru everything on dateTime already but perhaps I'm just not putting it all together yet.
<?php
$timezones = array(
'EST' => -5*3600, //equador
'UTC' => 0, //london
'CCT' => +8*3600, //beijing
'PST' => -8*3600, //los angeles
);
foreach ($timezones as $time) {
$now = time();
$now += $time;
print gmstrftime('DATE: %B %d %Y and TIME: %r <br/>',$now);
}
$nowM = date('m');
$nowD = date('d');
$nowY = date('Y');
$nowHr = date('h');
$nowMin = date('i');
$nowSec = date('s');
?>
<form action="homework2.php" method="post">
<label>Sync Timecode</label>
<input type="text" name="month" placeholder="Month <?php $nowM ?>" value="<?php $nowM ?>" />
<input type="text" name="day" placeholder="Day <?php $nowD ?>" value="<?php $nowD ?>" />
<input type="text" name="year" placeholder="Year <?php $nowY ?>" value="<?php $nowY ?>" />
<input type="text" name="hour" placeholder="Hours <?php $nowHr ?>" value="<?php $nowHr ?>" />
<input type="text" name="min" placeholder="Minutes <?php $nowMin ?>" value="<?php $nowMin ?>"/>
<input type="text" name="sec" placeholder="Seconds<?php $nowSec ?>" value="<?php $nowSec ?>"/>
<input type="submit" id="button">
</form>
<?php
$format = 'd-m-Y h:i:s';
$queryTime = $_POST['day'] . "-" . $_POST['month'] . "-" . $_POST['year'] . " " . $_POST['hour'] . ":" . $_POST['min'] . ":" . $_POST['sec'];
if (date($format,strtotime($queryTime)) == $queryTime) {
$now = new DateTime(strtotime($queryTime), new DateTimeZone('America/Los_Angeles'));
} else {
echo "You entered:" . $queryTime . "<hr style='display:block;'>";
exit;
}
$timezones = array(
'EST' => new DateTimeZone('America/Panama'),
'UTC' => new DateTimeZone('Europe/London'),
'CCT' => new DateTimeZone('Asia/Hong_Kong'),
'PST' => new DateTimeZone('America/Los_Angeles'),
);
echo "You entered:" . $now->format($format) . "<hr style='display:block;'>";
foreach ($timezones as $zone) {
$now = new DateTime($now, new DateTimeZone($zone));
print "The time in" . $zone . "is" . $now->format($format) . "<br/>";
}
?>
your fault shall be forgiven :D
Seriously, I got your code working take a look at the result here:
http://sofia.bplaced.net/homework2.php
It wasn't THAT wrong.
I don't now how reliable this page is, but this shows every change i made:
http://www.diffchecker.com/cfdm0ppc
The new working code:
<?php
$timezones = array(
'EST' => -5*3600, //equador
'UTC' => 0, //london
'CCT' => +8*3600, //beijing
'PST' => -8*3600, //los angeles
);
foreach ($timezones as $time) {
$now = time();
$now += $time;
print gmstrftime('DATE: %B %d %Y and TIME: %r <br/>',$now);
}
$nowM = date('m');
$nowD = date('d');
$nowY = date('Y');
$nowHr = date('h');
$nowMin = date('i');
$nowSec = date('s');
?>
<form action="homework2.php" method="post">
<label>Sync Timecode</label>
<input type="text" name="month" placeholder="Month <?php $nowM ?>" value="<?php $nowM ?>" />
<input type="text" name="day" placeholder="Day <?php $nowD ?>" value="<?php $nowD ?>" />
<input type="text" name="year" placeholder="Year <?php $nowY ?>" value="<?php $nowY ?>" />
<input type="text" name="hour" placeholder="Hours <?php $nowHr ?>" value="<?php $nowHr ?>" />
<input type="text" name="min" placeholder="Minutes <?php $nowMin ?>" value="<?php $nowMin ?>"/>
<input type="text" name="sec" placeholder="Seconds<?php $nowSec ?>" value="<?php $nowSec ?>"/>
<input type="submit" id="button">
</form>
<?php
$format = 'd-m-Y H:i:s';
$queryTime = $_POST['day'] . "-" . date('m',strtotime($_POST['month'])) . "-" . $_POST['year'] . " " . $_POST['hour'] . ":" . $_POST['min'] . ":" . $_POST['sec'];
if (date($format,strtotime($queryTime)) == $queryTime) {
try {
$now = new DateTime(date("c",strtotime($queryTime)));
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}
} else {
echo "You entered: " . $queryTime . "<hr style='display:block;'>";
exit;
}
$timezones = array(
'EST' => 'America/Panama',
'UTC' => 'Europe/London',
'CCT' => 'Asia/Hong_Kong',
'PST' => 'America/Los_Angeles',
);
echo "You entered: " . $now->format($format) . "<hr style='display:block;'>";
foreach ($timezones as $zone) {
$now = new DateTime(date("c",strtotime($queryTime)));
date_timezone_set($now, timezone_open($zone));
echo "The time in " . $zone . " is " . $now->format($format." \G\M\TP") . "<br/>";
}
?>
I had to alter the following things:
Your IF-statement was wrong, you compared a 12h Value to a 24H value
line 35:
"h" to "H" //altered hour-format
I expected you wanted your user to enter a month like "April" and not like "04"
line 36:
"$_POST['month']" to "date('m',strtotime($_POST['month']))" //altered month-format
You should always fetch error-exeptions - this way your code may go on in case of an error
line 36:
altered to "try{...}"
line 41:
"You entered: " //added a spacer
line 45 ot 50:
modified the array as you tried to print these in line 56 and used them as parameter in 55
line 52:
"You entered: " //added a spacer
line 55:
"DateTime()" to "date_timezone_set()" //altered the command. The new cmd is part of the same function-set
line 56:
"print" to "echo" //I like uniform code
line 56(2 and 3):
"The time in " and "is " //added spacers
line 56(4):
" \G\M\TP" //relative time to GMT
you wrote something about "...display the time for each of the 4 times relative to the time that was manually entered."
"\G\M\T" will print as "GMT"
"P" will result in the time relative to GMT$
This should work for you.
Aiyion.Prime
I have a form that has radio inputs that have a dynamically generated name like below:
<input type="number" name="<?php echo date("Y")-4 ?>brand%gross" placeholder="Gross Sales % for <?php echo date("Y")-4 ?>">
<input type="number" name="<?php echo date("Y")-3 ?>brand%gross" placeholder="Gross Sales % for <?php echo date("Y")-3 ?>">
<input type="number" name="<?php echo date("Y")-2 ?>brand%gross" placeholder="Gross Sales % for <?php echo date("Y")-2 ?>">
<input type="number" name="<?php echo date("Y")-1 ?>brand%gross" placeholder="Gross Sales % for <?php echo date("Y")-1 ?>">
Then the form is processed and creates a dynamic table with all the values the user inputs that is then emailed to me. My question is how do I get dynamically generated radios to output to the table that is sent? I know the below isn't correct but just to give you a better look at what I'm trying to do:
if( isset($_POST) ){
${ echo date("Y")-4 } = $_POST['{ echo date("Y")-4 }];
Any help is greatly appreciated!
If you want to set a varible content inside $_POST, well... Use a variable.
$foo = date("Y")-4;
$_POST['str'] = $foo;
So... the thing is , you want to use a variable variable name that might go like this:
$foo = date("Y")-4;
$$foo = $_POST[$foo];
Got it?
EDIT 1:
So that the variable won't start with a number:
$bar = "dt_";
$foo = date("Y")-4;
${$bar.$foo} = $_POST[$foo];
By have a string (the output of date()) from which you subtract and integer, you end up casting the result as an integer, not a string. You are probably better off making the string correctly to begin with and getting rid of the integer arithmetic issue.
I would suggest working with DateTime objects. Here's how you might output you input fields.
<?php
$current_date = new DateTime();
while($i = 1; $i <= 4; $i++) {
$date_int = new DateInterval('P' . (string)$i . 'Y');
$temp_date = $current_date->sub($date_int);
$date_string = $temp_date->format('Y');
?>
<input type="number" name="<?php echo $date_string; ?>brand%gross" placeholder="Gross Sales % for <?php echo $date_string; ?>" />
<?php
} // end while
?>
When processing the $_POST you can do similar:
<?php
$current_date = new DateTime();
$year_array = array();
while($i = 1; $i <= 4; $i++) {
$date_int = new DateInterval('P' . (string)$i . 'Y');
$temp_date = $current_date->sub($date_int);
$date_string = $temp_date->format('Y');
if (!empty($_POST[$date_string. 'brand%gross'])) {
$year_array[$date_string] = $_POST[$date_string . 'brand%gross'];
}
} // end while
?>
Note that I use an array to store your data indexed by year string , as you can't have a variable name that starts with a number (i.e. $2013nrand%gross is not valid).
I would also STRONGLY suggest using array access notation in your inputs to simply things.
If you made each input like this:
<input type="number" name="year_brand_gross[<?php echo $date_string; ?>]" placeholder="Gross Sales % for <?php echo $date_string; ?>" />
Then the names of year_brand_gross[2013] and such would automatically get populated as an array into $_POST['year_brand_gross'], eliminating the need to loop through the POST input.
Instead you could set this to a variable like this
if(!empty($_POST['year_brand_gross']) {
$year_array = $_POST['year_brand_gross'];
}
For PHP < 5.3.0 you can use alternate method to generate the year strings:
$current_date = new DateTime();
for ($i = 1; $i <=4; $i++) {
$current_date->modify('-1 year');
$date_string = $current_date->format('Y');
// other code here
}
Note that, as shown, this will alter the value of $current_date with each iteratoin, which differs from the first solution.
First off you want to update you html so that the names of the fields
<input type="number" name="year[<?= date("Y")-4 ?>brand%gross]" placeholder="Gross Sales % for <?= date("Y")-4 ?>">
<input type="number" name="year[<?= date("Y")-3 ?>brand%gross]" placeholder="Gross Sales % for <?= date("Y")-3 ?>">
<input type="number" name="year[<?= date("Y")-2 ?>brand%gross]" placeholder="Gross Sales % for <?= date("Y")-2 ?>">
<input type="number" name="year[<?= date("Y")-1 ?>brand%gross]" placeholder="Gross Sales % for <?= date("Y")-1 ?>">
In your PHP you will be able to access the elements by there keys
$val2010 = $_POST["year"]["2010brand%gross"];
I have this piece of code which permits me to print multiple dates, so this is the form, which gets populated with dates separated by a comma, like 19/02/1990,12/12/1220 etc etc..
Now, what i need to do is to save them in an array and then print the array!
For the moment i have this code, could you please help me?
Thanks!
<form action="insert_date.php" method="post">
<div id="with-altField"></div>
<input type="text" id="altField" name="altField">
</div>
<input type="submit" value="Submit" />
</form>
This doesn't work if i select more than one date, but if i select one, it does, that's why i need to save it in an array form!
insert_date.php
<?php
$date=$_POST['altField'];
echo $date;
?>
$dates = explode(",", $_POST['altField']);
foreach($dates as $date){
echo htmlentities($date, ENT_QUOTES, 'utf-8') . '<br />';
}
Try This
<?php
$dates = $_POST['altField'];
$arrOfDates = explode(',', $dates);
var_dump($arrOfDates);
foreach($arrOfDates as $date)
{
echo $date;
}
?>
On insert_date.php you can explode by ,
<?php
$date=$_POST['altField'];
$explode = explode(',', $date);
?>
then you can use foreach to parse your dates
<?php
foreach($explode as $date){
echo trim($date);
}
?>
I've created a form that submits data to a MySQL database but the Date, Time, Year and Month fields constantly revert to the exact same date (1st January 1970) despite the fact that when I submit the information to the database the form displays the current date, time etc to me. I've already set it so that the time and date fields automatically display the current time and date. Could someone please help me with this.
Form:
<html>
<head>
<title>Ultan's Blog | New Post</title>
<link rel="stylesheet" href="css/newposts.css" type="text/css" />
</head>
<body>
<div class="new-form">
<div class="header">
<img src="images/edit-home-button.png">
</div>
<div class="form-bg">
<?php
if (isset($_POST['submit'])) {
$month = htmlspecialchars(strip_tags($_POST['month']));
$date = htmlspecialchars(strip_tags($_POST['date']));
$year = htmlspecialchars(strip_tags($_POST['year']));
$time = htmlspecialchars(strip_tags($_POST['time']));
$title = htmlspecialchars(strip_tags($_POST['title']));
$entry = $_POST['entry'];
$timestamp = strtotime($month . " " . $date . " " . $year . " " . $time);
$entry = nl2br($entry);
if (!get_magic_quotes_gpc()) {
$title = addslashes($title);
$entry = addslashes($entry);
}
mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('tmlblog');
$sql = "INSERT INTO php_blog (timestamp,title,entry) VALUES ('$timestamp','$title','$entry')";
$result = mysql_query($sql) or print("Can't insert into table php_blog.<br />" . $sql . "<br />" . mysql_error());
if ($result != false) {
print "<p class=\"success\">Your entry has successfully been entered into the blog. </p>";
}
mysql_close();
}
?>
<?php
$current_month = date("F");
$current_date = date("d");
$current_year = date("Y");
$current_time = date("H:i");
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="month" value="<?php echo $current_month; ?>" />
<input type="text" name="date" value="<?php echo $current_date; ?>" />
<input type="text" name="year" value="<?php echo $current_year; ?>" />
<input type="text" name="time" id="time" size="5"value="<?php echo $current_time; ?>" />
<input class="field2" type="text" id="title" value="Title Goes Here." name="title" size="40" />
<textarea class="textarea" cols="80" rows="20" name="entry" id="entry" class="field2"></textarea>
<input class="field" type="submit" name="submit" id="submit" value="Submit">
</form>
</div>
</div>
</div>
<div class="bottom"></div>
<!-- //End Wrapper!-->
</body>
</html>
</html>
For some reason the posts are being submitted without a timestamp and are reverting to a default timestamp.
Sounds like your form is giving your database a very low amount of "Ticks". Notice you have an with name="date" and id="date" three times. This is most likely your problem. Change those names and ids, do use month, year, date (according to your "postback").
You have three text boxes named date. Since $_POST['month'] and $_POST['year'] are not set, strtotime() cannot figure out the correct timestamp and the SQL query looks like this:
INSERT INTO php_blog (timestamp,title,entry) VALUES ('','Title Goes Here.','')
Change the names of the input elements to what your PHP code is expecting:
<input type="text" name="month" value="<?php echo $current_month; ?>" />
<input type="text" name="date" value="<?php echo $current_date; ?>" />
<input type="text" name="year" value="<?php echo $current_year; ?>" />
After you've done this, strtotime() will be able to parse the date and insert the correct value into the query.
INSERT INTO php_blog (timestamp,title,entry) VALUES ('1272738360','Title Goes Here.','')
It could be that strtotime fails to recognize the format you are submitting your date in.
Try a classic YYYY/MM/DD format:
$timestamp = strtotime("$year/$month/$date $time");
Looks like strtotime don't understand the format you feeding to it.
Use mktime instead.
Anyway you have to always debug your code, i.e. print out the query to see if anything goes wrong.
Or consider to use mysql-supported type colymn, date or datetime
You may be confused an unix timestamp which is just number ans mysql timestamp type column which is string of 2010-05-01 00:00:00