How do you format php in html? - php

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

Related

Call out value into input field in PHP

How to display SQL result into text input?
When I press the generate button it should appear in the input text.
<?php
$random_name = "";
$conn = mysqli_connect("localhost","root","","wordlist");
if(!$conn)
{
die("Connection Error!");
}
$query_random = "SELECT kata FROM list ORDER BY RAND() LIMIT 1";
$result = mysqli_query($conn,$query_random);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$random_name = $row["kata"];
}
}
mysqli_close($conn);
?>
</head>
<body>
<div class="container" >
<form action="#">
<h4>Word Generator : </h4>
<div class="form-group">
<input type="text" class="form-control">
</div><br>
<button id="generate-btn" type="submit" title="Generate Word">Generate</button>
</div>
</form>
You just need to add this in place of your input, your code is correct but you missed to print the value, that's all
<input type="text" class="form-control" value="<?php echo #$random_name ?>">

How to debug a HTML/PHP form not submitting properly

I've looked at this code until I'm cross-eyed and can't see the error I'm making. I'm a bit of a beginner.
My HTML - editPost.php:
<?php
session_start();
include "includes/header.php";
include "connectioninfo.php";
include "functions.php";
if(isset($_SESSION['user']))
{
editPost();
}
else
{
header("Location: /");
}
$return = getPost();
?>
<div class="container">
<form action="editPost.php" method="post">
<?php $id = $_GET['id']?>
<input type="hidden" name="id" value="<?php echo $id?>">
<div class="row">
<div class="lab">
<label for="category">Category:<br/></label>
</div>
<div class="inp">
<select id="category" required autofocus name="category">
<option value="" selected disabled hidden>Choose a category.</option>
<option value="Something">About</option>
<option value="Something else">Coding</option>
</select>
</div>
</div>
<div class="row">
<div class="lab">
<label for="title">Title.</label>
</div>
<div class="inp">
<input type="text" name="title" placeholder="Title" required value="<?php echo $return[0]?>">
</div>
</div>
<div class="row">
<div class="lab">
<label for="content">Content.</label>
</div>
<div class="inp">
<textarea name="content" id="content" style="height: 30em;"><?php echo $return[1]?></textarea>
</div>
</div>
<div class="row">
<input type="submit" name="submit" value="Post.">
</div>
</form>
</div>
<?php
include "includes/footer.php";
?>
getPost() is just getting the values to autofill the form. it's a function in the included functions.php:
function getPost()
{
global $connection;
$id=$_GET['id'];
$query = "SELECT * FROM database WHERE id = '$id'";
$result = $connection->query($query);
if($result)
{
while($post = $result->fetch_object())
{
$id = $post->id;
$title = $post->title;
$link = $post->permalink;
$summary = $post->summary;
$category = $post->category;
$content = $post->content;
$pubDate = $post->pubDate;
$author = $post->author;
$return = array($title,$content);
return $return;
}
}
else
{
die('Query FAILED!' . mysqli_error());
}
}
and finally, editPost()
function editPost()
{
global $connection;
if(isset($_POST['submit']))
{
global $connection;
$title = mysqli_real_escape_string($connection,$_POST['title']);
$content = mysqli_real_escape_string($connection,$_POST['content']);
$category = $_POST['category'];
$id = $_POST['id'];
//Permalink
$link = strtolower(trim($title));
$link = preg_replace('/[^a-z0-9-]/', '-', $link);
$link = preg_replace('/-+/', "-", $link);
$link = rtrim($link, '-');
$link = preg_replace('/\s+/', '-', $link);
$query = "UPDATE database SET title = '$title', permalink = '$link', content = '$content', category = '$category' ";
$query .= "WHERE id = '$id'";
$result = $connection->query($query);
if(!$result)
{
die('Query FAILED!' . mysqli_error());
}
else
{
header("Location: /");
}
$result->close();
}
}
Clicking on the edit link of a post brings me to this form, and it looks great - title and content are filled out with what's in the database, and I'm ready to edit.
The process (both html and function) is nearly identical to my createPost.php, and that works fine. but editPost.php just sends me back to the same page, with no values in the fields, and the post hasn't been updated. No error messages either.
What am I missing?
Edit
As a reference, I'm posting the contents of newPost.php and the function newPost() - which are working fine.
newPost.php:
<?php
session_start();
include "connectioninfo.php";
include "functions.php";
if(isset($_SESSION['user']))
{
newPost();
}
else
{
header("Location: /");
}
include "includes/header.php";
?>
<div class="container">
<form action="newPost.php" method="post">
<div class="row">
<div class="lab">
<label for="category">Category.</label>
</div>
<div class="inp">
<select id="category" required autofocus name="category">
<option value="" selected disabled hidden>Choose a category.</option>
<option value="About">About</option>
<option value="Coding">Coding</option>
</select>
</div>
</div>
<div class="row">
<div class ="lab">
<label for="title">Title.</label>
</div>
<div class ="inp">
<input type="text" name="title" required placeholder="Title">
</div>
</div>
<div class="row">
<div class ="lab">
<label for="summary">Summary.</label>
</div>
<div class ="inp">
<input type="text" name="summary" required placeholder="Summary (for the RSS feed and Twitter)">
</div>
</div>
<div class="row">
<div class="lab">
<label for="content">Content.</label>
</div>
<div class="inp">
<textarea name="content" id="content" placeholder="The content of the post" style="height: 30em;"></textarea>
</div>
</div>
<div class="row">
<input type="submit" name="submit" value="Post.">
</div>
</form>
</div>
<?php
include "includes/footer.php";
?>
newPost():
function newPost()
{
if(isset($_POST['submit']))
{
global $connection;
$title = mysqli_real_escape_string($connection,$_POST['title']);
$summary = mysqli_real_escape_string($connection,$_POST['summary']);
$content = mysqli_real_escape_string($connection,$_POST['content']);
$category = $_POST['category'];
$pubDate = date("Y-m-d H:i:s");
$author = $_SESSION['user'];
//Permalink
$link = strtolower(trim($title));
$link = preg_replace('/[^a-z0-9-]/', '-', $link);
$link = preg_replace('/-+/', "-", $link);
$link = rtrim($link, '-');
$link = preg_replace('/\s+/', '-', $link);
$query = "INSERT INTO database(title, permalink, category, summary, content, pubDate, author) ";
$query .= "VALUES ('$title', '$link', '$category', '$summary', '$content', '$pubDate', '$author')";
$result = $connection->query($query);
if(!$result)
{
die('Query FAILED!' . mysqli_error());
}
else
{
header("Location: /");
}
$result->close();
}
}
thanks to everyone for their help. As I found out and stated in the comments, the problem was in my .htaccess
I do a rewrite in .htaccess - mysite.com/editPost.php?id=1 is actually mysite.com/edit/1 - running the long form WORKS, the short form is giving me the error.
My .htaccess has RewriteRule ^edit/([^/.]+)?$ /editPost?id=$1 [L] I just had to change <form action="editPost.php" method="post"> in editPost.php to <form action="edit" method="post"> and it works no problem :-/

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

