php editing script doesn't work properly - php

The script is about editing data retrieved from database. It works fine (it edits the data) but the errors array is displayed immediately when the script runs. So i get all there errors: forgotten title, body, date.
For testing purposes i omit the title for example and click submit i get only the you forgot to enter your title
<?php
$page_title = 'Edit a Joke';
include ('includes/header.html');
echo '<h1>Edit a Joke</h1>';
// Check for a valid Joke ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_jokes.php
$id = $_GET['id'];
}
else { // No valid ID, kill the script.
echo '<p>This page has been accessed in error.</p>';
exit();
}
require ('mysqli_connect.php');
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$errors = array();
// Check for a title
if (empty($_GET['title'])) {
$errors[] = 'You forgot to enter title.';
} else {
$tit = mysqli_real_escape_string($dbc, ($_GET['title']));
}
// Check for body:
if (empty($_GET['body'])) {
$errors[] = 'You forgot to enter body.';
} else {
$bod = mysqli_real_escape_string($dbc, ($_GET['body']));
}
// Check for date:
if (empty($_GET['date'])) {
$errors[] = 'You forgot to enter date.';
} else {
$dat = mysqli_real_escape_string($dbc, ($_GET['date']));
}
if (empty($errors)) // If everything's OK.
{
// Make the query:
$q = "UPDATE joke SET title='$tit', body='$bod', date='$dat' WHERE joke_id=$id LIMIT 1";
$r = #mysqli_query ($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
// Print a message:
echo '<p>The joke has been edited.</p>';
} else { // If it did not run OK.
echo '<p class>The joke could not be edited. Sorry</p>'; // Public message.
}
}
else { // Report the errors.
echo '<p>The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p>';
}// End of if (empty($errors)) IF.
}// End of submit conditional.
// Always show the form...
// Retrieve the joke information:
$q = "SELECT title, body, date FROM joke WHERE joke_id=$id";
$r = #mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) { // Valid joke ID, show the form.
// Get the joke's information:
$row = mysqli_fetch_array ($r, MYSQLI_NUM);
// Create the form:
echo '<form action="edit_joke.php" method="GET">
<p> Title: <input type="text" name="title" value="' . $row[0] . '" /></p>
<p> Body: <input type="text" style="height: 100" size="100" name="body" value="' . $row[1] . '" /> </p>
<p> Date: <input type="date" name="date" value="' . $row[2] . '" /> </p>
<p> <input type="submit" name="submit" value="Submit" /></p>
<input type="hidden" name="id" value="' . $id . '" />
</form>';
} else { // Not a valid joke ID.
echo '<p>This page has been accessed in error.</p>';
}
mysqli_close($dbc);
?>

Change at the beginning:
if (isset($_GET['test'])) {
$errors = array();
// Check for a title
....
}
// Always show the form...
And add in your <form:
<input type="hidden" name="test" value="1">

Related

Update function php

