Update Statement mySQL issues - php

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\">"

Related

I need help for my mailing system(PHP, JS, HTML) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed yesterday.
Improve this question
I am currently working on a mailing/messaging system. Now I want to send a message, but I want to add more recipients, but I can't do this. It would be kind if one of you would like to help me.
I would like each message(body, from and subject) to be in a separate table. And that the message id and to(and if there are multiple recipients that it creates multiple rows.) come in another table.
(My English is not so good, so sorry if there are spelling mistakes).
// JS for the to-tags.
function parse() {
var tag_input = document.getElementById("tags_input");
var tags = document.getElementById("tags");
//
var input_val = tag_input.value.trim();
var no_comma_val = input_val.replace(/,/g, "");
//
if (input_val.slice(-1) === "," && no_comma_val.length > 0) {
var new_tag = compile_tag(no_comma_val);
tags.appendChild(new_tag);
tag_input.value = "";
}
}
function compile_tag(tag_content) {
let a = -3;
var tag = document.createElement("p");
//
var text = document.createElement("span");
text.setAttribute("class", "badge badge-success");
text.setAttribute("id", tag_content);
text.innerHTML = tag_content;
//
var remove = document.createElement("i");
remove.setAttribute("class", "fa fa-remove");
remove.setAttribute("id", "remove");
remove.onclick = function() {this.parentNode.remove();};
//
tag.appendChild(remove);
tag.appendChild(text);
//
return tag;
}
// HTML AND PHP
<?php
session_start();
include_once("error.php");
include "db.php";
if (isset($_SESSION['login'])){
?>
<?php
$functions = array('newMessage');
if (isset($_GET['action'])){
if (in_array($_GET['action'], $functions)){
function newMessage(){
// when on the button press
if (isset($_POST['button_send'])) {
global $conn;
// take the user id
$from = $_SESSION['id'];
// create table one
$create = "INSERT INTO `messages` SET
`messageFrom` = '$from',
`messageSubject` = '".mysqli_real_escape_string($conn, $_POST['inp_subject'])."',
`messageBody` = '".mysqli_real_escape_string($conn, $_POST['textarea_body'])."'
";
// when table one is created make table to. **This is where things go wrong**
if (mysqli_query($conn, $create)){
if ($create = true){
$read = mysqli_query($conn, "SELECT * FROM `blog` WHERE `messageSubject` = '$_POST['inp_subject']' AND `messageFrom` = '$from' ");
$data = mysqli_fetch_assoc($read);
$id = $data['messageId'];
$create = "INSERT INTO `receivers` SET
`messageId` = '$id',
`messageSubject` = '".mysqli_real_escape_string($conn, $_POST['inp_subject'])."',
`messageBody` = '".mysqli_real_escape_string($conn, $_POST['textarea_body'])."'
"; if (mysqli_query($conn, $create)){
echo "fine";
}else{
echo 'Sorry, '.mysqli_error($conn);
}
}else{
echo 'Sorry, '.mysqli_error($conn);
}
}else{
echo 'Sorry, '.mysqli_error($conn);
}
}
?>
<form method="post">
<div class="from_group">
<input type="text" name="inp_to" id="inp_to" placeholder="Give the name(s)..." required>
<label>To:</label>
</div>
// The TO-input
<div class="container">
<div class="col-sm-6">
<input onkeyup="parse();" type="text" id="tags_input" placeholder="comma-separated tags" maxlength="100" class="form-control">
</div>
// the to tags
<div class="col-sm-6" id="tags" name="tags">
</div>
</div>
<script src="js/input_comma.js"></script>
<div class="from_group">
<input type="text" placeholder="Give the subject..." name="inp_subject" required>
<label>Subject: </label>
</div>
<div class="from_group">
<textarea name="textarea_body" rows="10" cols="30">
</textarea>
</div>
<button name="button_send"> Send </button>
</form>
</div>
<?php
}
echo $_GET['action'] ();
}else{
functionNotfound();
}
}
?>
<?php
}else{
notLoggedin();
}
?>
Already thanks for the help.
I would like each message(body, from and subject) to be in a separate table. And that the message id and to(and if there are multiple recipients that it creates multiple rows.) come in another table.