Can get data on editing part <br /><b>Notice</b>: Undefined variable: row in

I am new in PHP. I keep on getting "undefined variable row in". I already read and try suggestion from other related question and answer here but nothing works for me.
PHP code
<?php
session_start();
require_once('dbConfig.php');
if(isset($_GET['ass_id'])){
$ass_id = $_GET['ass_id'];
$sql = "select * from beedass where ass_id=".$ass_id;
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
$row = mysqli_fetch_assoc($result);
}else{
$errorMsg = 'Could not select a record';
}
}
if(isset($_POST['btnUpdate'])){
$subject = $_POST['subject'];
$date = $_POST['date'];
$content = $_POST['content'];
if(empty($subject)){
$errorMsg = 'Please input subject course';
}elseif(empty($date)){
$errorMsg = 'Please input date to be passed';
}elseif(empty($content)){
$errorMsg = 'Please input assignment content';
}
//check upload file not error than insert data to database
if(!isset($errorMsg)){
$sql = "update beedass
set subject = '".$subejct."',
date = '".$date."',
content = '".$content."'
where ass_id=".$ass_id;
$result = mysqli_query($conn, $sql);
if($result){
$successMsg = 'New record updated successfully';
header('refresh:5;view_beedass.php');
}else{
$errorMsg = 'Error '.mysqli_error($conn);
}
}
}
?>
Keep on getting error on this line on my HTML code:
<form action="edit_beedass.php?ass_id=<?php echo $row['ass_id'];?>"
method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="form-group">
<label for="name" class="col-md-2">Subject Course</label>
<div class="col-md-10">
<input type="text" name="subject" class="form-control" value="<?
php echo $row['subject'] ; ?>">
</div>
</div>
<div class="form-group">
<label for="position" class="col-md-2">Date and Time to be
Passed</label>
<div class="col-md-10">
<input type="text" name="date" class="form-control" value="<?php
echo (isset($row['date']))? $row['date'] : $date ; ?>">
</div>
</div>
<div class="form-group">
<label for="position" class="col-md-2">Assignment Content</label>
<div class="col-md-10">
<input type="text" name="content" class="form-control" value="<?
php echo (isset($row['content'])) ; ?>">
</div>
</div>
The error I get is undefined variable row in echo $row['subject'], echo $row['date'] and echo $row['content'].

PHP Form update without logout