I'm working in a update file using php and mysql but the update function doesn't work. I wrote the code using an example and modified according to the requirements. The file does work and doesn't really drop any error but it doesn't change anything in the database. It is suppose to update a book database.
Code:
<?php
$page_title = 'Add Books';
include ('bookincludes/header.html');
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('../mysqli_connect.php'); // Connect to the db.
$errors = array(); // Initialize an error array.
if (empty($_POST['title'])) {
$errors[] = 'Please add title.';
} else {
$e = mysqli_real_escape_string($dbc, trim($_POST['title']));
}
if (empty($_POST['author'])) {
$errors[] = 'Please add the name of the author.';
} else {
$p = mysqli_real_escape_string($dbc, trim($_POST['author']));
}
if (!empty($_POST['isbn1'])) {
if ($_POST['isbn1'] != $_POST['isbn2']) {
$errors[] = 'ISBN number does not match.';
} else {
$np = mysqli_real_escape_string($dbc, trim($_POST['isbn1']));
}
} else {
$errors[] = 'You need to enter ISBN number.';
}
if (empty($errors)) { // If everything's OK.
$q = "SELECT ISBN FROM Books WHERE (Title='$e' AND Author ='$p')";
$r = #mysqli_query($dbc, $q);
$num = #mysqli_num_rows($r);
if ($num == 1) { // Match was made.
$row = mysqli_fetch_array($r, MYSQLI_NUM);
// Make the UPDATE query:
$q = "UPDATE Books SET ISBN='$np' WHERE ISBN = $row[0] ";
$r = mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
// Print a message.
echo '<h1>Thank you!</h1>
<p>Thank you, Book has been added or modified</p><p><br /></p>';
} else { // If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">System error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
}
mysqli_close($dbc); // Close the database connection.
// Include the footer and quit the script (to not show the form).
include ('includes/footer.html');
exit();
} else {
echo '<h1>Error!</h1>
<p class="error">ISBN number is incorrect.</p>';
}
} else { // Report the errors.
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p><p><br /></p>';
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} // End of the main Submit conditional.
?>
<h1>Update</h1>
<form action="Bupdate.php" method="post">
<p>ISBN number: <input type="text" name="isbn1" size="20" maxlength="60" value="<?php if (isset($_POST['isbn1'])) echo $_POST['isbn1']; ?>" /> </p>
<p>Confirm ISBN: <input type="text" name="isbn2" size="20" maxlength="60" value="<?php if (isset($_POST['isbn2'])) echo $_POST['isbn2']; ?>" /> </p>
<p>Author: <input type="text" name="author" size="20" maxlength="60" value="<?php if (isset($_POST['author'])) echo $_POST['author']; ?>" /></p>
<p>Title: <input type="text"" name="title" size="20" maxlength="60" value="<?php if (isset($_POST['title'])) echo $_POST['title']; ?>" /></p>
<p>Year: <input type="text"" name="year" size="20" maxlength="60" value="<?php if (isset($_POST['year'])) echo $_POST['year']; ?>" /></p>
<p><input type="submit" name="submit" value="Update" /></p>
</form>
<?php include ('bookincludes/footer.html'); ?>
This is what If I try to change the ISBN got:
System error. We apologize for any inconvenience.
Query: UPDATE Books SET ISBN='978-1782175910' WHERE ISBN =
978-1782175919
If I tried to update the ISBN or the year but I get the message above.
How can I fix this?
The query requires that text values are wrapped in quotes like this
$q = "UPDATE Books SET ISBN='$np' WHERE ISBN = '$row[0]'";
Although I would look for a tutorial that uses parameterised and prepared queries rather than string concatenated queries to avoid SQL Injection
And any tutorial that suggests using the # error silencing prefix should tell you the author has no idea what they are doing and should be avoided like the plague.
you seem to be missing single quotes on your where clause
UPDATE Books SET ISBN='978-1782175910' WHERE ISBN = 978-1782175919
should be
UPDATE Books SET ISBN='978-1782175910' WHERE ISBN = '978-1782175919'

How to keep form data after validation fail and when the page redirects with PHP?

