Display of database fetched data in HTML through PHP - 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

Related

Problem: Can't update the db value type text when i change the content of text area

I'm trying to update the variable description with the value of the textarea.
Here is my html:
<form action="index.php" method="post">
<div class="search">
<label for="animalId">Search for Id</label><br>
<input type="text" name="animalId" value="<?php echo $animalId; ?>">
</div>
<div class="animal_description">
<label for="animalDescription">Animal's description:</label><br>
<textarea name="animalDescription" id="animal-Description" cols="30" rows="10"><?php echo
$animalDescription; ?></textarea>
</div>
<button type="submit" name="Update">Update</button>
</form>
Here is my php code to update the description variable:
//if the update button is clicked
if (isset($_POST['update'])) {
//getting variable
$animalId = $_POST['animalId'];
$animalDescription = $_POST['animalDescription'];
//checking if any empty field
if(empty($animalId)){
$ERRORS['animal-description'] = "The id field is requiered";
}
else {
$idQuery = "UPDATE animals SET description='$animalDesription' WHERE id_num='$id'";
$stmt = $conn->prepare($idQuery);
if ($stmt->execute()) {
$ERRORS['final-message'] = "Successfully updated the database";
}
else {
$ERRORS['final-message'] = "Failed to connect";
}
}
}
When I enter an existent Id and some text in the textarea, it does nothing just refresh the page.
Try:
<form action="index.php" method="post">
<div class="search">
<label for="animalId">Search for Id</label><br>
<input type="text" name="animalId" id = "animalId" value="<?php echo
$animalId; ?>">
</div>
<div class="animal_description">
<label for="animalDescription">Animal's description:</label><br>
<textarea name="animalDescription" id="animalDescription" cols="30"
rows="10"><?php echo
$animalDescription; ?></textarea>
</div>
<button type="submit" name="Update">Update</button>
</form>
//if the update button is clicked
if (isset($_POST['Update'])) {
//getting variable
$animalId = $_POST['animalId'];
$animalDescription = $_POST['animalDescription'];
//checking if any empty field
if(empty($animalId)){
$ERRORS['animal-description'] = "The id field is requiered";
} else {
$idQuery = "UPDATE animals SET description=? WHERE
id_num=?";
$stmt = $conn->prepare($idQuery);
$stmt->bind_param("si", $animalDescription, $animalId);
if ($stmt->execute()) {
$ERRORS['final-message'] = "Successfully updated the database";
}
else {
$ERRORS['final-message'] = "Failed to connect";
}
}
}

How do you format php in html?

