PHP posting values but database not updating [duplicate] - php

This question already exists:
PHP's white screen of death [duplicate]
Closed 6 years ago.
I'm having a problem where my form is submitting the values but they aren't getting entered into the database?
I have tried echo'ing the $_POST to see what is getting posted and everything is posting as it should but its failing at the point of entering into the database.
Here is my code
if(isset ($_POST["update_detail"])) {
foreach($_POST["id"] AS $id) {
$name = mysqli_real_escape_string($_POST["name"][$id]);
$age = mysqli_real_escape_string($_POST["age"][$id]);
$update1 = "UPDATE `booked_peoples` SET `name` = '$name',`age` = '$age' WHERE `booked_peoples`.`id` = ".$id;
$update2 = mysqli_query($con,$update1);
if($update2){
echo '<script>window.location.href="add_passengers.php?book_id='.$book_id.'";</script>';
}
else {
echo 'OOPS';
} } }
and here is the php form code
if(isset($_GET['book_id']) and $_GET['action']=='edit')
{
$sq_edit_ps = "select * from booked_peoples where booking_id = ".$book_id;
$qr_edit_ps = mysqli_query($con,$sq_edit_ps);
while($rw_edit_ps = mysqli_fetch_array($qr_edit_ps))
{
$ps_id = $rw_edit_ps['id'];
echo '<form action="" method="POST" role="form">';
echo '<div class="row">
<div class="col-sm-9">
<label>Name</label>
<input class="form-control" type="text" name="name['.$ps_id.']" value="'.$rw_edit_ps['name'].'"/>
</div>
<div class="col-sm-3">
<label>Age</label>
<input class="form-control" type="text" name="age['.$ps_id.']" value="'.$rw_edit_ps['age'].'"/>
<input type="hidden" name="id[]" value="'.$ps_id.'"/>
</div>
</div>';
}
echo '
<button class="btn btn-info btn-flat" type="submit" name="update_detail" >Update</button>
</form>
</div>';
}
Im getting code blind.......:(

It was the mysql_real_escape_string that was stopping it form working.
It needed to be $name = mysqli_real_escape_string($con, $_POST["name"][$id]);
Thank you to the poster above for pointing it out :)
Wanted to post the solution in case anyone else comes across the same problem

Related

