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

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>

Related

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

Having issues getting uploaded images to display on output page PHP

I cannot get an uploaded image to display on the output page with the other text-based information. I am very new to working with PHP and I am working on a practice project that enables a user to upload blog posts about products.
There is a form where the user submits information and an uploaded image. That information gets posted to another page with the blog posts. My issue is getting the image to show on the page with the rest of the output.
I'm probably making simple, really stupid mistakes. But after looking at this for so long, I'm unable to figure it out myself. I've tried googling everything I can think of in "upload and display images php" realm, and nothing has helped.
If anyone could help point me in the right direction, I would greatly appreciate it.
There is one page for the upload form, newpost.php
here is the PHP for that:
<?php
session_start();
$msg = "";
include('../includes/db_connect.php');
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit();
}
if(isset($_POST['submit'])){
$target ="images/".basename($_FILES['image']['name']);
$title = $_POST['title'];
$price = $_POST['price'];
$description = $_POST['description'];
$category = $_POST['category'];
$uploads_dir = 'image/';
$image = basename($_FILES['image']['name']);
$title = $db->real_escape_string($title);
$price = $db->real_escape_string($price);
$description = $db->real_escape_string($description);
$user_id = $_SESSION['user_id'];
$description = htmlentities($description);
if($title && $price && $description && $category && $image){
$query = $db->query("INSERT INTO post (user_id, title, price, description, category_id, image) VALUES('$user_id', '$title', '$price', '$description', '$category', '$image')");
if($query){
echo "product posted";
}else{
echo "error";
}
}else{
echo "missing data";
}
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)){
$msg = "Image uploaded successfully";
}else{
$msg = "There was an error uploading the file";
}
}
?>
and here is the HTML form:
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label>TITLE *</label>
<input type="text" name="title" class="form-control"
placeholder="Product title here" required>
</div>
<div class="form-group">
<label>PRICE *</label>
<input type="text" name="price" class="form-control"
placeholder="Enter with the following format: 0.00 " required>
</div>
<div class="form-group">
<label>CATEGORY</label>
<select name="category" class="form-control">
<?php
$query = $db->query("SELECT * FROM categories");
while($row = $query->fetch_object()){
echo "<option value='".$row->category_id."'>".$row->category."</option>";
}
?>
</select>
</div>
<div class="form-group">
<label>PRODUCT DESCRIPTION *</label>
<textarea type="textarea" name="description" class="form-control" placeholder="Write a description of the product here" required></textarea>
</div>
<div class="form-group">
<label>IMAGE(S) *</label>
<input type="hidden" name="size" value="1000000">
<input type="file" name="image">
</div>
<div class="required">
* indicates a required field
</div>
<button type="submit" name="submit" value="Submit" class="btn btn-default">POST PRODUCT</button>
</form>
Now here is the PHP for the page where the posts display:
<?php
include('includes/db_connect.php');
$query = $db->prepare("SELECT post_id, title, price, description, image FROM post");
$query->execute();
$query->bind_result($post_id, $title, $price, $description, $image);
?>
And here is my HTML so far. THIS IS WHERE MY ISSUE IS.
<?php
while ($query->fetch()):
?>
<article>
<h2><?php echo $title?></h2>
<p>$<?php echo $price?></p>
<p><?php echo $description?></p>
<!-- I'm trying to get my image to show here and am having issues with that. The above information is visible and working as it should. The images just show up as broken image icons /-->
<p><?php echo "<img src='images/".$image."' >";?></p>
</article>
<?php endwhile?>
Here is my sql table I am working from for the post:
CREATE TABLE `post` (
`post_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`price` text NOT NULL,
`category_id` int(11) NOT NULL,
`description` text NOT NULL,
`posted` datetime NOT NULL,
`image` varchar(300) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Thank you to anyone who looks at this an offers advice. I really appreciate it.
Shouldn't it be:
<p><?php echo "<img src='post/".$image."' >";?></p>
Have you looked that the image exists in the 'images' directory?
Have you looked in the database, that the image is correct there?
You can use phpmyadmin for this.

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

Update a query by substracting a multiplicated number and using where

I'm making a paid to click website and I'm looking to update a query by substracting and a multiplicated number.
I'm trying to get the users to buy some ads package, they enter the views count and the cost per view, then when they click on "Submit", it should update the user in the current session. However, it's not working: it's updating all the users balances.
Here's my code :
<?php
session_start();
require_once '../constants/initSite.php';
$siteConstant->addFile('css', 'account.css');
echo $siteConstant->getHead();
echo $siteConstant->getMenu();
if(isset($_SESSION['username']) && isset($_SESSION['password'])){
require_once '../constants/class.DatabaseConstants.php';
require_once '../class/class.DBase.php';
$done = false;
$db = new DatabaseConstants();
$dBase = new DBase($db->getHost(), $db->getUser(), $db->getPass());
$dBase->setDatabaseName($db->getDb());
if(!$dBase->connectDatabase()){
die('SQL ERROR at db class vd fn');
}
$userQuery = mysqli_query($dBase->getDbobj(), "SELECT * FROM members WHERE username=\"".$_SESSION['username']."\"");
if(mysqli_num_rows($userQuery)){
$userData = mysqli_fetch_assoc($userQuery);
}else{
die('User Not Found!');
}
if(isset($_POST['submit'])){
$adquery = 'INSERT INTO ads (Title,Link,ViewLimit,Pays) VALUES ("'.$_POST['title'].'","'.$_POST['link'].'","'.$_POST['views'].'","'.$_POST['pays'].'")';
mysqli_query($dBase->getDbobj(), $adquery);
if(!mysqli_affected_rows($dBase->getDbobj())<1){
$done = true;
}
$id = 0;
$qryE = mysqli_query($dBase->getDbobj(), 'SELECT Id FROM ads');
while($dataE = mysqli_fetch_assoc($qryE)){
$id = $dataE['Id'];
}
$userQueryE = mysqli_query($dBase->getDbobj(),'SELECT id FROM members');
while($userDataE = mysqli_fetch_assoc($userQueryE)){
mysqli_query($dBase->getDbobj(), 'INSERT INTO view (MemberId,AdId) VALUES ("'.$userDataE['id'].'","'.$id.'")');
}
$userquery = ('UPDATE members SET balance=("'.$userData['balance'].'" - "'.$_POST['views'].'" * "'.$_POST['pays'].'") WHERE username="'.$_SESSION['username'].'"') ;
$userData = mysqli_fetch_assoc($userQuery);
}
?>
<center><img style="margin-bottom:5px"src="../image/ad468x60.png"/></center>
<div id="maincontent" style="height:35em">
<center>
<ul id="menu2">
<li>Account Details</li>
<li>Add Advertisement</li>
<li>Request Payment</li>
<li>Referrals</li>
<li>Account Setting</li>
</ul>
<br>
</center>
<center><p style="color:#0481b1;"><b><u>Add Advertisements</u></b></p></center>
<form id="msform" method="POST" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<center>
<?php
if(isset($_POST['submit']) && !$done){
echo '<h3 style="color:red;">Something went wrong!</h3>';
}
if ($done){
echo '<h3 style="color:green;">Advertisement Added and is Active.</h3>';
}
?>
<?php
if($userData['balance'] < 5 ){
echo '<h3 style="color:red;">insufficient balance</h3></br>
<h2 style="color:red;text-decoration:underline">You currently have '.$userData['balance'].' '.$siteData['currency'].' </h2>
<center><h2 style="color:red">You do not have enough balance to add an advertissement.<br><br>You need to have at least 5 '.$siteData['currency'].' in your account balance to add an advertissement.</h2></center>';
}
else {
echo'
Title <input type="text" name="title" placeholder="Enter Site Title" required="true"/> <br><br>
Link <input type="text" name="link" placeholder="Enter Site Link" required="true"/><br><br>
Number of Viewers to send<input type="text" name="views" min="100" placeholder="Enter number of views to send(100 Views Minimum)" required="true"/><br><br>
Reward per view<input type="text" name="pays" min="0.00001" placeholder="Enter reward per view(0.00001 '.$siteData['currency'].' Minimum)" required="true"/><br><br>
<input type="submit" name="submit" class="NormButton" Value="Submit" /> ' ;
}
?>
</center>
</form>
</div>
<?php
require_once '../main/footer.php';
$dBase->closeDatabse();
}else{
header('location: index.php');
}
echo $siteConstant->getTail();
Why is your where clause is before SET
Check this
"UPDATE members SET balance=($userData['balance'] - $_POST['views'] * $_POST['pays']) WHERE username=$_SESSION['username']"

Categories