How can I change an array value with a click? - php

I've seen references to Ajax for this, but I'm not entirely sure how I could integrate that with the arrays and still have a functioning system. I want to change the value of $place and $title each time a user presses the button, and I know that I'll need an if statement and some way of processing a form (no clicks in PHP), but I don't know anything else beyond that. I've pasted my PHP and the HTML button below:
<!DOCTYPE html>
<html>
<head>
<title>StatsCalc V1</title>
<link rel="stylesheet" type="text/css" href="sheen.css">
<link rel="script" type="text/javascript" href="slide.js">
<link rel="icon" type="image/png" href="favicon.ico">
<link href='http://fonts.googleapis.com/css?family=Raleway:500' rel='stylesheet' type='text/css'>
</head>
<body>
<?php
$place = 0;
$title = 0;
echo '<div class="boxes"><h1>Statistics Calculator: Version 1</h1></div>';
$links = array('<div class="fancyBoxes"><img class="mainPic" src="normalDist.svg" alt="a normal distribution, courtesy openclipart.org"></div>', "", "");
echo $links[$place];
/*if($_GET){
if(isset($_GET['clickies'])){
$place = 1;
$title = 1;
}
}*/
if($_POST['clickies'] and $_SERVER['REQUEST_METHOD'] == "POST"){
$place = 1;
$title = 1;
}
$subtitle = array('<div class="boxes"><h1>Standardised Score</h1></div>', '<div class="boxes"><h1>Standard Deviation</h1></div>', '<div class="boxes"><h1>Averages</h1></div>');
echo $subtitle[$title];
?>
<input type="submit" id="clickies" name="clickies" value="" />
<script src="move.js"></script>
<script src="slide.js"></script>
<script src="jquery-1.11.2.js"></script>
<!--The calculator must be able to field standardised score, standard deviation, and averages (mean/median/mode)-->
<!--Headings will be assigned with an array; slides will be navigated with tabs on either side of the window-->
<!--Credit to https://openclipart.org/detail/171055/normal-distn-shaded-outside-1s-by-oderwald-171055 for the Standardised Score image/label thingy-->
</body>
</html>

maybe this could give you idea on how to do it.
if($_SERVER['REQUEST_METHOD'] == "POST") {
if (isset($_POST['clickies'])) {
$count = intval($_POST['count']);
$count++;
$place = $count;
$title = $count;
}
} else {
$place = 0;
$title = 0;
}
echo '<div class="boxes"><h1>Statistics Calculator: Version 1</h1></div>';
$links = array('<div class="fancyBoxes"><img class="mainPic" src="normalDist.svg" alt="a normal distribution, courtesy openclipart.org"></div>', "", "");
echo $links[$place];
echo $place; echo "<br/>";
$subtitle = array('<div class="boxes"><h1>Standardised Score</h1></div>', '<div class="boxes"><h1>Standard Deviation</h1></div>', '<div class="boxes"><h1>Averages</h1></div>');
echo $subtitle[$title];
?>
<form action="" method="POST">
<input type="submit" id="clickies" name="clickies" value="" />
<input type="hidden" id="count" name="count" value="<?php echo $place;?>" />
</form>
what I did is need to put the button inside a form and put a method= post
and make it submit it to the same page
i also store the count in a hidden input and pass it always when the form is submitted and update its value on the form,
try to modify according to your need

<?php
$_SESSION["place"] = 0;
$place = 0;
$title = 0;
session_start();
echo '<div class="boxes"><h1>Statistics Calculator: Version 1</h1></div>';
$links = array('<div class="fancyBoxes"><img class="mainPic" src="normalDist.svg" alt="a normal distribution, courtesy openclipart.org"> </div>', "", "");
if($_POST['clickies'] and $_SERVER['REQUEST_METHOD'] == "POST"){
$_SESSION["place"] = $_SESSION["place"] + 1;
$title = 1;
}
echo $links[$_SESSION["place"]];
$subtitle = array('<div class="boxes"><h1>Standardised Score</h1></div>', '<div class="boxes"><h1>Standard Deviation</h1></div>', '<div class="boxes"><h1>Averages</h1></div>');
echo $subtitle[$title];
?>
<form method="post" action="">
<input type="submit" id="clickies" name="clickies" value="submit" />
</form>
you can use session of php.

Related