I have this form that I'm working with off a tutorial. I'm trying keep the fields populated when there is a validation error.
Here is my form:
<div class="add">
<?php $errors4 = errors_seesion_funtion(); ?>
<?php echo form_errors($errors4); ?>
<div class="error-message"><?php echo message(); ?></div>
<div class="done"><input name="Done" type="button" value="Done" /></div>
<h2>ADD New Department:</h2>
<form action="create-department-process.php" method="post">
<p class="department-name">Department name:
<input type="text" name="department_name" id="department-name" value="<?php if (isset($_POST['department_name'])) { echo htmlentities($_POST['department_name']); } ?>" />
<span class="error">* <?php if (!empty($errors4)) { echo "<div class=\"error\">";
echo "Hi";
echo "</div>";
}
?></span>
</p>
<p class="department-name">Test name:
<input type="text" name="test_name" id="test-name" value="" />
<span class="error">* <?php /*echo form_errors($errors4); */
if (!empty($errors4)) {
echo "<div class=\"error\">";
echo "test name";
echo "</div>";
}
?></span>
</p>
<input type="submit" name="dept_added" id="add-btn" value="ADD Department" />
</form>
<br />
<div class="cancel">Cancel</div>
Here is my Session:
session_start();
function message() {
if (isset($_SESSION["message"])) {
$output = "<div class='message'>";
$output .= htmlentities($_SESSION["message"]);
$output .= "</div>";
// clear message after use
$_SESSION["message"] = null;
return $output;
}
}
function errors_seesion_funtion() {
if (isset($_SESSION["errors3"])) {
$errors2 = $_SESSION["errors3"];
$_SESSION['post_data'] = $_POST;
// clear message after use
$_SESSION["errors3"] = null;
return $errors2;
}
}
Here is my Validation Functions:
$errors_array = array();
function fieldname_as_text($fieldname) {
$fieldname = str_replace("_", " ", $fieldname);
$fieldname = ucfirst($fieldname);
return $fieldname;
}
function has_presence($value) {
return isset($value) && $value !== "";
}
function validate_presences($required_fields) {
global $errors6;
foreach($required_fields as $field) {
$value = trim($_POST[$field]);
if (!has_presence($value)) {
$errors6[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
Here is my create-department-process.php
if (isset($_POST['dept_added'])) {
$department_name = mysql_prep($_POST["department_name"]);
//Validations for form
$required_fields = array("department_name", "test_name");
validate_presences($required_fields);
if (!empty($errors6)) {
$_SESSION["errors3"] = $errors6;
redirect_to("add-department.php"); //this is the page the form is on
}
// Process the form
$query1 = "INSERT INTO departments (";
$query1 .= " department_name ";
$query1 .= ") VALUES ( ";
$query1 .= " '{$department_name}' ";
$query1 .= ") ";
$result1 = mysqli_query($db_connection, $query1);
if ($result1) {
// Success
$_SESSION["message"] = "Department created.";
redirect_to("add-department.php");
} else {
// Failure
$_SESSION["message"] = "Department creation failed.";
redirect_to("creation-error.php");
}
} else {
redirect_to("fail.php");
}
I've tried to put this in the value of my form
<?php if (isset($_POST['department_name'])) { echo htmlentities($_POST['department_name']); } ?>
But the value I type in doesn't stay when PHP runs the form validation and redirects. Does anyone have any idea on how I can keep the data I type into the form fields when I have a validation error?
Thank you for your time and Help! I really appreciate it!
I think your POST data is getting lost when you do this:
if (!empty($errors6)) {
$_SESSION["errors3"] = $errors6;
redirect_to("add-department.php"); //this is the page the form is on
}
I'm guessing redirect_to actually redirects your browser to the specified page, therefore resetting the REQUEST values and losing the pervious POST data. You either need to save the POST values in the session (a la errors_seesion_funtion) and access them from there in your form, or include the form above to preserve the original POST values.

Clear form fields after a successful submit

well im working on a small html form.
<form class="contact" action="" method="POST">
<label>Name : </label><input type="text" name="name" value="<? echo $name; ?>"/>
<p class="middle"><label>Comment : </label><textarea name="message"></textarea><? echo $message; ?></p>
<label class="captcha"><img src="captcha.php" style="line-height: 30px;"></label><input type="text" name="code"/>
<input type="submit" class="csubmit" value="Now !" name="get"/>
</form>
and this is the php code:
<?php
if (isset($_POST['get'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "no name. <br />";
}
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
$error .= "no message <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "wrong captcha <br />";
}
if (!empty($error)) {
echo '<p class="error">Error :<br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
if (empty($error)) {
$message = mysql_real_escape_string($message);
$name = mysql_real_escape_string($name);
$id = mysql_real_escape_string($_GET['id']);
$date = date("Y-m-d H:i:s");
mysql_query("INSERT INTO comments(id, name, comment, time,approved)VALUES('$id', '$name', '$message', '$date', '0')");
echo "thank you";
}
}
?>
As you can see i user $message and $name to keep informations after a submit with wrong captcha code, but the problem is that i want to clear those fields after a submit with correct informations. Can you please tell me how can i clear form fields after a succesfull submit ?
You can use .reset() on your form.
$("#form")[0].reset();
You could follow that with Javascript too
document.getElementById('form').reset();
Or, if successful, redirect the user back to your contact page:
header("Location: contact.php"); // redirect back to your contact form
exit;
EDIT
<input type="submit" class="csubmit" value="Now !" name="get" onClick="clearform();" />
function clearform()
{
document.getElementById("name").value=""; //don't forget to set the textbox ID
document.getElementById("message").value=""; //don't forget to set the textbox ID
document.getElementById("code").value=""; //don't forget to set the textbox ID
}
Also use:
required="required"
so people will be required to fill out the input fields :)
Which by the way is the prefered method. If you keep the user in a page that was reached through a POST method, if he refreshes the page the form will be submitted again.

PHP function showing blank screen?

I am copying a youtube video tutorial for private messaging. The rest of the tutorial works fine, but as soon as I add this function to my site, my entire site goes blank and nothing is shown? No errors or anything, just a white screen? Have I done something wrong here? Here is the function:
<?php
function fetch_user_ids($usernames){
foreach ($usernames as &$name){
$name = mysql_real_escape_string($name);
}
$result = mysql_query("SELECT `userid`, `username` FROM `users` WHERE `username` IN ('" . implode("', '", $usernames) . "')");
$names = array();
while (($row = mysql_fetch_assoc($result)) !== false){
$names[$row['username']] = $row['userid'];
}
return $names;
}
?>
Here is the script to send the information:
<?php
if (isset($_POST['to'], $_POST['subject'], $_POST['body'])){
$errors = array();
if (empty($_POST['to'])){
$errors[] = 'You must enter atleast one name.';
}else if (preg_match('#^[a-z, ]+$#i', $_POST['to']) === 0){
$errors[] = 'The list of names you gave does not look valid.';
}else{
$usernames = explode(',', $_POST['to']);
foreach ($usernames as &$name){
$name = trim($name);
}
$user_ids = fetch_user_ids($usernames);
if (count($user_ids) !== count($usernames)){
$errors[] = 'The following users could not be found: ' . implode(', ', array_diff($usernames, array_keys($user_ids)));
}
}
if (empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty';
}
if (empty($_POST['body'])){
$errors[] = 'You body must have some text!';
}
if (empty($errors)){
//Send message
}
}
if (isset($errors)){
if (empty($errors)){
echo '<div class="msg success">Your message has been sent ! return</div>';
}else{
foreach ($errors as $error){
echo '<div class="msg error">', $error, '</div>';
}
}
}
?>
<form action="" method="POST">
<div>
<label for="to">To</label>
<input type="text" name="to" id="to" />
</div>
<div>
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" />
</div>
<div>
<textarea name="body" rows="10" cols="110"></textarea>
</div>
<div>
<input type="submit" value="send" />
</div>
</form>
If I take away the "function" part, I can print the data, so it must be something to do with the function element?
I would suggest changing the !== to != and seeeing if that works, it could be interpreting it has a number and not as a bool
Make it simpler. Inside foreach, get rid of &$name and replace it with $name. Also check if your database is returning nothing.
foreach ($usernames as $name){
$name = mysql_real_escape_string($name);
}
$result = mysql_query("SELECT `userid`, `username` FROM `users` WHERE `username` IN ('" . implode("', '", $usernames) . "')");
// Check if the query itself is failing or not here:
if(!$result) die("Failed to perform query");
$names = array();
// Check if the database is returning any rows or not:
print_r(mysql_num_rows($result));
while($row = mysql_fetch_assoc($result)){
$names[$row['username']] = $row['userid'];
}
return $names;

Unable to submit form, Just hit First Validation Error

When i submit my form i just hit my first validation error. No data ever posts.
I'm new to all this stackOverflow stuff and new to all the database scene. To get what I've got i used some TUT's and Books.
Hope someone can help me.
$itemid = $_GET['page_id'];
$itemid = mysql_real_escape_string($itemid);
//get data from database that needs editing
$sql = mysql_query("SELECT * FROM content WHERE `page_id`='{$itemid}'")or die(mysql_error());
//if(!$sql) die ("Database access failed" . mysql_error());
if(isset($_POST['submit'])){
//start validation
//check fields are not empty
if(empty($pagetitle)) {
$error['page_title'] = 'enter a title.';
}
$pagecontent = trim($_POST['page_content']);
if(empty($pagecontent)){
$error['page_content'] = 'Please enter your content.';
}
//If validation is ok... cary on.. do this
if (!$error) {
$pageid = $_POST['page_id'];
$pagetitle = $_POST['page_title'];
$pagecontent = $_POST['page_content'];
//Update items
$sql = "UPDATE content SET page_title ='$pagetitle', page_content ='$pagecontent' WHERE page_id='$itemid'";
$resultupdate = mysql_query($sql)or die (mysql_error());
//Success Message
echo "Your site is now updated";
}//close if !error
}//close if form submit
//input validation checks input not empty
if (isset($error['page_title'])) {
echo "<p><span class=\"warning\">" . $error['page_title']."</span><p> ";
}
if (isset($error['page_content'])) {
echo "<p><span class=\"warning\">" . $error['page_content']."</span><p> ";
}
?>
<div>
<?php while ($row = mysql_fetch_object($sql)) { ?>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<input type="hidden" name="page_id" value="<?php echo $row->page_id; ?>" />
<div class="edit-title">
<h2><label>Page Title</label></h2>
<p><textarea name="page_title"><?php echo $row->page_title; ?></textarea></p>
</div><!-- end edit title -->
<div class="edit-content">
<h2><label>Page Content</label></h2>
<p><textarea name="page_content"><?php echo $row->page_content; ?></textarea></p>
</div><!-- end edit content -->
<div class="submit-form">
<input type="submit" name="submit" value="Update" />
</div>
</form>
<?php } ?>
</div>
You check if $pagetitle exists but you don't initialize it, you should have put :
if(empty($_POST['page_title'])) { ... }
EDIT :
if(isset($_POST['submit'])){
//start validation
//check fields are not empty
if(empty($_POST['page_title'])) {
$error['page_title'] = 'enter a title.';
}
$pagecontent = trim($_POST['page_content']);
if(empty($pagecontent)){
$error['page_content'] = 'Please enter your content.';
}
//If validation is ok... cary on.. do this
if (!$error) {
$pageid = $_POST['page_id'];
$pagetitle = $_POST['page_title'];
$pagecontent = $_POST['page_content'];
//Update items
$sql = "UPDATE content SET page_title ='$pagetitle', page_content ='$pagecontent' WHERE page_id='$itemid'";
$resultupdate = mysql_query($sql)or die (mysql_error());
//Success Message
echo "Your site is now updated";
}//close if !error
}//close if form submit

Categories