I have a simple test.php script:
<?php
$name = $_GET['name'];
$response = "Hi, ".$name."! How are you?";
echo $response;
?>
I know I can echo the html script in the php like: echo "<b>".$response."</b>"; but how can I just return the $response to my html page, and in the html page, it format the $response string?
I have a index.html page:
<title>Your name</title>
<center>Welcome to the coolest page ever</center>
<br>
"The PHP $response goes here"
<br>
<u>This is the footer</u>
As you can see, there is a html page with a template, and the response is required on one spot only (in the middle of the page). I don't want to echo the entire html script.
If I put the php script into the html, then my php script is exposed...
Example link: www.domain.com/test.php?name=John
save this page with whatever.php.
<html>
<title>Your name</title>
<body>
<center>Welcome to the coolest page ever</center>
<br>
<?php if(isset($_GET['name'])) { $response = "Hi, ".$_GET['name']."! How are you?";
echo $response;}
?>
<br>
<u>This is the footer</u>
</body></html>
You can put the html in your php page test.php
Here is an example of how I have used echo inside of html to display a value
First do your php to connect to your database and execute whatever query you want
I use includes as well to make dealing with the header/Navigation and footer simple for every page. Instead of having to have that code inside of your test.php page you can create separate pages and just include them. That way if you want to edit your header or footer you can do it in one place and it will change for all of your pages.
As you will see in my html you can then put the echo value into the html like so value="
//php code begins here
<?php
include_once 'header.php';
$sql = "SELECT * FROM `person` WHERE person_id = " .$user_id." ";
$conn = mysqli_connect( $dbServername , $dbUsername , $dbPassword , $dbName );
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "user_id: " . $row["person_id"]. " - person_id: " . $row["person_first"]. " " . $row["person_last"]. "<br>";
$person_id = $row["person_id"];
$person_first = $row["person_first"];
}
} else {
echo $sql;
}
$conn->close();
?>
//first php section ends here
//html section starts here
<div class="form-group">
<label class="col-md-12">First Name</label>
<div class="col-md-12">
<input type="text" required="" name="person_first" value="<?php echo $person_first;?>" class="form-control form-control-line"> </div>
</div>
<div class="form-group">
<label class="col-md-12">Last Name</label>
<div class="col-md-12">
<input type="text" required="" name="person_last" value="<?php echo $person_last;?>" class="form-control form-control-line"> </div>
</div>
<div class="form-group">
<label for="example-email" class="col-md-12">Mobile</label>
<div class="col-md-12">
<input type="text" required="" name="person_mobile" value="<?php echo $person_mobile;?>" class="form-control form-control-line"> </div>
</div>
<div class="form-group">
<label for="example-email" class="col-md-12">Address</label>
<div class="col-md-12">
<input type="address" required="" name="person_address" value="<?php echo $person_address;?>" class="form-control form-control-line"> </div>
</div>
<div class="form-group">
<label class="col-md-12">Email</label>
<div class="col-md-12">
<input type="text" required="" name="person_email" value="<?php echo $person_email;?>" class="form-control form-control-line"> </div>
</div>
<div class="form-group">
<label class="col-md-12">SSN</label>
<div class="col-md-12">
<input type="text" required="" name="SSN" value="<?php echo $SSN;?>" class="form-control form-control-line"> </div>
</div>
//html ends here
//php footer code starts here
<?php
include_once 'footer.php';
?>
// php footer ends here
Begin code for new page header.php
<?php
include 'includes/dbh.php';
session_start();
if (!isset($_SESSION["u_id"]))
{
header("location: login.php");
}
$user_id = $_SESSION['u_id'];
echo "UserID is '".$user_id."'";
$sql = "SELECT * FROM users WHERE user_id='$user_id'";
// $sql = "SELECT SINGLE `user_id` FROM `users` WHERE user_id = '".$user_id."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "user_id: " . $row["user_id"]. " - Name: " . $row["user_first"]. " " . $row["user_last"]. "<br>";
$displayname = $row["user_first"]. " " . $row["user_last"];
$email = $row["user_email"];
$uid = $row["user_uid"];
}
} else {
echo "0 results";
}
$sql = "SELECT * FROM players WHERE player_id=$user_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "player_id: " . $row["player_id"]. " - player_id: " . $row["player_first"]. " " . $row["player_last"]. "<br>";
$player_id = $row["player_id"];
$player_first = $row["player_first"];
$player_last = $row["player_last"];
$player_mobile = $row["mobile"];
$player_address = $row["player_address"];
$player_city = $row["city"];
$player_state = $row["state"];
$player_zip = $row["zip"];
$player_dob = $row["dob"];
$player_gender = $row["gender"];
}
}
$conn->close();
?>
End header.php

Can't upload file in BLOB to the database, Directory issues in PHP