I don't know what i did wrong on my code, the error message for php form validation stopped working [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I don't know what I did wrong on my code, the error message for php form validation stopped working.
It was working perfectly until i added value attribute to the input so that the user input will persist even if the page refresh and didn't deliver due to typeError.
The form does'nt show any error again but my reason for adding the value attribute is working.
I'm learning php, please help me to understand why i'm having the issue.
I don't understand because i'm not getting any error from php.
This is my code
<?php
// empting the value variables when user have'nt typed anything to prevent error. This is the shorthand of typing samething that's going to have the same value
$email = $title = $ingredients = '';
// put out the error on the html instead of echoing it
// so i used array so that i can neatly put out all the errors instead of using different variables for all
$error = array('email' => '', 'title' => '', 'ingredients' => '');
// check if the form was clicked and retrive the values sent
// i will achieve this by using a default method called isset() and i will check if value is contained in the form using the submit btn, this is because when a user clicks on the form submit, the user have entered a value
if(isset($_POST['submit'])){
// check if the field submited is empty
// we achieve this using a default method called empty()
// we check them one field at a time
// check for email
if(empty($_POST['email'])){
$error['email'] = ' Email is empty';
} else {
$email = $_POST['email'];
}
// check for title
if(empty($_POST['title'])){
$error['title'] = ' Title is empty';
} else {
$title = $_POST['title'];
}
// check for ingredients
if(empty($_POST['ingredients'])){
$error['ingredients'] = ' Ingredients is empty';
} else {
$ingredients = $_POST['ingredients'];
}
}
?>
<!DOCTYPE html>
<html lang="en">
<?php include 'template/header.php'?>
<form action="form.php" method="POST">
<div class="input_div">
<label >Email :</label>
<input type="text" name="email" value=" <?php echo $email ?> ">
<div class="error_msg"><?php echo $error['email']; ?></div>
</div>
<div class="input_div" >
<label >Pizza Title :</label>
<input type="text" name="title" value=" <?php echo $title ?> " >
<div class="error_msg"><?php echo $error['title']; ?></div>
</div>
<div class="input_div" >
<label >Ingredients (comma seperated) :</label>
<input type="text" name="ingredients" value=" <?php echo $ingredients ?> ">
<div class="error_msg"><?php echo $error['ingredients']; ?></div>
</div>
<div class="input_div" >
<input type="submit" class="submitBtn" name="submit" value="Submit">
</div>
</form>
<?php include 'template/footer.php' ?>
</html>
Other then the issues with whitespace in your inputs you should also be aware of XSS when inserting the values back into the form (like using " would break the form) and also don't populate the errors till needed, this will allow you to easily continue and do the success step without needing to loop over the $errors array and it also allows you to hide the <div class="error_msg"></div> element and only show when there is an error.
Also your missing <head> and <body>, presuming they are in the includes, but doing it that way would make it rather difficult to add additional elements or scripts.
<?php
$email = $title = $ingredients = '';
$error = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// check for email
if (empty($_POST['email'])) {
$error['email'] = 'Email is empty';
} else {
$email = $_POST['email'];
}
// check for title
if (empty($_POST['title'])) {
$error['title'] = 'Title is empty';
} else {
$title = $_POST['title'];
}
// check for ingredients
if (empty($_POST['ingredients'])) {
$error['ingredients'] = 'Ingredients is empty';
} else {
$ingredients = $_POST['ingredients'];
}
if (empty($error)) {
// do some thing with $email, $title, $ingredients
die(header('Location: ./thank-you.php'));
}
}
function xss_safe($value) {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
?><!DOCTYPE html>
<html lang="en">
<?php include 'template/header.php' ?>
<form action="form.php" method="POST">
<div class="input_div">
<label>Email :</label>
<input type="text" name="email" value="<?= xss_safe($email) ?>"/>
<?= isset($error['email']) ? '<div class="error_msg">'.$error['email'].'</div>' : '' ?>
</div>
<div class="input_div">
<label>Pizza Title :</label>
<input type="text" name="title" value="<?= xss_safe($title) ?>"/>
<?= isset($error['title']) ? '<div class="error_msg">'.$error['title'].'</div>' : '' ?>
</div>
<div class="input_div">
<label>Ingredients (comma seperated) :</label>
<input type="text" name="ingredients" value="<?= xss_safe($ingredients) ?>"/>
<?= isset($error['ingredients']) ? '<div class="error_msg">'.$error['ingredients'].'</div>' : '' ?>
</div>
<div class="input_div">
<input type="submit" class="submitBtn" name="submit" value="Submit">
</div>
</form>
<?php include 'template/footer.php' ?>
</html>
Seeing as your error checking is merely for empty/missed input fields it's easier to just make the inputs required as per HTML5. Here's a simplified version using placeholders for information after the form has been submitted.
Warning: If you are going to be inserting this data into a MySQL table, you need to sanitize the inputs first!
<?php
$email = $title = $ingredients = "";
if (isset($_POST["submit"])) {
$email = $_POST["email"];
$title = $_POST["title"];
$ingredients = $_POST["ingredients"];
}
echo "
<form method='POST'>
<label>Email:</label>
<input type='email' name='email' placeholder='$email' required>
<label>Pizza Title:</label>
<input type='text' name='title' placeholder='$title' required>
<label>Ingredients (comma seperated):</label>
<input type='text' name='ingredients' placeholder='$ingredients' required>
<input type='submit' name='submit' value='Submit'>
</form>
";
?>

Display of database fetched data in HTML through PHP

I have an textarea to create an article, which then gets loaded into the db.
Also i have a function to fetch an article by chapter number to display it on the site.
The function works well, but the fetched data, or better said all echos from the PHP function get right into the body-tag which kills my layout.
I'd like to know, how can I display the data from the PHP output into a specific area in my HTML?
index.html:
<body>
<div class="main">
<h1>WebDev's Playground</h1>
<p>Momentaner Versuch: Formatierte Texte in Datenbanken speichern.</p>
<div class="playground">
<form action="?send=1" method="post">
<label for="heading">Überschrift</label>
<input name="heading" type="text" style="display:block;" />
<label for="chapter">Kapitel</label>
<input name="chapter" type="number" style="display:block;"/>
<textarea name="textbereich" rows="10" cols="130"></textarea>
<input type="submit" style="display:block;" />
</form>
</div>
<div>
<form action="?read=1" method="post">
<input name="chapter" type="number">
<button type="submit">Auslesen</button>
</form>
</div>
</div>
</body>
And this is from my logic.php:
//BEGINNING fetching data / ouput data
if (isset($_GET['read'])) {
$id = "";
$chapter = $_POST['chapter'];
$heading = "";
$textbereich = "";
$error = false;
$errormessage = "Es ist folgender Fehler aufgetreten: ";
if (!$error) {
$statement = $pdo->prepare("SELECT * FROM beitraege WHERE chapter = :chapter");
$result = $statement->execute(array("chapter" => $chapter));
$ergebnis = $statement->fetch(PDO::FETCH_ASSOC);
print ("<h2>" . $ergebnis['heading'] . "</h2>");
print ("<p>Kapitel: " . $ergebnis['chapter'] . "</p>");
print ("<pre>" . $ergebnis['content'] . "</pre>");
}
}
//END fetching data/ output data
?>
Solution: I have to store the data in variables and call them on the HTML in the wanted area.
$outputHeading = "";
$outputChapter = "";
$outputContent = "";
if (!$error) {
$statement = $pdo->prepare("SELECT * FROM beitraege WHERE chapter = :chapter");
$result = $statement->execute(array("chapter" => $chapter));
$ergebnis = $statement->fetch(PDO::FETCH_ASSOC);
$outputHeading = $ergebnis['heading'];
$outputChapter = $ergebnis['chapter'];
$outputArticle = $ergebnis['content'];
}
and in HTML:
<div>
<form action="?read=1" method="post">
<input name="chapter" type="number">
<button type="submit">Auslesen</button>
</form>
<h2><?php echo $outputHeading;?></h2>
<h2><?php echo $outputChapter; ?></h2>
<pre><?php echo $outputContent; ?></pre>
</div>
I hope this text area you are getting data and store it into DB,
<textarea name="textbereich" rows="10" cols="130"></textarea>
but when you are fetching from DB your tag should be
<textarea name="textbereich" rows="10" cols="130"><?php echo $value; ?></textarea>
so that the value will be populated in text Area

form doesn't contains a value to let me edit the file

file does not appear
hi guys, i having problem with my forms which i already set a value from my database which my file input doesn't appear out from database. who have idea what problem? the datatype i using for file in mysql is medium blob which stores the file in a folder called upload. first code is my editquiz.php, while second codes is my pedit.php.
<form method ="post" action = "peditQuiz.php" enctype="multipart/form-data">
<input type = "hidden" name = "quizID" id="quizID" value = "<?php echo $st_row['q_id'] ?>" >
<div class="form-group">
<h4><b>Quiz ID: <span class="text-primary"><?php echo $st_row['q_id'] ?></span> </b></h4>
</div>
<hr>
<div class="form-group">
<label>Quiz Title</label>
<input type="text" class="form-control" name = "quizTitle" id="quizTitle" value = "<?php echo $st_row['q_title'] ?>" required>
</div>
<div class="form-group">
<label>Quiz Description</label>
<input type="text" class="form-control" name = "quizDesc" id="quizDesc" value = "<?php echo $st_row['q_desc'] ?>" required >
</div>
<div class="form-group">
<label>Quiz URL (paste the link here)</label>
<input type="url" class="form-control" name = "quizURL" id="quizURL" value = "<?php echo $st_row['q_url'] ?>">
</div>
<div class="form-group">
<label>Upload new Quiz file (Max. allowed file size is 8MB)</label>
<input type="file" class="form-control" name = "quizFile" id ="quizFile" value = "<?php echo $st_row['q_file'] ?>" placeholder = "<?php echo $st_row['q_file'] ?>">
</div>
<input type="submit" class="btn btn-default" name = "btnUpdate" value = "Update">
<input type="reset" class="btn btn-default" value = "Clear">
<button type="button" style = "float:right" class="btn btn-info" >Back</button>
//Pedit.php
<?php
include("connection.php");
$userid = $_SESSION['userID'];
$title= $_POST['quiz_Title'];
$desc = $_POST['quiz_Desc'];
$url = $_POST['quiz_URL'];
$file = rand(1000, 100000). "-".$_FILES['quiz_File']['name'];
$file_loc = $_FILES['quiz_File']['tmp_name'];
$file_size = $_FILES['quiz_File']['size'];
$file_type = $_FILES['quiz_File']['type'];
$folder="files/";
move_uploaded_file($file_loc, $folder.$file);
/*
$id = $_POST['quizID'];
$sql = "SELECT * FROM quiz where quiz_id = '$id'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
$count = mysql_num_rows($result);
if($count > 0){
echo "<script>alert('Quiz record already exist');window.location.href = 'addQuiz.php';</script>";
} else { */
if($url==NULL){
$sql = "insert into quiz (q_title, q_desc, q_url, q_file, admin)
values ('$title','$desc ','$url','$file','$userid ' )" ;
mysql_query($sql);
echo "<script>alert('New record created succcessfully');window.location.href = 'manageQuiz.php';</script>";
} else{
$sql = "insert into quiz (q_title, q_desc, q_url, admin)
values ('$title','$desc ','$url','$userid ' )" ;
mysql_query($sql);
echo "<script>alert('New record created succcessfully');window.location.href = 'manageQuiz.php';</script>";
}
//}
mysql_close($con);
?>
Your question is difficult to follow, but I'll try:
It looks like you are using php to dump values in your form via PHP before you load the values later with your include statement.
I'm also not sure why you are saying that you use a file-based database but also seem to include sql commands, but regardless of how you load values into "$st_row['q_id']", they must be loaded before you attempt to echo them into your html.
If you have a requirement to include the db file later for some reason, you could use javascript to push the values into the form fields after the fact.
If, however, you are looking for the results of the sql queries from an included file ... I think you'll need to specify what value you expected to load from what file and provide that code as well.
Hope that helped. Good luck. Also congrats on asking a question on stackoverflow. Looks like you're a beginner but trying hard. ;)

PDO insert parameter key instead parameter value [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
Here I have a form:
<form action="includes/Payment.inc.php" method="get" class="px-4 py-4" >
<div class="form-group">
<div class="d-inline py-1"><h5>Payment Type</h5></div>
<select class="bg-white text-dark" name="payment_type">
<option value="Type">Type</option>
<option value="Food">Food</option>
<option value="House-Rent">House-Rent</option>
<option value="Other">Other</option>
</select>
<h5 class="py-1">Amount of Money</h5>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="text" class="form-control" name="amount" aria-label="Text input with checkbox">
<span class="input-group-addon">JPY</span>
</div>
<h5 class="py-1">Detail</h5>
<textarea placeholder="Enter The Detail in here" name="detail"></textarea><br>
<label><h5 class="py-1">Date: </h5></label>
<input type="date" name="date"><br>
<button type="submit" name="submit" class="btn btn-primary m-4 border rounded">Submit</button>
</div>
</form>
When clicked simply put all the information into database with following PHP code:
<?php
if (isset($_GET['submit'])) {
include_once 'dbh.inc.php';
$payment_type = $_GET['payment'];
$amount_money = filter_input(INPUT_GET,'amount',FILTER_SANITIZE_NUMBER_INT);
$detail = filter_input(INPUT_GET,'detail',FILTER_SANITIZE_STRING);
$date = $_GET['date'];
if (empty($amount_money)) {
header('Location: ../Data.php?money_empty');
exit();
}
else {
$sql = "INSERT INTO payment(payment_type,amount,detail,payment_date)
VALUES (':payment_type',':amount',':detail',':payment_date')";
$result = $conn->prepare($sql);
$result->bindParam(':payment_type',$payment_type,PDO::PARAM_STR);
$result->bindParam(':amount',$amount_money,PDO::PARAM_INT);
$result->bindParam(':detail',$detail,PDO::PARAM_STR);
$result->bindParam(':payment_date',$date,PDO::PARAM_STR);
$result->execute();
header("Location: ../Data.php?payment_success");
exit();
}
}
Then when I test the form, the execution is completed but when I checked the "payment" table, here's what i got:
payment_type(varchar) = ":payment_type"
amount(int) = 0
detail(varchar) = ":detail"
payment_date(date) = "0000-00-00".
What's wrong with my code ??
In your code, you use '' to eclosed the string part in insert parameters this not need with PDO. Use the following instead...
<?php
if (isset($_GET['submit'])) {
include_once 'dbh.inc.php';
$payment_type = $_GET['payment'];
$amount_money = filter_input(INPUT_GET,'amount',FILTER_SANITIZE_NUMBER_INT);
$detail = filter_input(INPUT_GET,'detail',FILTER_SANITIZE_STRING);
$date = $_GET['date'];
if (empty($amount_money)) {
header('Location: ../Data.php?money_empty');
exit();
}
else {
$sql = "INSERT INTO payment(payment_type,amount,detail,payment_date)
VALUES (:payment_type,:amount,:detail,:payment_date)";
$result = $conn->prepare($sql);
$result->bindParam(':payment_type',$payment_type,PDO::PARAM_STR);
$result->bindParam(':amount',$amount_money,PDO::PARAM_INT);
$result->bindParam(':detail',$detail,PDO::PARAM_STR);
$result->bindParam(':payment_date',$date,PDO::PARAM_STR);
$result->execute();
header("Location: ../Data.php?payment_success");
exit();
}
}
You are quoting your parameter markers, eg ':payment_type', which makes them look like plain strings to PDO, so those strings are what show up in the DB. As the docs show, you should not quote them:
$sql = "INSERT INTO payment(payment_type,amount,detail,payment_date)
VALUES (:payment_type, :amount, :detail, :payment_date)";

Update Statement mySQL issues

I am having trouble updating the posts table of my database when a user updates a blog post they have made.
Flow of events - user makes a blog post, its saved to DB then they can go back and edit it. Edit brings up a pre-filled html form populated with data from the posts table. Then the user can change the title and content and when they press update the posted values from the form should replace the title and content of the original post in posts DB all other columns remain unchanged.
Currently my database just doesn't seem to update, not sure why. Using a combination of html/php/sql/pdos to execute sql statements - getting very complex for my novice experience and any help is appreciated.
Code (UPDATE statement is at bottom and most problematic):
// begin edit post
if(isset($_GET['editPost'])) {
$editPostId = $_GET['editPost'];
$sqlEditPostCheck = <<<EOD
SELECT author, id FROM posts WHERE author = '$currentUserId'
EOD;
$stmtEditPostCheck = $pdo->prepare($sqlEditPostCheck);
$stmtEditPostCheck->execute();
$ableToEdit = false;
while ($row = $stmtEditPostCheck->fetch(PDO::FETCH_ASSOC)) {
if($editPostId === $row['id'] && $currentUserId === $row['author']) { $ableToEdit = true; }
}
if($ableToEdit === true) {
$editPost_Title = "";
$editPost_Content = "";
$sqlEditPostPreFills = <<<EOD
SELECT id, post_title, content FROM posts WHERE id="$editPostId"
EOD;
$stmtEditPost = $pdo->prepare($sqlEditPostPreFills);
$stmtEditPost->execute();
while ($row = $stmtEditPost->fetch(PDO::FETCH_ASSOC)) {
$editPost_Title = $row['post_title'];
$editPost_Content = $row['content'];
$editPostId = $row['id'];
}
$content = <<<EOD
<form action="?profile&editPost="$editPostId" method="post">
<h1>Edit Post</h1>
<div class="form-group">
<input name="Epost_title" type="text" id="Epost_title" value="$editPost_Title" class="form-control">
</div>
<div class="form-group">
<textarea class="form-control" name="Epost_content" id="Epost_content" value="" rows="6">$editPost_Content</textarea>
</div>
<div style="text-align: right;">
<button type="submit" name="update" style="width: 30%;" class="btn btn-success btn-lg">Update</button>
</div>
</form>
<hr />
EOD;
} // end IF ableToEdit
$updatedContent = "";
if(isset($_POST['Epost_content'])) { $updatedContent = $_POST['Epost_content']; }
$updatedTitle = "";
if(isset($_POST['Epost_title'])) { $updatedTitle = $_POST['Epost_title']; }
if(isset($_POST['Epost_content']) && isset($_POST['Epost_title'])) {
$sqlUpdatePost = <<<EOD
UPDATE posts SET post_title='$updatedTitle', content='$updatedContent' WHERE posts.id='$editPostId' AND posts.author='$currentUserId';
EOD;
$stmtUpdate = $pdo->prepare($sqlUpdatePost);
$stmtUpdate->execute();
}
}
// end edit post
This line look bad for me
<form action="?profile&editPost="$editPostId" method="post">
try to change it to
<form action="?profile&editPost=\"$editPostId\" method=\"post\">"

Categories