PHP Quiz not working properly

I'm trying to make a simple php quiz,but instead of choices I have to insert answers and compare them with strcasecmp() so it won't be a problem if the first letter is uppercase or anything like that,but the code doesn't work properly.Sometimes it doesn't return the correct result,even though I insert the correct answer.
Here is the code:
<?php
$number = rand(1,2);
$result = "";
$answer = "";
$question = "";
$question1 = "What is the capital of China";
$question2 = "What king of country is China?";
$answer1 = "beijing";
$answer2 = "republic";
if ($number == 1) {
$answer = $answer1;
$question = $question1;
}
if ($number == 2) {
$answer = $answer2;
$question = $question2;
}
if(isset($_POST['submit'])){
if (strcasecmp($answer,$_POST['answer']) == 0) {
$result = "Correct!";
} else {
$result = "Wrong!";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form method="post" action="index.php">
<div class="middle">
<p class="question"><?php echo $question;
?></p>
<p class="result"><?php echo $result;
$result = "" ?></p>
<div class="box">
<input type="text" name="answer" placeholder="Type here" class="text">
</div>
</div>
<input type="submit" name="submit" value="Continue" class="btn">
</form>
</body>
</html>
By looking at your code, we can see that when you submit your form, you are restarting the script, which actually resets $random to a new value. With 2 questions, you have 50% chances to have the 'correct' answer, but you would see that your script doesn't work at all with more questions added.
Basically, you should use another way to achieve what you want. You could try to add the id of the question in an hidden <input> and check when your form is submit to determine which one it was.
if(isset($_POST['submit'])){
switch ($_POST['question']) { // Add '{'
case 1:
if (strcasecmp($answer1,$_POST['answer']) == 0) {
$result = "Correct!";
} else {
$result = "Gresit!";
}
break;
case 2:
if (strcasecmp($answer2,$_POST['answer']) == 0) {
$result = "Correct!";
} else {
$result = "Gresit!";
} // Forgot to Add '}'
break;
} // Add '}' It give error in PHP 5.3 Parse error: syntax error, unexpected T_CASE, expecting ':' or '{'
}
For the HTML, you could add this input in your form :
<input type="text" name="question" value="<?php echo $number ?>" hidden>
This is not the best way to achieve what you want, this is just an example of what would work.

Counter not increasing more than one time

I wanted to make specific letter counter, but my counter is not increasing more that once. Can some one explain what i'm doing wrong?
Here is my code:
PHP:
<?php
$count_s = 0;
$count_v = 0;
$input = '';
if(filter_has_var(INPUT_POST, 'submit')) {
if($_SERVER["REQUEST_METHOD"] == "POST") {
$input = $_POST['inp'];
switch($input) {
case 'v':
$count_v++;
case 's':
$count_s++;
}
}
}
?>
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h3>Enter Symbol: </h3>
<form action="index.php" method="POST">
<input type="text" class="input" name='inp' maxlength="1" >
<button class="btn" type="submit" name="submit">Submit</button>
</form>
<div class="output">
<?php
echo "Count of letter 'V': ".$count_v."<br/>";
echo "Count of letter 'S': ".$count_s."<br/>";
?>
</div>
</body>
</html>
Try this it will be work perfectly. paste it in any test file. This will retain no of times you input v and no of times you input s, value of s and v will remain same of input some other value.
<?php
$input = '';
if(!isset($count_v))
{
$count_v=0;
}
if(!isset($count_s))
{
$count_s=0;
}
if (filter_has_var(INPUT_POST, 'submit'))
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$input = $_POST['inp'];
switch ($input)
{
case 'v':
$_POST['count_v']++;
$count_v=$_POST['count_v'];
$count_s=$_POST['count_s'];
break;
case 's':
$count_v=$_POST['count_v'];
$_POST['count_s']++;
$count_s=$_POST['count_s'];
break;
default:
$count_v=$_POST['count_v'];
$count_s=$_POST['count_s'];
break;
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h3>Enter Symbol: </h3>
<form method="POST">
<input type="hidden" name='count_v' value="<?php echo $count_v?>">
<input type="hidden" name='count_s' value="<?php echo $count_s?>">
<input type="text" class="input" name='inp' maxlength="1" >
<button class="btn" type="submit" name="submit">Submit</button>
</form>
<div class="output">
<?php
echo "Count of letter 'V': " . $count_v . "<br/>";
echo "Count of letter 'S': " . $count_s . "<br/>";
?>
</div>
</body>
</html>
you need to store counters in each request, because the variables lifetime is short (request life time), then they will be re-init from 0
to do this you can store the counters in file, database, or session
it depends on the time you want them to persist.
below is a sample for using session
** note the new line session_start(); you need to add it.
<?php
session_start();
$count_s = 0;
$count_v = 0;
$input = '';
if(filter_has_var(INPUT_POST, 'submit')) {
if($_SERVER["REQUEST_METHOD"] == "POST") {
$input = $_POST['inp'];
switch($input) {
case 'v':
if(!isset($_SESSION["count_v"])){
$_SESSION["count_v"] = 0;
}
$tmp = $_SESSION["count_v"];
$tmp++;
$_SESSION["count_v"] = $tmp;
break;
case 's':
if(!isset($_SESSION["count_s"])){
$_SESSION["count_s"] = 0;
}
$tmp = $_SESSION["count_s"];
$tmp++;
$_SESSION["count_s"] = $tmp;
break;
}
}
}
?>
and to read the values (in html page) use this:
<?php
echo "Count of letter 'V': ".$_SESSION["count_v"]."<br/>";
echo "Count of letter 'S': ".$_SESSION["count_s"]."<br/>";
?>
if you are going to store more than the 2 letters (s and v) then you can make the session key "count_v" generated dynamically using input itself. this will be a much less code, you will not need a switch/case
Edit: as i saw in your comment above, yes you can maintain counter values using hidden fields in HTML page, and use them to initialize the $count_s and $count_v instead of zero. you need to take care of first request when hidden values might be unset, or they could be zero

$_POST is empty when submitting a form

<html>
<head>
<!-- SCRIPTS -->
<script type="text/javascript" src="scripts/controller.js"></script>
<!-- STYLES -->
<link href="styles/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
$errUrl = $videoId = "";
$start = $end = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
print_r($_POST);
if (isset($_POST["yt_url"])) {
echo "hello2";
$videoId = youtube_parser($_POST['yt_url']);
}
if (!$videoId) {
$errUrl = "URL is not valid!";
$videoId = "";
} else {
$errUrl = "";
}
//$start = $_POST['startH'] * 3600 + $_POST['startM'] * 60 + $_POST['startS'] * 1;
//$end = $_POST['endH'] * 3600 + $_POST['endM'] * 60 + $_POST['endS'] * 1;
}
function youtube_parser($url) {
$regExp = '/^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$/';
$match = preg_match($regExp, $url, $matches);
return ($match && strlen($matches[5]) === 11)? $matches[5] : false;
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="left">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<span class="error">* <?php echo $errUrl; ?></span><br>
URL: <input type="text" name="yt_url">
<br><br>
Start Time:<br>
<span class="label">Hour: </span><input value="0" type="number" name="start_h"><br>
<span class="label">Minute: </span><input value="0" type="number" name="start_m"><br>
<span class="label">Second: </span><input value="0" type="number" name="start_s">
<br><br>
End Time:<br>
<span class="label">Hour: </span><input value="0" type="number" name="end_h"><br>
<span class="label">Minute: </span><input value="0" type="number" name="end_m"><br>
<span class="label">Second: </span><input value="0" type="number" name="end_s">
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</div>
<div class="player"><?php
if (isset($videoId) && !empty($videoId)) {
echo '<iframe width="560" height="315" src="https://www.youtube.com/embed/$videoId?start=$start&end=$end" frameborder="0" allowfullscreen></iframe>';
}
?></div>
</body>
</html>
The above is what I have so far. I am attempting to learn php, and I have been working through the tutorials on w3schools I got to the part about working with forms, and none of the information is being passed in the $_POST array, I have set names for all of my DOM controls. Any insight would be greatly appreciated! I have a feeling it my have something to do with my PHP setup as even the provided example doesn't work.
Additional Information:
Web server running through Intellij PHPStorm.
php version is 7.0.9
Your code looks valid and when I tried it it shows expected output from $_POST array:
So it looks like you got problems with environment you are testing it on.
BTW <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
is wrong. Aside from spaghetti code, you should not use htmlspecialchars() here but urlencode()
(yet I'd use nothing _SERVER['PHP_SELF'] cannot be spoofed by client).
Also as #CarlJan suggested you may want to use isset($_POST['submit']) to check if your form was submitted as this will condition will only be true if your submit button is sent via POST. For now you are checking if this is POST request (in general) but it is not the same as it can be post from other form, or triggered by hand.

How to put a delete button under each post in my blog/website?

I am wanting to put a delete button, so people can delete their post if they want on my simple blog website. I am just a little unsure how to do it. I guess I need to put a value=delete input field on my posting_wall but not sure where to go from there. Thank you in advnace if you can help me.
Form
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/index.css" />
<link type="text/css" rel="stylesheet" href="../css/footer.css" />
<link type="text/css" rel="stylesheet" href="../css/header.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
$('form').submit(function (e) {
var value;
// "message" pattern : from 3 to 150 alphanumerical chars
value = $('[name="message"]').val();
if (!/^[-\.a-zA-Z\s0-9]{3,150}$/.test(value)) {
alert('Sorry, only alphanumerical characters are allowed and 3-150 character limit".');
e.preventDefault();
return;
}
// "name" pattern : at least 1 digit
value = $('[name="name"]').val();
if (!/\d+/.test(value)) {
alert('Wrong value for "name".');
e.preventDefault();
return;
}
});
});
</script>
</head>
<body>
<?php include 'header.php' ?>
<form action="posting_wall.php" method="get">
<div id="container">
Name:<input type="text" name="name" pattern="[A-Za-z0-9]{3,15}" title="Letters and numbers only, length 3 to 15" required autofocus><br>
E-mail: <input type="email" name="email" maxlength="20" required><br>
Post:<br>
<textarea rows="15" cols="50" name='message'></textarea>
</div>
Date this event took place: <input type="text" name='date' id="datepicker" > <br>
<input type="reset" value="Reset">
<input type="submit">
</form>
<p>Posting Wall</p>
<div id="time">
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60secs
echo 'The time at which you are posting is:'. date('h:i Y-m-d') ."\n";
?>
</div>
<?php include 'footer.php' ?>
</body>
</html>
Posting Wall Page (where I want the delete button under each post)
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/post.css" />
<link type="text/css" rel="stylesheet" href="../css/footer.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
</head>
<body>
<h1>Daily Dorm News <br></h1>
<h2> Your Daily Dorm News Posts </h2>
<div id="container"> <?php if ( isset($_GET['name']) and preg_match("/^[A-Za-z0-9]+$/", $_GET['name']) ) {
echo $_GET['name'];
} else {
echo "You entered an invalid name!\n";
}
?><br>
Your email address is: <?php if ( isset($_GET['email']) and preg_match("/.+#.+\..+/i", $_GET['email']) ) {
echo $_GET['email'];
} else {
echo "You didn't enter a proper email address!\n";
}
?><br>
You Posted : <?php if ( isset($_GET['message']) and preg_match("/^[-\.a-zA-Z\s0-9]+$/", $_GET['message']) ) {
echo $_GET['message'];
} else {
echo "The message is not valid! The message box was blank or you entered invalid symbols!\n";
}
?>
<br>
This event happened :<?php echo $_GET["date"]; ?><br>
</div>
<?php
/* [INFO/CS 1300 Project 3] index.php
* Main page for our app.
* Shows all previous posts and highlights the current user's post, if any.
* Includes a link to form.php if user wishes to create and submit a post.
*/
require('wall_database.php');
// Fetching data from the request sent by form.php
$name = strip_tags($_REQUEST['name']);
$email = strip_tags($_REQUEST['email']);
$message = strip_tags($_REQUEST['message']);
$date = strip_tags($_REQUEST['date']);
$is_valid_post = true;
// Checking if a form was submitted
if (isset($_REQUEST['name'])){
// Fetching data from the request sent by form.php
$name = strip_tags($_REQUEST['name']);
$email = strip_tags($_REQUEST['email']);
$message = strip_tags($_REQUEST['message']);
$date = strip_tags($_REQUEST['date']);
// Saving the current post, if a form was submitted
$post_fields = array();
$post_fields['name'] = $name;
$post_fields['email'] = $email;
$post_fields['message'] = $message;
$post_fields['date'] = $date;
$success_flag = saveCurrentPost($post_fields);
}
//Fetching all posts from the database
$posts_array = getAllPosts();
?>
<?php
if(isset($name)) {
echo "<h3>Thanks ".$name." for submitting your post.</h3>";
}
?>
<p id="received">Here are all the posts we have received.</p>
<div id="logo">Dont Forget to tell you’re friends about Daily Dorm Post! <br>
The only Dorm News Website on campus!</div>
<ul id="posts_list">
<?php
// Looping through all the posts in posts_array
$counter = 1;
foreach(array_reverse($posts_array) as $post){
$alreadyPosted = false;
$name = $post['name'];
$email = $post['email'];
$message = $post['message'];
$date = $post['date'];
if ($counter % 2==1)
$li_class = "float-left";
else
$li_class = "float-right";
if ($name == $_GET['name']) {
$alreadyPosted = true;
}
echo '<div class=post';
if ($alreadyPosted) {
echo ' id="highlight"';
}
echo '>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.'</span> wrote a post.</h3></li>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.' email is: '.$email.'</span></h3></li>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.' wrote '.$message.'</span> wrote a post.</h3></li>';
echo '<li class="'.$li_class.'"><h3><span>This event occured on '.$date.'</span></h3></li>';
echo '</div>';
}
?>
</ul>
</div>
<p id="submit">Would you like to submit another post?</p>
<?php include 'footer.php' ?>
</body>
</html>
create a delete button or make
<script>
function confirm(){
var responce = confirm("Are you sure want to delete?");
if (responce==true)
{
return true;
}
else
{
return false;
}
}
</script>
<a onclick="confirm()" href="delete_post.php?id=1>">Delete</a>

Using Strip Tags and check for empty fields PHP

So i have a form here, and I want on the to do some php so that if the field is empty, it will say once you submit the form after it loads to the post page, that sorry you entered no date. I also want to add strip tags, however I am unsure how, if they go on the posting_wall or if they go in the form.php? I want to use strip all tags.
I believe the empty validation was if(!empty(($date)) { echo "sorry you did not enter a date"; } but i could not get it to work.
Thank you in advance if you can help me with this. I will post the form.php and the posting wall below.
Form.php
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/index.css" />
<link type="text/css" rel="stylesheet" href="../css/footer.css" />
<link type="text/css" rel="stylesheet" href="../css/header.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
$('form').submit(function (e) {
var value;
// "message" pattern : from 3 to 150 alphanumerical chars
value = $('[name="message"]').val();
if (!/^[-\.a-zA-Z\s0-9]{3,150}$/.test(value)) {
alert('Sorry, only alphanumerical characters are allowed and 3-150 character limit".');
e.preventDefault();
return;
}
// "name" pattern : at least 1 digit
value = $('[name="name"]').val();
if (!/\d+/.test(value)) {
alert('Wrong value for "name".');
e.preventDefault();
return;
}
});
});
</script>
</head>
<body>
<?php include 'header.php' ?>
<form action="index.php" method="get">
<div id="container">
Username:*<input type="text" name="name" pattern="{3,15}" title="Letters and numbers only, length 3 to 15" required autofocus><br>
E-mail:* <input type="email" name="email" maxlength="20" required><br>
Post:*<br>
<textarea rows="15" cols="50" name='message'></textarea>
</div>
Date this event took place: <input type="text" name='date' id="datepicker" > <br>
Your favorite website is: <input type="text" name="website">
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br>
<input type="reset" value="Reset">
<input type="submit">
</form>
<p> Fields with * next to them are required </p>
<p>Posting Wall</p>
<div id="time">
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60secs
echo 'The time at which you are posting is:'. date('h:i Y-m-d') ."\n";
?>
</div>
<?php include 'footer.php' ?>
</body>
</html>
Posting wall
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/post.css" />
<link type="text/css" rel="stylesheet" href="../css/heaader.css" />
<link type="text/css" rel="stylesheet" href="../css/footer.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
</head>
<body>
<h1>Daily Dorm News </h1>
<h2> You're best place for the latest dorm news from campus </h2>
<div id="container"> <?php if ( isset($_GET['name']) and preg_match("/^[A-Za-z0-9]+$/", $_GET['name']) ) {
echo $_GET['name'];
} else {
echo "You entered an invalid name!\n";
}
?><br>
Your email address is: <?php if ( isset($_GET['email']) and preg_match("/.+#.+\..+/i", $_GET['email']) ) {
echo $_GET['email'];
} else {
echo "You didn't enter a proper email address!\n";
}
?><br>
You Posted : <?php if ( isset($_GET['message']) and preg_match("/^[-\.a-zA-Z\s0-9]+$/", $_GET['message']) ) {
echo $_GET['message'];
} else {
echo "The message is not valid! The message box was blank or you entered invalid symbols!\n";
}
?>
This event happened :<?php echo $_GET["date"]; ?><br>
Your gender is:<?php echo $_GET["gender"]; ?><br>
Your favorite website is: <?php echo $_GET["website"]; ?><br>
</div>
<?php
/* [INFO/CS 1300 Project 3] index.php
* Main page for our app.
* Shows all previous posts and highlights the current user's post, if any.
* Includes a link to form.php if user wishes to create and submit a post.
*/
require('wall_database.php');
// Fetching data from the request sent by form.php
$name = strip_tags($_REQUEST['name']);
$email = strip_tags($_REQUEST['email']);
$message = strip_tags($_REQUEST['message']);
$date = strip_tags($_REQUEST['date']);
$gender = strip_tags($_REQUEST['gender']);
$website = strip_tags($_REQUEST['website']);
$is_valid_post = true;
// Checking if a form was submitted
if (isset($_REQUEST['name'])){
// Fetching data from the request sent by form.php
$name = strip_tags($_REQUEST['name']);
$email = strip_tags($_REQUEST['email']);
$message = strip_tags($_REQUEST['message']);
$date = strip_tags($_REQUEST['date']);
$gender = strip_tags($_REQUEST['gender']);
$website = strip_tags($_REQUEST['website']);
// Saving the current post, if a form was submitted
$post_fields = array();
$post_fields['name'] = $name;
$post_fields['email'] = $email;
$post_fields['message'] = $message;
$post_fields['date'] = $date;
$post_fields['gender'] = $gender;
$post_fields['website'] = $website;
$success_flag = saveCurrentPost($post_fields);
}
//Fetching all posts from the database
$posts_array = getAllPosts();
?>
<?php
if(isset($name)) {
echo "<h3>Thanks ".$name." for submitting your post.</h3>";
}
?>
<div id="logo"> Don't forget to tell all you're friends about Daily Dorm News! <br> The only dorm news website on campus!</div>
<p id="received">Here are all the posts we have received.</p>
<ul id="posts_list">
<?php
// Looping through all the posts in posts_array
$counter = 1;
foreach(array_reverse($posts_array) as $post){
$alreadyPosted = false;
$name = $post['name'];
$email = $post['email'];
$message = $post['message'];
$date = $post['date'];
$gender = $post['gender'];
$website = $post['website'];
if ($counter % 2==1)
$li_class = "float-left";
else
$li_class = "float-right";
if ($name == $_GET['name']) {
$alreadyPosted = true;
}
echo '<div class=post';
if ($alreadyPosted) {
echo ' id="highlight"';
}
echo '>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.'</span> wrote a post.</h3></li>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.' email is: '.$email.'</span></h3></li>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.' wrote '.$message.'</span> wrote a post.</h3></li>';
echo '<li class="'.$li_class.'"><h3><span>This event occured on '.$date.'</span></h3></li>';
echo '<li class="'.$li_class.'"><h3><span>Your a '.$gender.'</span></h3></li>';
echo '<li class="'.$li_class.'"><h3><span>You said your favorite website is '.$website.'</span></h3></li>';
echo '</div>';
}
?>
</ul>
</div>
<p id="submit">Would you like to submit another post?</p>
<?php require 'footer.php' ?>
</body>
</html>
You can check through jquery in the submit function
var datepicker=$("#datepicker").val();
if(datepicker=='') { alert('Please enter date'); return false; }
It should be
if(empty(($date)) {
echo "sorry you did not enter a date";
}
NOT
if(!empty(($date)) {
echo "sorry you did not enter a date";
}
The first expression will print "sorry you did not enter a date" if the date field is empty. The second expression will print that message if the date field is not empty.
You can try the code below. It will print 'This is an empty string'
<?php
$date = '';
if (empty($date)) {
echo 'This is an empty string';
}
if (!empty($date)) {
echo 'The date is ' . $date;
}

Categories