I want to do a search in my database base on date range.I can get a result in mysql console:
SELECT SUM(amount) as sum from serviceces where date_of_service between '2014-11-06' and '2014-111- 12';
//so in my form
<?php
include_once('../../libs/search/search_sales_by_date.php');
include_once('../../libs/search/total_sales.php');
?>
<?php error_reporting (E_ALL ^ E_NOTICE); ?>
<!Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>search by dates</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( ".datepicker" ).datepicker({ dateFormat: 'mm-dd-yy' });
});
</script>
</head>
<body>
<div>
<?php
if(isset($error)) {
echo $error;
}
if(isset($success)) {
echo $success;
}
?>
</div>
<h3>Search Sales</h3>
<p>From</p>
<form method="GET" action="search_sales_by_dates.php">
<p>Date: <input type="text" class="datepicker" name="from_date" id="field1"></p>
<p>To</p>
<p>Date: <input type="text" class="datepicker" name="to_date" id="field2"></p><br />
<input type="submit" value="search" name="submit" id="submitdata">
</form>
//search.php
<?php
//$total_by_date_range = "";
if(isset($_GET['submit'])) {
include_once('../../classes/class.ManageServices.php');
$init = new ManageServices();
$date_from = (isset($_GET['from_date']) ? $_GET['from_date'] : null);
$date_to = (isset($_GET['to_date']) ? $_GET['to_date'] : null);
if(empty($date_from) && empty($date_to)) {
$error = "No search query";
} elseif(empty($date_from) && !empty($date_to)) {
$error = "Specify your end date search";
} elseif(!empty($date_from) && empty($date_to)) {
$error ="Specify your start date search";
} else {
$total_by_date_range = 0;
$total_by_date_range = $init->getSumByDateRange($date_from, $date_to);
if($total_by_date_range== 1) {
$success ="Total calculated base on your search: ".$total_by_date_range;
} elseif (!$total_by_date_range) {
$error = "error";
} else {
$error = "Record not found due to some errors";
}
}
}
?>
//class.ManageServices.php
function getSumByDateRange($date_from, $date_to) {
$query = $this->link->query("SELECT SUM(amount) as sum_of_date_range FROM services WHERE
date_of_service between '".$date_from."' and '".$date_to."'");
$rowcount = $query->rowCount();
$result = $query->fetch();
return $result;
}
My problem is, if I do an echo $total_date_by_range in my form,it shows nothing ,doing a vardump($total_by_date_range) displays null.What's wrong with my code? Also I need to display the result on the same form. Any ideas on how to achieve this? I put at the top of form since it will display notice unidentified index.....everytime I submit the button.
Updates..
vardump($total_by_date_range) results in
array (size=1)
0 =>
array (size=2)
'sum_of_date_range' => null
0 => null
why does 'sum_of_date_range' null?
Related
Problem
index.php is a page that displays albums from a server hosted by MAMP using SQL. In grid.php I query the server and displays the albums in a grid. index.php also has a form in addalbum.php that allows the user to add an album to the database.
However, when the user submits the form in addalbum.php although the database gets updated, the page doesn't show the new data even though I do:
<form action="../p3/index.php" method="post">
I have to either refresh the page or click on it again to see the updated data. I'm confused as to why this is happening since I set the form action to index.php so it should refresh the page.
If anyone has some advice on that it would be greatly appreciated!
Code
index.php
<?php
$name = "Albums";
require_once('config.php');
require_once("nav.php");
require_once("php/header.php");
require_once("php/grid.php");
require_once("php/footer.php");
// require_once("../P3_M2/php/header.php");
// require_once("../P3_M2/php/grid.php");
// require_once("../P3_M2/php/footer.php");
require_once('php/login.php');
require_once('php/addalbum.php');
$error_log = addAlbumToDatabase();
foreach($error_log as $error){ //debuggin
echo "<h1>$error</h1>";
}
?>
config.php
<?php
define( 'DB_HOST', 'blahblahblah');
define('DB_NAME', 'blahblahblah');
define('DB_USER', 'blahblahblah');
define('DB_PASS','blahblahblah');
//Set up sqli
$mysqli = new mysqli( DB_HOST, DB_USER, DB_PASS, DB_NAME );
if ($mysqli->errno) { //Was there an error connecting to the database?
//The page isn't worth much without a db connection so display the error and quit
print($mysqli->error);
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>
<?php echo "$name" ?>
</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--Styling-->
<link type="text/css" rel="stylesheet" href="css/main.css" />
<link type="text/css" rel="stylesheet" href="css/grid.css" />
<link type="text/css" rel="stylesheet" href="css/form.css" />
<?php
$nameLowercased = strtolower($name);
echo "<link type='text/css' rel='stylesheet' href='css/$nameLowercased.css'/>";
?>
<!--Custom icon-->
<link href="https://file.myfontastic.com/fNQ9F99nd88vQm96ESUaLW/icons.css" rel="stylesheet" />
<!-- jQuery library -->
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!--Javascript-->
<script type="text/javascript" src="js/main.js"></script>
</head>
grid.php
<?php
/*DATA*/
//Query for each page
$queryFor = array(
'Albums' => 'SELECT * FROM Album;',
'Photos' => 'SELECT * FROM Image;',
'Album' => "SELECT * FROM Image WHERE id IN
(SELECT image_id FROM AIDict WHERE album_id = $album_id);"
);
//Loop through the $result rows fetching each one as an associative array
$printGridFor = array(
'Albums'=> function($row){
$albumId = $row['id'];
$albumTitle = $row['title'];
$albumDate = $row['date_created'];
$dateFormatted = date("F d, Y", strtotime($albumDate));
$creator = $row['creator'];
print("<div class='grid-square'>
<a href='album.php?id=$albumId'class='grid-info'>
<h1>$albumTitle</h1>
<h2>$dateFormatted</h2>
<h2>$creator</h2>
</a>
<button class='delete'><span class='icon-trash-can'></span></button>
<button class='edit''><span class='icon-pencil'></span></button>
</div>");
},
'Photos' => function($row){
$imgTitle = $row['title'];
$filename = $row['file_name'];
$filepath = $row['file_path'].$filename;
print("<div class='grid-square'>
<img src='$filepath' alt='$imgTitle ''>
<button class='delete'><span class='icon-trash-can'></span></button>
<button class='edit'><span class='icon-pencil'></span></button>
</div>");
},
'Album' => function($row){ //Same as 'Photos'
$imgTitle = $row['title'];
$filename = $row['file_name'];
$filepath = $row['file_path'].$filename;
print("<div class='grid-square'>
<img src='$filepath' alt='$imgTitle ''>
<button class='delete'><span class='icon-trash-can'></span></button>
<button class='edit'><span class='icon-pencil'></span></button>
</div>");
}
);
/*SQL*/
//Get the data
$query = $queryFor[$name];
$result = $mysqli->query($query);
if (!$result) { //If no result, print the error
print($mysqli->error);
exit();
}
?>
<div class="grid">
<?php
while ($row = $result->fetch_assoc()) {
$printGridFor[$name]($row);
}
?>
</div>
<button class="add"><span class="icon-plus"></span></button>
addalbum.php
<?php
function addAlbumToDatabase(){
$errors = array();
if(isset($_POST['submit'])){
global $mysqli;
$maxIdQuery = "SELECT MAX(id) FROM Album";
$maxIdResult = $mysqli->query($maxIdQuery);
if (!$maxIdResult) { print($mysqli->error); exit();} //If no result, print the error
if($row = $maxIdResult->fetch_row()){
$maxId = $row[0]; //Get max id
//Insert album into database
$stmt = $mysqli->prepare("INSERT INTO Album (id, title, date_created, date_modified, location, creator)
VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssss', $album_id, $title, $date_created, $date_modified, $location, $creator);
$album_id = $maxId + 1;
$title = (isset($_POST['album-title'])) ? $_POST['album-title'] : "Untitled";
date_default_timezone_set('America/New_York');
$todays_date = date('Y-m-d');
$date_created = (!empty($_POST['date-created'])) ? $_POST['date-created'] : $todays_date;
$date_modified = (!empty($_POST['date-modified'])) ? $_POST['date-modified'] : $date_created;
$location = (isset($_POST['location'])) ? $_POST['location'] : NULL;
$creator = (isset($_POST['creator'])) ? $_POST['creator'] : NULL;
$executed = $stmt->execute(); //execute statement
$stmt->close(); //close statement
if(!$executed){ //Add to error log
$errors[] = "Unsucceful when inserting $title into database";
$errors[] = $mysqli->error;
}
return $errors;
}
$errors[] = "$title not inserted into database";
return $errors;
}
$errors[] = "Nothing added b/c submit button not pressed";
return $errors;
}
?>
<div class="form-screen">
<button class="close close-form"><span class="icon-x"></span></button>
<form action="../p3/index.php" method="post">
<div class="form-wrapper">
<h1>Add Album</h1>
<input type="text" name="album-title" placeholder="Album Title*" required>
<input type="text" name="date-created" class="date" placeholder="Date Created">
<input type="text" name="date-modified" class="date" placeholder="Date Modified">
<input type="text" name="location" placeholder="Location">
<input type="text" name="creator" placeholder="Author*" required="">
<button type="submit" class="field submit" name="submit" value="submit">Create Album</button>
</div>
</form>
</div>
main.js
$(document).ready(function () {
//Show/Hide edit & delete buttons
$(".grid").on("mouseenter", ".grid-square", function () {
$(this).find(".delete").fadeIn(100);
$(this).find(".edit").fadeIn(100);
});
$(".grid").on("mouseleave", ".grid-square", function () {
$(this).find(".delete").fadeOut(100);
$(this).find(".edit").fadeOut(100);
});
//Show/Hide nav bar
$(".closeNavBtn").on("click", function () {
$(".sidenav").css("width", "0px");
});
$(".menu").on("click", function () {
$(".sidenav").css("width", "250px");
});
$(window).scroll(function (event) {
if ($(".sidenav").width() === 250) {
$(".sidenav").css("width", "0vw");
}
});
//Show/Hide login screen
$(".login").on("click", function () {
$(".login-screen").fadeIn(300);
});
$(".close-login").on("click", function () {
$(".login-screen").fadeOut(300);
});
//Show/Hide form screen
$(".add").on("click", function(){
$(".form-screen").fadeIn(300);
});
$(".close-form").on("click", function(){
$(".form-screen").fadeOut(300);
});
//Customize input label based on file
var input = document.querySelector('.inputfile');
if(input != null){customizeInputLabel(input);}
//Datepicker
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(".date").datepicker({
inline: true,
showOtherMonths: true, dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
});
});
//customizeInputLabel changes label when select file
function customizeInputLabel(input) {
var label = input.nextElementSibling
, labelVal = label.innerHTML;
input.addEventListener('change', function (e) {
var fileName = '';
if (this.files && this.files.length > 1) fileName = (this.getAttribute('data-multiple-caption') || '').replace('{count}', this.files.length);
else fileName = e.target.value.split('\\').pop();
if (fileName) label.querySelector('span').innerHTML = fileName;
else label.innerHTML = labelVal;
})
}
File directory structure
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>
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;
}
I am trying to cater to past users who have posted in the past. What I am trying to do is highlight any of the users pasts posts and also, on the home page do something like welcome back $name ! ONLY if the user has posted before though. I have no idea how to do this, need to check against the database probably but I am not sure how.
Thank you in advance.
The blogs form
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/index.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('Wrong value for "message".');
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>
<h1> <u>Daily Dorm News</u> <br> The best place to get your latest Dorm news </h1>
<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" required> <br>
<input type="reset" value="Reset">
<input type="submit">
</form>
<p>Posting Wall</p>
<?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:s Y-m-d') ."\n";
?>
</body>
</html>
Post page PHP
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/post.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
</head>
<body>
<h1>Your Daily Dorm News Post! </h1>
<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>
</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();
require('header.php');
?>
<p>Submit a Post</p>
<?php
if(isset($name)) {
echo "<h3>Thanks ".$name." for submitting your post.</h3>";
}
?>
<p>Here are all the posts we have received.</p>
<ul id="posts_list">
<div id="posts">
<?php
// Looping through all the posts in posts_array
$counter = 1;
foreach(array_reverse($posts_array) as $post){
$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";
echo '<div class=post>';
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>
</body>
</html>
Can someone please take a look at these, it just is not happing for me its a html form, a php file to process it and a javascript file, errors in the from browser show things like U+12AF phantom illegal characters in the JScript file, been going at it for 1.5 hours and am at my wits end.
--submit.js--
$(document).ready(function() {
$(function() {
$('#paycheck').bind('submit', function() {
$.post('Paycheck.php', $("#paycheck").serialize(), function(data) {
$('#result').html(data);
});
});
});
});
--Paycheck.html--
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<pre><title>Weekly Gross Paycheck Calculator</title></pre>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="submit.js"></script>
</head>
<body>
<h2 style = "text-align:center">PayCheck</h2>
<form name="paycheck" id="paycheck" action="" method="POST">
<p>Number of Hours: <input type="text" name="numHours"/></p>
<p>Hourly Wage $<input type="text" name="hourlyWage"/></p>
<p><input type="reset" value="Clear Form" />
<input type="submit" name="submit" value="Send Form" /></p>
</form>
<!-- Form and javascript will output the results here -->
<div id="result"></div>
</body>
</html>
--Paycheck.php--
<?php
function validateInput($data, $fieldName){
global $errorCount;
if (empty($data)) {
echo "\"$fieldName\" is a required field.<br/>\n";
++$errorCount;
$retval = "";
} else { // Only clean up the input if it isn't empty
if (!is_numeric($data)){
echo "\"$fieldName\" must be numeric.<br/>\n";
++$errorCount;
$retval = "";
}else{
$retval = trim($data);
$retval = stripslashes($retval);
}
return($retval);
} // end validateInput()
}
$ShowForm = TRUE;
$errorCount = 0;
$numHours = "";
$hourlyWage = "";
$wage = "";
if (isset($_POST['Submit'])) {
$numHours = validateInput($_POST['numHours'],"Number of Hours");
$hourlyWage = validateInput($_POST['hourlyWage'],"Hourly Wage");
if ($errorCount==0)
$ShowForm = FALSE;
else
$ShowForm = TRUE;
}
echo $numHours ." " . $hourlyWage;
if ($ShowForm == TRUE) {
if ($errorCount > 0)// if there were errors
print "<p>Please re-enter the form information below.</p>\n";
} else {
//If hours are over 40 then use time and a half
if($numHours > 40) { $wage = ((($numHours - 40) * 1.5) * $hourlyWage) + ($hourlyWage * 40); }
//otherwise use normal multiplication.
else { $wage = $numHours * $hourlyWage; }
print "<p>Your weekly gross salary is $". $wage . ".</p>\n";
}
?>
A few things:
You have an extra nested lambda function in your js which is not required.
$(document).ready($(function() {
$('#paycheck').bind('submit', function() {
$.post('Paycheck.php', $("#paycheck").serialize(), function(data) {
$('#result').html(data);
});
});
});
There is no action on your form, change to action="Payment.php"
Also in the php script line 27 should be if (isset($_POST['submit'])) { (with a lower case s in submit).
After these changes everything seems to work as intended.
Are you sure about the last line in your php script? I mean, shouldn't the dollar sign be escaped like in:
print "<p>Your weekly gross salary is \$". $wage . ".</p>\n";
Comments are right btw:
1)
$(document).ready(function() {
// don't double wrap
$('#paycheck').bind('submit', function() {
$.post('Paycheck.php', $("#paycheck").serialize(), function(data) {
$('#result').html(data);
});
});
});
2)
<head>
<title>Weekly Gross Paycheck Calculator</title>
<!-- no pre tags -->
<script type=...