I'm having difficulties to insert the value as blob type always empty and the other method can't insert the images in a folder. Please you can show the way out. Thanks! This code is to save the image in a folder and then access it with the name to display, but is not saving the photos to the folder. I edited and include the form here, containing JavaScript and css .It looks some how messy but i'm a beginner. Thanks.
<?php
include("../views/post_form.php");
require("../includes/include.php");
require("../includes/sess_n.php");
if ($_SERVER["REQUEST_METHOD"]== "POST")
{
$usertext = $_POST["usertext"];
$image = $_FILES['image']['name'];
$talent =$_POST["talenttype"];
if(empty($usertext) || empty($image)|| empty($talent))
{
die();
}
$id = $_SESSION["id"];
$folder ="images/".basename($_FILES['image']['name']);
move_uploaded_file($_FILES['image']['tmp_name'],$folder) ;
$query = mysqli_query($link,"SELECT * FROM `upload` WHERE id = '$id'");
$upload = mysqli_query($link,"INSERT INTO `upload` (description,image,talent,folder) VALUES('$usertext','$image','$talent','$folder ')");
}
?>
To display, I want the photos to be save to the folder, not saving. I used blob method not inserting into the database.
<?php
include("../views/feeds_form.php");
require("../includes/include.php");
require("../includes/sess_n.php");
$query = mysqli_query($link,"SELECT * FROM `upload` ");
if ($query === false)
{
die();
}
echo '<table>';
while ($run = mysqli_fetch_assoc($query))
{
echo '<tr>';
echo '<td>';?> <img src =" <?php echo $run["image"]; ?>" height=100 width=100> <?php echo '<td>';
echo '<td>'; echo $run["description"]; echo '<td>'; echo $run["folder"];echo '<td>';
echo '</tr>';
}
echo '</table>';
?>
The form here.
<?php
include("../public/header.php");
?>
<div><title>post</title></div>
<style>
.form-inline
{
text-align: center;
margin-bottom: 50px;
}
</style>
<script type="text/javascript">
function validate(){
var usertext = document.getElementById("usertext");
var talent = document.getElementById("talenttype");
var image = document.getElementById("image");
if (usertext.value === "" && talent.value === "" && image.value ==="")
{
alert("Field Must Not be Empty");
}
}
</script>
<form class="form-inline" method ="POST" action ="post.php" enctype="multipart/form-data" onsubmit= "return validate();">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3"> </label>
<textarea class="form-control" id = "usertext" name ="usertext" rows="5" placeholder="Describe Person Here"></textarea> <br><hr>
<label class="sr-only" for="exampleInputEmail3"></label><br>
<div class="form-group">
<label for="exampleInputPassword1"></label>
<input type="file" class="form-control" id = "image" id="exampleInputPassword1" name="image" placeholder="image">
</div> <br><br><br> <hr>
<div class="form-group">
<label for="exampleInputPassword1"></label>
<input type="text" class="form-control" id = "talenttype" id="exampleInputPassword1" name = "talenttype" placeholder="Talent-Type"><br><br>
</div> <hr>
<div>
<button type="submit" name ="post" class="btn btn-default">Post</button><br>
</div>
</div>
</form>
<?php
include("../public/footer.php");
?>
I was having permission issues, the images folder permission was changed. That solves everything. Thanks!

My search form does not seem to work

I want my search form to display users(username,firstname or lastname) from my database and display them as the user is typing like how facebook and twitter do but when i click search,nothing happens.Here are 2 parts of my header inc that deal with the search form,1st part:
<?php
include( "Connect.php" );
ob_start(); session_start();
if (isset($_SESSION['user_login'])) {
$user = $_SESSION["user_login"];
}
else {
$username = "";
}
$output = "";
//Collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = $mysqli->query("SELECT * FROM users WHERE first_name LIKE '%$searchq%' OR last_name LIKE '%$searchq%'") or die("could not search!");
$count = mysqli_num_rows($query);
if($count == 0) {
$output = 'There was no search results!';
} else {
while($row = mysqli_fetch_array($query)) {
$fname = $row['first_name'];
$lname = $row['last_name'];
$id = $row['id'];
$output .= '<div> '.$fname.' '.$lname. '</div>';
}
}
}
?>
2nd part:
<form id="searchForm">
<fieldset>
<div class="input">
<p>
<form action="header inc.php" method="post">
<input type="text" class="Search" id="search" size="35" placeholder="Search username,fullname or topic"/>
<label for="Submit"></label>
<input type="submit" name="search" value="Go" id="search" />
</p>
</div>
</form>
<?php print ("$output"); ?>
invalid action name
action="header inc.php"
you cannot use space in .php files
Edit the filename as headerInc.php and pass it in the form as:
action="headerInc.php"
I have changed your html code , just use it and it will start working. In your html there is hierarchy of form tag , I have added method post to first form and I have replaced the name of the text field by submit button name. In each post your data value was "go".
I hope it will resolve your problem :
<form id="searchForm" method="post">
<fieldset>
<div class="input">
<p>
<form action="header inc.php" method="post">
<input type="text" class="Search" name="search" id="search" size="35" placeholder="Search username,fullname or topic"/>
<label for="Submit"></label>
<input type="submit" value="Go" id="search_button" />
</p>
</div>
</form>
<?php echo $output; ?>

How to add action tag to form?

