I'm busy studying a book on php and they have an exercise on deleting records from a database. The issue I am having is deleting the image that is associated with the database entry. I have a defined constant of:
define(GW_UPLOADPATH, 'images/')
in a file called appvars.php. Here is the remove.php
<?php
require_once 'authorize.php';
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
require_once 'appvars.php';
require_once 'connectionvars.php';
if(isset($_GET['id']) && isset($_GET['name']) && isset($_GET['score']) && isset($_GET['date'])
&& isset($_GET['screenshot'])){
$id = $_GET['id'];
$name = $_GET['name'];
$score = $_GET['score'];
$date = $_GET['date'];
$screenshot = $_GET['screenshot'];
} else if(isset($_POST['id']) && isset($_POST['name']) && isset($_POST['score']) && isset($_POST['date'])){
$id = $_POST['id'];
$name = $_POST['name'];
$score = $_POST['score'];
$date = $_POST['date'];
} else {
echo 'No record selected';
}
if(isset($_POST['submit'])){
if(($_POST['confirm'] == 'Yes') && is_file(GW_UPLOADPATH.$screenshot)){
unlink(trim(GW_UPLOADPATH.$screenshot));
$query = "DELETE from guitarwars where id = $id limit 1";
mysqli_query($dbc, $query);
mysqli_close($dbc);
echo '<p class="error">The score of ' . $score . ' for' . $name . ' was successfully deleted</p>';
} else {
echo '<p class="error">Error removing record</p>';
}
}
else if(isset ($id) && isset($name) && isset($date) && isset($score) && isset($screenshot)){
echo '<p>Are you sure you want to delete the following high score?</p>';
echo '<p>Name: ' . $name . '<br />Date: ' . $date . '<br />Score: ' . $score . '<br />'
. 'PATH:' . GW_UPLOADPATH.$screenshot. '</p>' ;
echo '<form method="POST" action="remove.php">';
echo '<input type="radio" name="confirm" value="Yes" />Yes<br />';
echo '<input type="radio" name="confirm" value="No" checked="checked" />No<br />';
echo '<input type="submit" name="submit" value="Submit">';
echo '<input type="hidden" name="id" value="' . $id . '">';
echo '<input type="hidden" name="name" value="' . $name . '">';
echo '<input type="hidden" name="date" value="' . $date . '">';
echo '<input type="hidden" name="score" value="' . $score . '">';
echo '</form>';
}
echo '<p>Back to Admin page</p>';
?>
</body>
</html>
the database removes the entry 100% but i get an error that image is a directory. if you view the html it reports the path as images/imageName.gif
The is_file() I added to try figure out what is going on and as a result I now get my assigned error message "Error removing record". So what I think, its not seeing my imageName.gif as a file. not sure how else to remove the file, the book pacifically uses unlink.
Any guidance is greatly appreciated
ADDED: addscore.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Guitar Wars - Add Your High Score</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<h2>Guitar Wars - Add Your High Score</h2>
<?php
require_once 'appvars.php';
require_once 'connectionvars.php';
if (isset($_POST['submit'])) {
// Grab the score data from the POST
$name = $_POST['name'];
$score = $_POST['score'];
$screenshot = $_FILES['screenshot']['name'];
$screenshot_type = $_FILES['screenshot']['type'];
$screenshot_size = $_FILES['screenshot']['size'];
if (!empty($name) && !empty($score) && !empty($screenshot)) {
if((($screenshot_type == 'image/gif') || ($screenshot_type == 'image/jpeg') || ($screenshot_type == 'image/pjpeg')
|| ($screenshot_type == 'image/png')) && (($screenshot_size > 0) && ($screenshot_size <= GW_MAXUPLOADSIZE))){
$target = GW_UPLOADPATH.$screenshot;
if(move_uploaded_file($_FILES['screenshot']['tmp_name'], $target)){
// Write the data to the database
$query = "INSERT INTO guitarwars VALUES (0, NOW(), '$name', '$score', '$screenshot')";
mysqli_query($dbc, $query) or die('Error inserting data: ' . mysqli_error($dbc));
// Confirm success with the user
echo '<p>Thanks for adding your new high score!</p>';
echo '<p><strong>Name:</strong> ' . $name . '<br />';
echo '<strong>Score:</strong> ' . $score . '<br />';
echo '<img src="' . GW_UPLOADPATH.$screenshot . '" alt="screenshot image" /></p>';
echo '<p><< Back to high scores</p>';
// Clear the score data to clear the form
$name = "";
$score = "";
mysqli_close($dbc);
}
} else {
echo '<p class="error">Please ensure image file is corrent format and less than ' . (GW_MAXUPLOADSIZE / 1024) .
'Kb</p>';
}
#unlink($_FILES['screenshot']['tmp_name']);
}
else {
echo '<p class="error">Please enter all of the information to add your high score.</p>';
}
}
?>
<hr />
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="32768"/>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<?php if (!empty($name)) echo $name; ?>" /><br />
<label for="score">Score:</label>
<input type="text" id="score" name="score" value="<?php if (!empty($score)) echo $score; ?>" /><br />
<label for="screenshot">Screen Shot:</label>
<input type="file" id="screenshot" name="screenshot" />
<hr />
<input type="submit" value="Add" name="submit" />
</form>
</body>
</html>
I think the issue is that $screenshot is undefined...
Simplifying the code a bit, you have:
if(isset($_GET['screenshot'])) {
$screenshot = $_GET['screenshot'];
} else if(isset($POST['id')) {
}
if(isset($_POST['submit'])){
if(($_POST['confirm'] == 'Yes') && is_file(GW_UPLOADPATH.$screenshot)){
So... assuming you aren't doing something really weird, a request will either be a GET request, or a POST request. You only set $screenshot if it's a GET request, but you are checking is_file only on a POST request. So you are checking is_file("images/") and it is (correctly) telling you it is a directory.
Try this:
else if(isset($_POST['id']) && isset($_POST['name']) && isset($_POST['score']) && isset($_POST['date']) && isset($_POST['screenshot'])){
$id = $_POST['id'];
$name = $_POST['name'];
$score = $_POST['score'];
$date = $_POST['date'];
$screenshot = $_POST['screenshot']; //<-- add this line
}
...
echo '<form method="POST" action="remove.php">';
echo '<input type="radio" name="confirm" value="Yes" />Yes<br />';
echo '<input type="radio" name="confirm" value="No" checked="checked" />No<br />';
echo '<input type="hidden" name="screenshot" value="$screenshot" />'; //<-- add this line
Related
i try to challenge my self but i stuck(
I try to create a php form with 2 steps confirmation:
When the user fill up the form and hit Submit, it checks all the conditions(name, pass etc.). If everything ok automatically redirecting the user.
After redirecting (to the same page) the user can check all the details again.
If they ok, hit again the submit button which redirects to the final page.
I stuck on the 2nd phase...how to redirect to the final page?
I'm very beginner so i'm curios what could be done better or any advise.
<?php
// the php code
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// setting up the variables
$title = $_POST['title'];
$fName = trim(filter_input(INPUT_POST,'fName', FILTER_SANITIZE_STRING));
$lName = trim(filter_input(INPUT_POST,'lName',FILTER_SANITIZE_STRING));
$age = intval($_POST['age']);
$_SESSION['title'] = $title;
$_SESSION['fName'] = $fName;
$_SESSION['lName'] = $lName;
$_SESSION['age'] = $age;
//checking for possible errors
if ( $fName == "" || strlen($fName) <= 2 ) {
$errorMsg1 = "<span>Provide your First name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $lName == "" || strlen($lName) <= 2 ) {
$errorMsg2 = "<span>Provide your Last name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $age < 18 ) {
$errorMsg3 = "<span>You must be 18 or above!</span>";
$status = false;
}
else { $status = true; }
// redirecting to done page
if ($status) {
header("Location:TEST ZONE.php?status=awaiting");
}
}
?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<div id="wrapper">
<?php
if ( isset($_GET['status']) && $_GET['status'] == "awaiting" ) {
echo "<form>"
. "Check your Details!<br>"
. $_SESSION['title'] . "<br>"
. $_SESSION['fName'] . "<br>"
. $_SESSION['lName'] . "<br>"
. $_SESSION['age'] . "<br>"
// **NOW WHEN I'M in the awaiting phase, i don't know what to do(**
. "<input type='submit' name='submit'/>";
echo "</form>";
}
else { ?>
<form action="TEST ZONE.php" method="post">
<h3>Register Form </h3>
<label for="title">Title </label>
<select name="title">
<option name="mr">Mr</option>
<option name="ms">Ms</option>
</select><br><br><br>
<label for="fName">First Name</label><br>
<input type="text" name="fName" id="fName" value="<?php if (isset($fName)) { echo $fName; } ?>"><br><?php
if (isset( $errorMsg1 )) {
echo $errorMsg1;
}
?><br><br>
<label for="lName">Last Name</label><br>
<input type="text" name="lName" id="lName" value="<?php if (isset($lName)) { echo $lName; } ?>"><br><?php
if (isset( $errorMsg2 )) {
echo $errorMsg2;
}
?><br><br>
<label for="age">Age</label><br>
<input type="text" name="age" id="age" value="<?php if (isset($age)) { echo $age; }?>"><br><?php
if (isset($errorMsg3)){
echo $errorMsg3;
} ?><br><br>
<input type="submit" value="Submit"><input type="reset">
</form> <?php } ?>
</div>
</body>
</html>
Add action in your form to redirect final page.
You already have all values in session so you can access it in final page also
<?php
// the php code
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// setting up the variables
$title = $_POST['title'];
$fName = trim(filter_input(INPUT_POST,'fName', FILTER_SANITIZE_STRING));
$lName = trim(filter_input(INPUT_POST,'lName',FILTER_SANITIZE_STRING));
$age = intval($_POST['age']);
$_SESSION['title'] = $title;
$_SESSION['fName'] = $fName;
$_SESSION['lName'] = $lName;
$_SESSION['age'] = $age;
//checking for possible errors
if ( $fName == "" || strlen($fName) <= 2 ) {
$errorMsg1 = "<span>Provide your First name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $lName == "" || strlen($lName) <= 2 ) {
$errorMsg2 = "<span>Provide your Last name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $age < 18 ) {
$errorMsg3 = "<span>You must be 18 or above!</span>";
$status = false;
}
else { $status = true; }
// redirecting to done page
if ($status) {
header("Location:TEST ZONE.php?status=awaiting");
}
}
?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<div id="wrapper">
<?php
if ( isset($_GET['status']) && $_GET['status'] == "awaiting" ) {
echo "<form action='final_page.php'>"
. "Check your Details!<br>"
. $_SESSION['title'] . "<br>"
. $_SESSION['fName'] . "<br>"
. $_SESSION['lName'] . "<br>"
. $_SESSION['age'] . "<br>"
// **NOW WHEN I'M in the awaiting phase, i don't know what to do(**
. "<input type='submit' name='submit'/>";
echo "</form>";
}
else { ?>
<form action="TEST ZONE.php" method="post">
<h3>Register Form </h3>
<label for="title">Title </label>
<select name="title">
<option name="mr">Mr</option>
<option name="ms">Ms</option>
</select><br><br><br>
<label for="fName">First Name</label><br>
<input type="text" name="fName" id="fName" value="<?php if (isset($fName)) { echo $fName; } ?>"><br><?php
if (isset( $errorMsg1 )) {
echo $errorMsg1;
}
?><br><br>
<label for="lName">Last Name</label><br>
<input type="text" name="lName" id="lName" value="<?php if (isset($lName)) { echo $lName; } ?>"><br><?php
if (isset( $errorMsg2 )) {
echo $errorMsg2;
}
?><br><br>
<label for="age">Age</label><br>
<input type="text" name="age" id="age" value="<?php if (isset($age)) { echo $age; }?>"><br><?php
if (isset($errorMsg3)){
echo $errorMsg3;
} ?><br><br>
<input type="submit" value="Submit"><input type="reset">
</form> <?php } ?>
</div>
final_page.php
<?php
session_start();
$title = $_SESSION['title'];
$fName = $_SESSION['fName'];
$lName = $_SESSION['lName'];
$age = $_SESSION['age'];
?>
I have a problem with preserving the values written inside a textfield, if an error occurs. I have 4 textfields, and if 1 is blank it needs to show a new form, with a error message and the input in the textfield from the previous file.
I guess it's the last part of my assignment_2.php where it's wrong.
assignment_1.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="sendit.php" method="get">
<input type="text" name="name" placeholder="name"/>
<br>
<input type="text" name="adress" placeholder="adress"/>
<br>
<input type="text" name="city" placeholder="city"/>
<br>
<input type="text" name="zip" placeholder="zip"/>
<br>
<input type="submit" />
</form>
<br>
</body>
</html>
sendit.php
<?php
$name = $_GET['name'];
$adress = $_GET['adress'];
$city = $_GET['city'];
$zip = $_GET['zip'];
if (!isset($_GET['name']) || $_GET['name'] == '') {
header("Location: assignment_2.php?errmsg=1");
exit;
}
else {
header("Location: assignment_2.php?errmsg=1&name=$name");
}
if (!isset($_GET['adress'])|| $_GET['adress'] == '') {
header("Location: assignment_2.php?errmsg=2&adress=$adress");
exit;
}
else {
header("Location: assignment_2.php?errmsg=1&adress=$adress");
}
if (!isset($_GET['city'])|| $_GET['city'] == '') {
header("Location: assignment_2.php?errmsg=3&city=$city");
exit;
}
else {
header("Location: assignment_2.php?errmsg=1&city=$city");
}
if (!isset($_GET['zip'])|| $_GET['zip'] == '') {
header("Location: assignment_2.php?errmsg=4&zip=$zip");
exit;
}
else {
header("Location: assignment_2.php?errmsg=4&zip=$zip");
}
echo $name . "<br>" . $adress . "<br>" . $city . "<br>" . $zip
?>
assigment_2.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
// 1.0 Create a contactform containing name, address, city, zipcode
// Send it to a form handler
// If any of the form fields are not filled out, return to this page and
// display an error containing information on how to prevent the error
// 1.1 Preserve the input for the user
?>
<?php
if (isset($_GET['errmsg'])) {
$err = $_GET['errmsg'];
switch ($err) {
case 1:
$err_msg = 'Missing navn';
break;
case 2:
$err_msg = 'Missing adress';
break;
case 3:
$err_msg = 'Missing city';
break;
case 4:
$err_msg = 'missing zip';
break;
default:
$err_msg = 'I just dont like you';
break;
}
echo '<div class="error">' . $err_msg . '</div>';
}
?>
<form action="sendit.php" method="get">
<input type="text" name="name" placeholder="name" <?php
if (isset($_GET['name'])) echo 'value="' .$_GET['name'] .'"';
?> />
<br>
<input type="text" name="adress" placeholder="adress" <?php
if (isset($_GET['adress'])) echo 'value="' .$_GET['adress'] .'"';
?>/>
<br>
<input type="text" name="city" placeholder="city" <?php
if (isset($_GET['city'])) echo 'value="' .$_GET['city'] .'"';
?>/>
<br>
<input type="text" name="zip" placeholder="zip" <?php
if (isset($_GET['zip'])) echo 'value="' .$_GET['zip'] .'"';
?>/>
<br>
<input type="submit" />
</form>
</body>
</html>
I will probably handle first client side validation, so the form will not submit until all inputs get fill, then I will do some server side validation and sanitization. BTW you don't need to have assigment2.
Keep things simple!
For starters, try working on only one file, and put your errors into an array.
Then try shortening your code, and to never "copy & paste" code.
On modern sites, developpers use frameworks to validate forms,
Keep playing with this one until it works like you want, and have a look at Symfony or Zend Framework form validation.
<?php
$errors = array();
if (isset($_GET['submitted'])) {
if (!isset($_GET['name']) || $_GET['name'] == '')
$errors[] = 'Missing navn'
if (!isset($_GET['adress']) || $_GET['adress'] == '')
$errors[] = 'Missing navn'
if (!isset($_GET['city']) || $_GET['city'] == '')
$errors[] = 'Missing navn'
if (!isset($_GET['zip']) || $_GET['zip'] == '')
$errors[] = 'Missing navn'
}
?><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
if (count($errors) !== 0)
echo '<div class="error">' . implode("<br>", $errors) . '</div>';
?>
<form action="" method="get">
<input type="hidden" name="submitted" value="1" />
<input type="text" name="name" placeholder="name" value="<?php echo isset($_GET['name']) ? $_GET['name'] : '' ?>" />
<br>
<input type="text" name="adress" placeholder="adress" value="<?php echo isset($_GET['adress']) ? $_GET['adress'] : '' ?>" />
<br>
<input type="text" name="city" placeholder="city" value="<?php echo isset($_GET['city']) ? $_GET['city'] : '' ?>" />
<br>
<input type="text" name="zip" placeholder="zip" value="<?php echo isset($_GET['zip']) ? $_GET['zip'] : '' ?>" />
<br>
<input type="submit" />
</form>
<br>
</body>
</html>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<!DOCTYPE = "HTML">
<html>
<head>
<meta charset = "UTF-8">
</head>
<body>
<p1><h1>Guitar Wars - High Scores</h1></p1>
<hr />
<p2> The screenshot must be an image file no greater than 2MB in size.</p2>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="2100000" />
<label for="name">Name: </label>
<input type="text" id="name" name="name" /><br />
<label for="score">Score: </label>
<input type="text" id="score" name="score" /><br />
<label for "screenshot">Screen shot: </label>
<input type="file" id="screenshot" name="screenshot" />
<hr />
<input type="submit" name="submit" value="Add" /><br />
</form>
<?php
$name = $_POST['name'];
$score = $_POST['score'];
$screenshot = $_FILES['screenshot']['name'];
$screenshot_type = $_FILES['screenshot']['type'];
$screenshot_size = $_FILES['screenshot']['size'];
require_once('appvars.php');
if (isset($_POST['submit'])){
// Level 1
if ((!empty($name) && !empty($score)) {
// Level 2
$db = mysqli_connect('localhost','****','****','guitarwars') or die('cannot connect to server');
$query = "INSERT INTO scoreboard (date, name, score, screenshot) VALUES (NOW(),'$name', '$score', '$screenshot')";
$result = mysqli_query($db,$query) or die (mysqli_error($db));
echo $name.', your score has been added successfully!<br><br>';
if (($_FILES['screenshot']['error'] == 0) && ((($screenshot_type == 'image/gif') || ($screenshot_type == 'image/jpeg') || ($screenshot_type == 'image/png')) && (($screenshot_size > 0) && ($screenshot_size <= GW_MAXSIZE)))){
// Level 3
echo "File name: ".$screenshot."<br>";
echo "Type: " . $screenshot_type . "<br>";
echo "Type: " . $screenshot_size . " bytes<br>";
$target = GW_UPLOADPATH.$screenshot;
$move = move_uploaded_file($_FILES['screenshot']['tmp_name'], $target);
}
else {
// Level 3
echo '<p class = "error">Adding score failed, you can upload only image file under 2MB in size.'.$_FILES['screenshot']['error'].'</p>';
}
}
else {
// Level 2
echo '<p class = "error">Adding score failed, you must fill all the fields.</p>';
}
mysqli_close($db);
}<--- this is the last bracket
?>
<p>Go to the scoreboard!</p>
</body>
</html>
My text-editor(coda) sounds beep(alert) when I move cursor over the last bracket'}'. However I can't figure out what's wrong with that bracket.
And I added codes for displaying errors which neither works.
Thank you in advance.
Your problem is in this line:
if ((!empty($name) && !empty($score)) {
You have a ( to many.
It should be:
if (!empty($name) && !empty($score)) {
if ((!empty($name) && !empty($score)) {
You have too few ) here, which is causing the {...} around it (your "Level 1" braces) to overlap the () parentheses.
I have a problem with date in php
even if I fill the textbox of the date , in the database I find it empty
here is my php page :
<?php
session_start();
if (!array_key_exists("user", $_SESSION)) {
header('Location: index.php');
exit;
}
require_once("Includes/db.php");
$wisherID = WishDB::getInstance()->get_wisher_id_by_name($_SESSION['user']);
$wishDescriptionIsEmpty = false;
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (array_key_exists("back", $_POST)) {
header('Location: editWishList.php');
exit;
} else
if ($_POST['wish'] == "") {
$wishDescriptionIsEmpty = true;
} else if ($_POST["wishID"] == "") {
WishDB::getInstance()->insert_wish($wisherID, $_POST["wish"], $_POST["dueDate"]);
header('Location: editWishList.php');
exit;
} else if ($_POST["wishID"] != "") {
WishDB::getInstance()->update_wish($_POST["wishID"], $_POST["wish"], $_POST["dueDate"]);
header('Location: editWishList.php');
exit;
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css" href="jquery-ui-1.8.24.custom/css/smoothness/jquery-ui-1.8.24.custom.css" rel="stylesheet" />
<script type="text/javascript" src="jquery-ui-1.8.24.custom/js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.24.custom/js/jquery-ui-1.8.24.custom.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.24.custom\development-bundle\ui\i18n\jquery.ui.datepicker-fr.js"></script>
<script type="text/javascript">
$(function() {
$.datepicker.setDefaults( $.datepicker.regional[ "" ] );
$( "#datepicker" ).datepicker( $.datepicker.regional[ "fr" ] );
});
</script>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
$wish = array("id" => $_POST["wishID"], "description" => $_POST["wish"], "due_date" => $_POST["dueDate"]);
else
if (array_key_exists("wishID", $_GET))
$wish = mysqli_fetch_array(WishDB::getInstance()->get_wish_by_wish_id($_GET["wishID"]));
else
$wish = array("id" => "", "description" => "", "due_date" => "");
?>
<form name="editWish" action="editWish.php" method="POST">
<input type="hidden" name="wishID" value="<?php echo $wish["id"]; ?>" />
<table>
<tr>
<td>Describe your wish:</td>
<td><input type="text" name="wish" value="<?php echo $wish['description']; ?>" /></td>
<td><?php if ($wishDescriptionIsEmpty) echo "Please enter description"; ?></td>
</tr>
<tr>
<td>When do you want to get it?</td>
<td><input type="text" name="due_date" id="datepicker" value="<?php echo $wish['due_date']; ?>" /></td>
</tr>
</table>
<input type="submit" name="saveWish" value="Save Changes"/>
<input type="submit" name="back" value="Back to the List"/>
</form>
je suis
</br>
</body>
</html>
and here is the coresponding method in db.php :
function insert_wish($wisherID, $description, $dueDate) {
$description = $this->real_escape_string($description);
if ($duedate == '') {
$this->query("INSERT INTO wishes (wisher_id, description)" .
" VALUES (" . $wisherID . ", '" . $description . "')");
} else
$this->query("INSERT INTO wishes (wisher_id, description, due_date)" .
" VALUES (" . $wisherID . ", '" . $description . "', '" . $dueDate . "')");
}
public function update_wish($wishID, $description, $duedate) {
$description = $this->real_escape_string($description);
if ($duedate == null) {
$this->query("UPDATE wishes SET description = '" . $description . "', due_date = NULL WHERE id = " . $wishID);
} else
$this->query("UPDATE wishes SET description = '" . $description . "', due_date = '" . $duedate . "' WHERE id = " . $wishID);
}
I use the datepicker query component for date
can you detect me the location of the error
thanks
I think you have given a wrong name to input element. Replace below
<input type="text" name="due_date" id="datepicker"
value="<?php echo $wish['due_date']; ?>" />
With
<input type="text" name="dueDate" id="datepicker"
value="<?php echo $wish['due_date']; ?>" />
You are using $_POST["dueDate"] to get date value and the name is incorrect in your markup.
Edit ::
As #simonTifo said in comment "it return me the exact date, bit in the datatabase it saves like 00-00-0000", there might be some format related issue to overcome this problem just use the date function in php. So the code suppose to be :
WishDB::getInstance()->insert_wish($wisherID, $_POST["wish"],
date('Y-m-d H:i:s', $_POST["dueDate"]));
Check that function manual and set whatever format according to your need.
Hope this will help !!
Is there a way to push data to two fields in a table if a check box is clicked?
So in English, as a pure hypothetical I have six fields and a check box in two rows. First row, field one is name, second is address, third is email.
What I want to do is if the information is to be transferred from left to right upon posting, a person needs to check a box.
The table would have six fields.
name, address, email, name2, address2, email2.
So what would happen is that data that would post in name would also post in name2, as long as the check box is checked.
Is this possible in PHP?
Ok, well since people want a script to look at for an example, here... I figure it be easier to write up a generic script than to post what I'm working on. Sorry, thought I'd make it easier for people here.
<?php
require_once('connectvars.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die('Error connecting to MySQL server.');
$output_form = 'yes';
echo '<div id="postwrap">'
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Document Test</title>
<link rel="stylesheet" type="text/css" href="CSS/postie.css" />
</head>
<body>
<div id="title">
<h3 id="NCMR2">Document Test</h3>
</div>
<?php
//Post Data
if (isset($_POST['submit'])) {
$ab = mysqli_real_escape_string($dbc, trim($_POST['ab']));
$date = mysqli_real_escape_string($dbc, trim(date('Y-m-d',strtotime ($_POST['date']))));
$part = mysqli_real_escape_string($dbc, trim($_POST['part']));
$rev = mysqli_real_escape_string($dbc, trim($_POST['rev']));
$partdesc = mysqli_real_escape_string($dbc, trim($_POST['partdesc']));
$ncmrqty = mysqli_real_escape_string($dbc, trim($_POST['ncmrqty']));
$ab2 = mysqli_real_escape_string($dbc, trim($_POST['ab']));
$date2 = mysqli_real_escape_string($dbc, trim(date('Y-m-d',strtotime ($_POST['date']))));
$part2 = mysqli_real_escape_string($dbc, trim($_POST['part']));
$rev2 = mysqli_real_escape_string($dbc, trim($_POST['rev']));
$partdesc2 = mysqli_real_escape_string($dbc, trim($_POST['partdesc']));
$ncmrqty2 = mysqli_real_escape_string($dbc, trim($_POST['ncmrqty']));
$output_form = 'no';
if (empty($ab) || empty($date) || empty($part) || empty($partdesc)){
// We know at least one of the input fields is blank
echo '<div id="alert">';
echo 'Please fill out all of the required NCMR information.<br />';
echo '</div>';
}
$output_form = 'yes';
}
//Access the Database
if (!empty($ab) && !empty($date) && !empty($pod)) {
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die('Error connecting to MySQL server.');
$query = "INSERT INTO ncmr (ab, date, part, rev, partdesc, ncmrqty, ab2, date2, part2, rev2, partdesc2, ncmrqty2)
VALUES ('$ab', '$date', '$part', '$rev', '$partdesc', '$ncmrqty', '$ab2', '$date2', '$part2', '$rev2', '$partdesc2', '$ncmrqty2')";
mysqli_query($dbc,$query)
or die ('Data not inserted.');
// Clear the form data
$ab = "";
$date = "";
$part = "";
$rev = "";
$partdesc = "";
$ncmrqty = "";
$ab2 = "";
$date2 = "";
$part2 = "";
$rev2 = "";
$partdesc2 = "";
$ncmrqty2 = "";
// Confirm success with the user
echo '<tr><td class="thank">';
echo '<p>Thank you for adding the NCRM, the correct person will be informed.</p>';
echo '<p><< Back to the form</p>';
$output_form = 'no';
echo '</td></tr>';
mysqli_close($dbc);
}
if ($output_form == 'yes') {
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'>";
echo '<fieldset>';
//Part, Rev, Part Description, NCMR Qty
echo '<div id="box1">';
echo '<div id="ab"><span class="b">Added By: </span><input type="text" name="ab" value="" /></div>';
echo '<div id="date"><span class="b">Date Filed: </span><input type="text" name="date" value="" /></div>';
echo '<div id="part"><span class="b">Part Number: </span><input type="text" name="part" value="" /></div>';
echo '<div id="rev"><span class="b">Part Revision: </span><input type="text" name="rev" value="" /></div>';
echo '<div id="partdesc"><span class="b">Part Description: </span><textarea name="partdesc" rows="4" cols="22" ></textarea></div>';
echo '<div id="ncmrqty"><span class="b">NCMR Qty: </span><input type="text" name="ncmrqty" value="" /></div>';
echo '</div>';
echo '<div id="box2">';
echo '<div id="ab2"><span class="b">Added By: </span><input type="text" name="ab2" value="" /></div>';
echo '<div id="date2"><span class="b">Date Filed: </span><input type="text" name="date2" value="" /></div>';
echo '<div id="part2"><span class="b">Part Number: </span><input type="text" name="part2" value="" /></div>';
echo '<div id="rev2"><span class="b">Part Revision: </span><input type="text" name="rev2" value="" /></div>';
echo '<div id="partdesc2"><span class="b">Part Description: </span><textarea name="partdesc2" rows="4" cols="22" ></textarea></div>';
echo '<div id="ncmrqty2"><span class="b">NCMR Qty: </span><input type="text" name="ncmrqty2" value="" /></div>';
echo '</div>';
echo '<div id="button3"><input type="submit" value="Submit NCMR" name="submit" /></div>';
echo '</div>';
echo '</fieldset>';
echo '</form>';
}
echo '</div>';
?>
</body>
</html>
Set a name to the checkbox, say "duplicateBox", and have its value set to 1 when checked.
<?php
$name = $_POST['name'];
$address = $_POST['address'];
$email = $_POST['email'];
$name2 = $_POST['name2'];
$address2 = $_POST['address2'];
$email2 = $_POST['email2'];
$duplicate = $_POST['duplicateBox'];
if($duplicate == 1)
{
$name2 = $name;
$address2 = $address;
$email2 = $email;
}
$insert = "INSERT INTO `table` (name,address,email,name2,address2,email2) VALUES ('$name','$address','$email','$name2','$address2','$email2')";
mysql_query($insert)or die(mysql_error());
?>
Yes, it is possible (kind of) to do that using conditional statement.
It's not that you are posting duplicate data, but duplicating data that is already posted to your PHP script.
Very simple example:
$fieldsToDuplicate = array('name', 'address', 'email');
if (isset($_POST['checkbox'] && 1 == $_POST['checkbox']) {
foreach ($fieldsToDuplicate as $value)
{
$_POST[$value.'2'] = $_POST[$value];
}
}
Though have in mind that you should validate & filter input you got from the user before actually manipulating/inserting to database :)
It is also possible to have duplicate fields in HTML and duplicate data with Javascript, and then handle it in PHP without any conditions.