Display related info in redirected page without reloading when clicked on particular image or text

I want to explain my doubt with an example
Lets say i got movie database where i stored info related to particular movie in each row.
Lets say i got two rows in my database
1) Titanic 1997 Romance, Thriller
2) Avatar 2009 Action, Fantasy, Romance
I have homepage.php where movie images with text below it are displayed as gallery and i got a movieinfo.php page where all the info about movie is present.
Ex :
Title : "Titanic"
Release Date : "1997"
Genre : "Romance, Thriller"
etc
Now when i clicked on titanic image(which is in my homepage.php) it should redirect to movieinfo.php and get the titanic info from database with id and should display related info of titanic in those double quotes " " (nothing should be changed in movieinfo.php other than those values placed in double quotes).
And same should be happen when i click on avatar image
I tried to change that info with php but it gets last imported data from database and displays that info.
After some research i found that it is possible with AJAX but i am absolute beginner with AJAX. Need someone's help to know the logic and it will be more helpful if you give me small code with above example
Thank you
I have created example code so that i can get help from you
Lets say this is my moviedb.php(which contains movie insertion php code)
<?php
$title = "";
$releaseDate = "";
$Genre = "";
if (isset($_POST['submit-btn'])) {
if (empty($_POST['title'])) {
$errors['title'] = 'Title required';
}
if (empty($_POST['genre'])) {
$errors['genre'] = 'Genre required';
}
if (empty($_POST['releaseDate'])) {
$errors['releaseDate'] = 'Release Date required';
}
$title = $_POST['title'];
$releaseDate = $_POST['releaseDate'];
$genre = $_POST['genre'];
// Check if title already exists
$sql = "SELECT * FROM movie WHERE movie_title='$title' LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$errors['title'] = "Title already exists";
}
if (count($errors) === 0) {
$query = "INSERT INTO movie SET movie_title=?, movie_releaseDate=?, movie_genre=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('sss', $title, $releaseDate, $genre);
$result = $stmt->execute();
if ($result) {
$movie_id = $stmt->insert_id;
$stmt->close();
$_SESSION['movie_id'] = $movie_id;
$_SESSION['title'] = $title;
$_SESSION['releaseDate'] = $releaseDate;
$_SESSION['genre'] = $genre;
$_SESSION['message'] = 'Movie has been inserted succesfully!';
header('location: movieinsertion.php');
} else {
$_SESSION['error_msg'] = "Database error: Could not insert movie";
}
}
}
?>
This is movieinsertion.php (which contains form to enter movie details to database )
<form action="movieinsertion.php" method="post">
<label for="title"><b>Title : </b></label>
<input type="text" placeholder="Enter Title" name="title" required>
<label for="releaseDate"><b>Release Date : </b></label>
<input type="text" placeholder="Enter Release Date" name="releaseDate" required>
<label for="genre"><b>Genre : </b></label>
<input type="text" placeholder="Enter Genre" name="genre" required>
<div class="clearfix">
<button type="submit" class="submitbtn" name="submit-btn" id="submit-btn">Movie insert</button>
</div>
</form>
This is movieinfo.php (where movie info is displayed)
<p class="movieinfo">
<b style="font-size:20px; color:tomato;"> Title : </b> <?php echo $_SESSION['title']; ?>
<br/>
<b> Release Date : </b> <?php echo $_SESSION['releaseDate']; ?>
<br/>
<b> Genre : </b> <?php echo $_SESSION['genre']; ?>
</p>
This is homepage.php (Where movie images are placed using anchor tag)
<div class="movieimg">
<a href = "movieinfo.php"> <img src="assets/image-1.jpg" alt="Titanic" style="width:100%">
<div class="text">Titanic</div></a>
</div>
<div class="movieimg">
<a href = "movieinfo.php"> <img src="assets/image-2.jpg" alt="Avatar" style="width:100%">
<div class="text">Avatar</div></a>
</div>

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. ;)

PHP posting values but database not updating [duplicate]

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

Categories