As i am newbie to PHP kindly pardon me if i looks silly ,
I created a form in php , while i do the update part of the form the update reflects in db whereas in the form it still shows the same old value . i tried refresh and force refresh but nothing changes .
Whereas if i logout and login again , the form shows the updated value .
I tried using die(); after mysql_close($link); but it logs out the session and needs to re-login .
Kindly help me on viewing the changes while i am still inside the login .
My code is as follows :
<?php
if(isset($_POST['update'])) {
$name_a = $_POST['name'];
$email_a = $_POST['email'];
$pass_a = $_POST['password'];
$sql = "UPDATE admin SET a_name = '$name_a', a_email = '$email_a', password = '$pass_a' where aid='$update_id' ";
$retval = mysql_query($sql,$link);
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($link);
}else {
?>
<!-- Widget: user widget style 1 -->
<div class="box box-widget widget-user-2">
<!-- Add the bg color to the header using any of the bg-* classes -->
<div class="widget-user-header bg-yellow">
<div class="widget-user-image">
<?php echo '<img src="' . $img . '" class="img-circle" alt="User Image">'; ?>
</div>
<!-- /.widget-user-image -->
<h3 class="widget-user-username"><?php echo "$name"; ?></h3>
<h5 class="widget-user-desc"><?php echo "$role"; ?></h5>
</div>
<div class="box-footer no-padding">
<form role="form" method = "post" action = "<?php $_PHP_SELF ?>">
<div class="box-body">
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="exampleInputName1" name="name" value="<?php echo "$name"; ?>">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="email" value="<?php echo "$email"; ?>">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="password" value="<?php echo "$password"; ?>">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="update" id="update" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
<!-- /.widget-user -->
<?php
}
?>
SOLUTION
1) use the updated value like $name_a instead of $name because $name_a contain updated value and $name contain old value
2) reload page after update and get new value from database on page load and store that value in $name , $email etc variable (if new data update successfully in database then only you get new value )
3) if You store your data in session or cookie then update session and cookie value also when you update in database
Try this:
<?php
$name = '';
$email = '';
$password = '';
$update_id = '';
//$img = '';
//$role = '';
//$link = null;
if(
isset($_POST['update']) &&
isset($_POST['id']) &&
isset($_POST['name']) &&
isset($_POST['email']) &&
isset($_POST['password'])
) {
$update_id = mysql_real_escape_string($_POST['id']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$sql = 'UPDATE admin SET a_name = \'' . $name . '\', a_email = \'' . $email . '\', password = \'' . $password . '\' WHERE aid = \'' . $update_id . '\'';
$result = #mysql_query($sql, $link);
if(!$result)
die('Could not update data: ' . mysql_error($link));
echo 'Updated data successfully', "\n";
}
elseif(isset($_GET['id'][0])) {
$update_id = mysql_real_escape_string($_GET['id']);
$sql = 'SELECT a_name,a_email,a_password FROM admin WHERE aid = \'' . $update_id . '\'';
$result = #mysql_query($sql, $link);
if($result) {
$result = mysql_fetch_row($result);
$name = $result[0];
$email = $result[1];
$password = $result[2];
}
else {
echo 'Could not find the id.' . "\n";
$update_id = '';
}
}
unset($result);
if(isset($update_id[0])) {
mysql_close($link);
?>
<!-- Widget: user widget style 1 -->
<div class="box box-widget widget-user-2">
<!-- Add the bg color to the header using any of the bg-* classes -->
<div class="widget-user-header bg-yellow">
<div class="widget-user-image">
<img src="<?php echo htmlspecialchars($img); ?>" class="img-circle" alt="User Image">
</div>
<!-- /.widget-user-image -->
<h3 class="widget-user-username"><?php echo htmlspecialchars($name); ?></h3>
<h5 class="widget-user-desc"><?php echo htmlspecialchars($role); ?></h5>
</div>
<div class="box-footer no-padding">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="hidden" name="id" value="<?php echo htmlspecialchars($update_id); ?>">
<div class="box-body">
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="exampleInputName1" name="name" value="<?php echo htmlspecialchars($name); ?>">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="email" value="<?php echo htmlspecialchars($email); ?>">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="password" value="<?php echo htmlspecialchars($password); ?>">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="update" id="update" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
<!-- /.widget-user -->
<?php }
else {
$sql = 'SELECT aid,a_name FROM admin';
$result = #mysql_query($sql, $link);
if($result) {
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '' . $row['a_name'] . '<br />' . "\n";
}
}
mysql_close($link);
}
?>
As #DivyeshSavaliya mentioned in the comment the issue is ,
I didn't Used Select query after update . Once done that the issue solved
The new working code is
<?php
if(isset($_POST['update'])) {
$name_a = $_POST['name'];
$email_a = $_POST['email'];
$pass_a = $_POST['password'];
$sql = "UPDATE admin SET a_name = '$name_a', a_email = '$email_a', password = '$pass_a' where aid='$update_id' ";
$retval = mysql_query($sql,$link);
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
}
$result = mysql_query("SELECT * FROM admin where aid='$update_id' ",$link);
while($row = mysql_fetch_array($result)){
$name = $row['a_name'];
$email = $row['a_email'];
$password = $row['password'];
}
mysql_close($link);
?>
Thanks to #DivyeshSavaliya

Categories