I have a working php guestbook script. It's only 1 file. I tried to validate it and there is only one error:
Line 147, Column 36: required attribute "action" not specified
<form method="post" name="blogform">
Now the code is this and I'm sure I would need to break up the file to two so that I can create a file for the action tag but I just don't know how. Any help is much appreciated.
<?php
session_start();
include("../../4a/inc/opendb.inc.php");
if(isset($_POST['send'])) //checks if $_POST variable "is set"
if(isset($_SESSION["ellenorzo"]) && !empty($_SESSION["ellenorzo"]) && $_SESSION["ellenorzo"]==$_POST["code"]){
$name = trim($_POST['name']); //eliminating whitespaces
$email = trim($_POST['email']);
$message = addslashes( trim($_POST['message']));
$query = "INSERT INTO blog (name, email, message, date) " .
"VALUES ('$name', '$email', '$message', NOW())";
mysql_query($query) or die('Hey, something is wrong!' . mysql_error());
header('Location: ' . $_SERVER['REQUEST_URI']);
exit;
}
?>
<?php
include('../../4a/inc/head.inc.php');
?>
<body style="color: #ffffff;">
<div class="mainblog">
<div class="top">
<div class="menu">
<?php
include('../menu.inc.php');
?>
</div>
</div>
<div class="middleblog">
<form method="post" name="blogform">
<input name="name" id="name" class="nameblog" type="text" />
<img src="../../4a/img/main/name.jpg" class="name" alt="Name" />
<input name="email" id="email" class="emailblog" type="text" />
<img src="../../4a/img/main/email.jpg" class="email" alt="Email" />
<textarea name="message" id="message" class="messageblog" rows="6" cols="6" onkeyup="return ismaxlength(this)">
</textarea>
<img src="../../4a/img/main/message.jpg" class="message" alt="Message" />
<input name="send" value="submit" id="send" class="sendblog" type="image" src="../../4a/img/main/send.jpg" onclick="return checkform();" />
<input type="hidden" name="send" value="submit" />
<div class="text_check_code">
<font class="text">
Enter the characters as they are shown below.
</font>
</div>
<img src="../../4a/inc/secure.inc.php" class="img_check_code" alt="Nospam" />
<input name="code" class="input_check_code" />
</form>
<?php
$rowsperpage = 10;
$pagenumber = 1;
if(isset($_GET['page']))
{
$pagenumber = $_GET['page'];
}
$offset = ($pagenumber - 1) * $rowsperpage;
$query = "SELECT id, name, email, message, date ".
"FROM blog ".
"ORDER BY id DESC ".
"LIMIT $offset, $rowsperpage";
$result = mysql_query($query) or die('Hey, something is wrong!. ' . mysql_error());
if(mysql_num_rows($result) == 0)
{
print("<br /><br /><br /><br /><br /><br /><br /><br />The blog is empty.");
}
else
{
while($row = mysql_fetch_array($result))
{
list($id, $name, $email, $message, $date) = $row;
$name = htmlspecialchars($name);
$email = htmlspecialchars($email);
$message = htmlspecialchars($message);
$message = stripslashes(nl2br($message)); //real breaks as user hits enter
?>
<br />
<div class="blogentries">
<b><?=$name?></b>
<br />
<?=$message?>
<br />
<i><?=$date?></i>
</div>
<br />
<?php
} //closing while statement
$query = "SELECT COUNT(id) AS numrows FROM blog";
$result = mysql_query($query) or die('Hey, something is wrong!. ' . mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];
$maxpage = ceil($numrows/$rowsperpage); //rounding up any integer eg. 4,1=5
$nextlink = '';
if($maxpage > 1)
{
$self = $_SERVER['PHP_SELF'];
$nextlink = array();
for($page = 1; $page <= $maxpage; $page++)
{
$nextlink[] = "$page";
}
$nextlink = "Next: " . implode(' » ', $nextlink); //returns all elements of an array as a string
}
include ("../../4a/inc/closedb.inc.php");
?>
<br />
<div class="nextlink">
<?=$nextlink;?>
</div>
</div>
<br />
<br />
<div class="bottomblog">
<?php
require_once('../../4a/inc/copyright.inc.php');
?>
</div>
<br />
<br />
</div>
<?php //closing the else statement
}
?>
<?php
include('../../4a/inc/footer.inc.php');
?>
The action property specifies the link the form is sent to. If the form calls itself you can leave it blank:
<form action="" method="post" name="blogform">
The action tag tells the form where to submit the data. If it is left blank, it will attempt to submit the data to the current php page. If it's giving you trouble, perhaps you need to specify it and point it to the php page that generates the form.
In the code you provided, the bit of code which handles new inserts is at the top of this page, so you should set the action tag to be the name of the page.
By the way, you should ensure that your inputs are all cleaned; just using trim() before inserting them is asking for trouble. See here for more on this topic.

Categories