$_GET or $_SESSION for passing variable - php

Hello monsters of programming. I just want to ask a question about using $_SESSION and $_GET. When to use $_GET and $_SESSION? what is the best for passing variable? Im just new to php and html and i don't know what is the best practice. Can someone help me to understand both of them?
Here is the example of my code. I used $_SESSION for passing the variable $newsid;
here is the edit.php
<?php
session_start();
include_once('connection.php');
$sql ="SELECT * FROM news ORDER BY news_id";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result)){
$newsid = $row['news_id'];
$title = $row['news_title'];
$date = $row['news_date'];
$content = $row['news_content'];
$newsimage = $row['news_image'];
?>
<div class="fix single_news">
<div class="single_image">
<img src="<?php echo $newsimage; ?>" style="width:200px; height:140px; alt="court">
</div>
<?php echo $title; ?>
<p><?php echo $date; ?></p>
<p><?php echo $content; ?></p>
</div>
<form action="" method="post">
<input type='hidden' name="news_id" value="<?php echo $newsid;?>">
<input type="submit" name="esubmit" value="edit" />
</form>
<hr>
<?php
}
if(isset($_POST['esubmit'])){
$_SESSION['news_id'] = $_POST['news_id'];
header('Location: edit2.php');
}
?>
here is the edit2.php
<?php
session_start();
$id = $_SESSION['news_id'];
include_once('connection.php');
$sql = "SELECT * FROM news WHERE news_id = '$id'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)){
$title = $row['news_title'];
$date = $row['news_date'];
$content = $row['news_content'];
$newsimage = $row['news_image'];
}
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form method="post" action ="" enctype="multipart/form-data">
Title<input type ="text" name ="title" value="<?php echo $title;?>"/><br>
Date<input type ="text" name="date" value="<?php echo $date;?>" /><br>
Content<textarea name="content"><?php echo $content;?></textarea>
<input type="submit" name="submit" value="Update" />
<input class="form-control" id="image" name="image" type="file" accept="image/*" onchange='AlertFilesize();'/>
<img id="blah" src="<?php echo $newsimage;?>" alt="your image" style="width:200px; height:140px;"/>
</form>
<hr>
<script src="js/jquery-1.12.4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>

$_GET is for parameters that are needed during that specific request (or can be easily carried over to other pages), e.g.:
item IDs
current page (pagination)
user's profile name
...
$_SESSION is for data that needs to be persisted across multiple requests, e.g.:
current user's ID
shopping carts
list filters
...
You should use the one that better suits your use case.
That being said, I'd consider storing news_id in the session a bad thing. What if I want to edit multiple items and open multiple browser tabs? I'll end up overwriting my data. Just because you can use sessions doesn't mean you should.

Related

PHP - Wrong data is passed and shown to another page

this is what i want to do, i have two pages, first is the "edit.php" and second is the "edit2.php". the page "edit.php" this is the page where all the news is shown and you will select what news you will edit by clicking the "edit button" and the "edit2.php" where will i exactly edit the news. i want to pass the value of the selected news in another page. But here is the problem, when i clicked the "Sample news 1" edit button the data showing in another page is the "Sample news 2". Even when i clicked the "Sample news 2" edit button, the data is also the "Sample news 2". Can someone give me ideas on how to fix this?
here is the picture of edit.php. I click the edit button of "Sample news 1".
here is the picture of edit2.php. and this is the output data. The data should be "Sample news 1" not "Samplel news 2".
here is my php code in edit.php
<?php
session_start();
include_once('connection.php');
$sql ="SELECT * FROM news ORDER BY news_id";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result)){
$newsid = $row['news_id'];
$title = $row['news_title'];
$date = $row['news_date'];
$content = $row['news_content'];
$newsimage = $row['news_image'];
if(isset($_POST['esubmit'])){
$_SESSION['news_id'] = $newsid;
$_SESSION['n_title'] = $title;
$_SESSION['n_date'] = $date;
$_SESSION['n_content'] = $content;
$_SESSION['n_image'] = $newsimage;
header('Location: edit2.php');
}
?>
<div class="fix single_news">
<div class="single_image">
<img src="<?php echo $newsimage; ?>" style="width:200px; height:140px; alt="court">
</div>
<?php echo $title; ?>
<p><?php echo $date; ?></p>
<p><?php echo $content; ?></p>
</div>
<form action="" method="post">
<input type="submit" name="esubmit" value="edit" />
</form>
<hr>
<?php
}
?>
here is my php code for "edit2.php"
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form method="post" action ="" enctype="multipart/form-data">
Title<input type ="text" name ="title" value="<?php echo $_SESSION['n_title']; ?>"/><br>
Date<input type ="text" name="date" value="<?php echo $_SESSION['n_date']; ?>" /><br>
Content<textarea name="content"><?php echo $_SESSION['n_content']; ?></textarea>
<input type="submit" name="submit" value="Update" />
<input class="form-control" id="image" name="image" type="file" accept="image/*" onchange='AlertFilesize();'/>
<img id="blah" src="<?php echo $_SESSION['n_image']; ?>" alt="your image" style="width:200px; height:140px;"/>
</form>
<hr>
<script src="js/jquery-1.12.4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
Remove if(isset($_POST['esubmit'])){ code out of while loop and add values in form as I shown in below example
Pass $newsid in edit form as hidden and retrieve the content based on new
<form action="" method="post">
<input type='hidden' value="<?php echo $newsid;?>" name="news_id">
<input type="submit" name="esubmit" value="edit" />
</form>
and in your php add this line.
if(isset($_POST['esubmit'])){
$_SESSION['news_id'] = $_POST['news_id'];
The problem is, in each iteration of while loop you're overwriting $newsid, $title, $date,... variables. So when you submit the form, the last row's data will get stored in the corresponding $_SESSION variables.
So here's the solution to your problem.
You don't need $_SESSION to pass the form values to edit2.php page, instead change the <form> element in the following way,
<form action="edit2.php?news_id=<?php echo $newsid; ?>" method="post">
On edit2.php page, first catch the news_id value using $_GET superglobal , like this:
$newsid = $_GET['news_id'];
And then get the appropriate news details using this $newsid, and finally populate the form.
Here's the complete code,
edit.php
<?php
include_once('connection.php');
$sql ="SELECT * FROM news ORDER BY news_id";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result)){
$newsid = $row['news_id'];
$title = $row['news_title'];
$date = $row['news_date'];
$content = $row['news_content'];
$newsimage = $row['news_image'];
?>
<div class="fix single_news">
<div class="single_image">
<img src="<?php echo $newsimage; ?>" style="width:200px; height:140px; alt="court">
</div>
<?php echo $title; ?>
<p><?php echo $date; ?></p>
<p><?php echo $content; ?></p>
</div>
<form action="edit2.php?news_id=<?php echo $newsid; ?>" method="post">
<input type="submit" name="esubmit" value="edit" />
</form>
<hr>
<?php
}
?>
edit2.php
<?php
if(isset($_POST['esubmit'])){
$newsid = $_GET['news_id'];
include_once('connection.php');
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, "SELECT * FROM news WHERE news_id = ? LIMIT 1")) {
/* bind parameters */
mysqli_stmt_bind_param($stmt, "s", $newsid);
/* execute query */
mysqli_stmt_execute($stmt);
/* get the result set */
$result = mysqli_stmt_get_result($stmt);
/* fetch row from the result set */
$row = mysqli_fetch_array($result);
}
}
if(isset($_POST['submit'])){
// Write code to commit the edit details
}
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
if(isset($_POST['esubmit'])){
?>
<form method="post" action ="edit2.php?news_id=<?php echo $row['news_id']; ?>" enctype="multipart/form-data">
Title<input type ="text" name ="title" value="<?php echo $row['news_title']; ?>"/><br>
Date<input type ="text" name="date" value="<?php echo $row['news_date']; ?>" /><br>
Content<textarea name="content"><?php echo $row['news_content']; ?></textarea>
<input class="form-control" id="image" name="image" type="file" accept="image/*" onchange='AlertFilesize();'/>
<img id="blah" src="<?php echo $row['news_image']; ?>" alt="your image" style="width:200px; height:140px;"/>
<input type="submit" name="submit" value="Update" />
</form>
<?php
}
?>
<script src="js/jquery-1.12.4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
Here is the issue, You are looping your data to the session, usually single session keeps only a value. Since that final item of your loop will store on the session [in this case it is 'Sample news 2']. I believe, you can place it on a hidden field & post it to the next page or you can use URL Parameter [GET], to pass the Id to the next page.
Ex : <a href ='edit2.php?newsId ='<?php echo $newsid?>> Edit </a>
what I think is happening is when you are clicking edit button this edit.php page is again reloading and that sql query is running again that's why it is taking value of first image in both cases.what I suggest you to try is use $_get[] instead of $_SESSION and $_POST and pass value of image id directly to page edit2.php and query others details from database in that page and then display it.try it
Remove <form> and <input> use just <a> instead like this.
<a href='edit2.php?id=$news_id'>Edit</a>
and then fetch this id in edit2.php like following
$news_id=$_GET['id'];
and atlast fetch other details of news from the database using this id like'
$query='select * from news where news_id=$news_id';

Update post from database

I'm trying to get my post to update just in case I make a mistake the first time around posting an article to my website.
Not sure what I'm doing wrong here.
Here is my update code:
<div class="row">
<?php
$post_title = "";
$description = "";
$id = $_GET['id'];
$result = mysql_query("SELECT title, description FROM htp_news WHERE id='$id'");
$post_title = mysql_result($result,0,"title");
$description = mysql_result($result,0,"description");
?>
<div class="row">
<form method="post" action="update-news.php">
<input type="hidden" name="ud_id" style="width: 100%" value="<? echo "$id"; ?>">
<div class="grid_12 botspacer60">
Title: <input type="text" name="ud_title" value="<?php echo "$post_title"; ?>">
<br /><br />
News Details:<br />
<textarea id="tiny_mce" name="ud_description" rows="8"><?php echo "$description"; ?></textarea>
</div>
<div class="grid_12">
<input type="submit" value="Update">
<input type="button" value="Cancel" onclick="window.location = '/admin'">
</div>
</form>
</div>
</div>
And here is my action page:
<?php
include($_SERVER['DOCUMENT_ROOT'] . "/includes/database.php");
$ud_id = $_POST['ud_id'];
$ud_title = $_POST['ud_title'];
$ud_description = $_POST['ud_description'];
// Insert record into database by executing the following query:
$query="UPDATE htp_news SET title='$ud_title', description='$ud_description' "."WHERE id='$ud_id'";
mysql_query($query);
echo "The post has been updated.<br />
<a href='edit-delete-news.php'>Update another position.</a><br />";
mysql_close();
?>
I appreciate any guidance on the matter.
Add a space before of WHERE Clause in query.
Use below -
$query="UPDATE htp_news SET title='$ud_title', description='$ud_description' WHERE id='$ud_id'";
Try this you need quotes in query
$result = mysql_query("SELECT `title`, `description` FROM `htp_news` WHERE id='$id'");
$query="UPDATE htp_news SET `title`='".$ud_title."', `description`='".$ud_description."' "." WHERE `id`='".$ud_id."'";

show data in multiple textbox in php

I want to show all the names of my tb_app which is currently have (4)names stored and show it on my textboxes...can anyone help me make my code work? I'm just a beginner at programming.
current code:
<html>
<head>
<title>test</title>
</head>
<body>
<?php
include('include/connect.php');
$sql = "SELECT name FROM tb_app";
while($rows = mysql_fetch_array($sql)){
$name = $rows['name'];
}
?>
Name List: <br />
<input type="text" value="<?php echo $name[0] ?>" /> <br />
<input type="text" value="<?php echo $name[1] ?>" /> <br />
<input type="text" value="<?php echo $name[2] ?>" /> <br />
<input type="text" value="<?php echo $name[3] ?>" /> <br />
</body>
</html>
Right now you are overwriting the $name variable in each iteration of your loop. You want to treat $name as an array instead, and add an element to the array in each iteration.
Change this:
$name = $rows['name'];
To this:
$name[] = $rows['name'];
You could of course echo your textbox directly inside your while loop as well, and skip the $name variable. However it's good practice to separate your DB or business logic from your display logic, which you are (somewhat) doing. In fact I'd recommend moving your PHP code to the very top of the page, before your opening <html> tag even, and limit how much PHP you mix in with your html.
A more dynamic way (i.e you have less or more then 4 names):
<html>
<head>
<title>test</title>
</head>
<body>
Name List: <br />
<?php
include('include/connect.php');
$sql = "SELECT name FROM tb_app";
while($rows = mysql_fetch_array($sql)){
echo '<input type="text" value="'. $rows['name'] .'" /> <br />';
}
?>
</body>
</html>
You could go even further:
Change name to names:
while($rows = mysql_fetch_array($sql)){
$names[] = $rows['name'];
}
And then
Name List:
<?php foreach ($names as $name): ?>
<input type="text" value="<?php echo $name ?>" /> <br />
<?php endforeach; ?>

Form doesn't work when query involves a variable for the table name -- PHP -- MYSQL

I have a few tables with image urls and image ids and I want to be able to delete from each of these tables using one php page and query.
The $tableToDeleteFrom is set as a variable in the url (ex delete.php?table=whatever)
$tableToDeleteFrom = $_GET['table'];
here is my query / php -- it appears this is where the problem may be, for some reason when $tableToDeleteFrom is not a variable, everything works fine. An image is deleted and the redirect brings is back to the correct page. However I need this to be dynamic because the user needs to be able to select which section they want to display in the url.
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM '.$tableToDeleteFrom.' WHERE id = ?');
$query->bindValue(1, $id);
$query->execute();
header('Location: img_delete_new.php?table='.$tableToDeleteFrom);
}
here is the php which fetches each line of the table and puts it into array to be accessed in the next bit of code:
class Image {
public function fetch_all() {
global $pdo;
$tableToDeleteFrom = $_GET['table'];
$query = $pdo->prepare("SELECT * FROM ".$tableToDeleteFrom);
$query->execute();
return $query->fetchAll();
}
}
$image = new Image;
$images = $image->fetch_all();
here is the form allowing user to select which image they want to delete:
<form action="img_delete_new.php" method="get">
<?php foreach ($images as $image) { ?>
<div class="delete">
<input type="radio" name="id" value="<?php echo $image['id']; ?>">
<img src="../images/thumbs/<?php echo $image['name']; ?>"><br>
<?php echo $image['desc']; ?>
</div>
<?php } ?>
<input type="submit" value="Delete Image" class="button">
</form>
updated the form to include the hidden variable "table"
<form action="img_delete_new.php" method="get">
<?php foreach ($images as $image) { ?>
<div class="delete">
<input type="hidden" name="table" value="<?php echo $tableToDeleteFrom;?>">
<input type="radio" name="id" value="<?php echo $image['id']; ?>">
<img src="../images/thumbs/<?php echo $image['name']; ?>"><br>
<?php echo $image['desc']; ?>
</div>
<?php } ?>
<input type="submit" value="Delete Image" class="button">
</form>

HTML form $_POST not being retrieve and set into PDO QUERY

I decided to leave in all the code to make it less confusing to those who see this.
On line #57, the only form on this page, I'm trying to $_POST the id that equals the post_iD.
Everything uploads correctly to MySQL besides the post_iD.
I always get a Notice: Undefined index: post_iD on $post_iD = $_POST['post_iD']; inside the if(isset($POST['comment'])).
I'm sure the issue is with how I'm trying to retrieve the post_iD inside the form, and not any issues with the PDO but html as PDO the data is being inserted correctly besides the post_iD which I have mentioned.
I'm using post_iD to loop posts from database, it works besides inside the form, any enlightenment with this issue?
Code Below.
if(isset($_POST['comment'])){
$comment = $_POST['comment'];
$post_iD = $_POST['post_iD'];
$data = $Wall->Insert_Comment( $uiD, $post_iD, $comment, $_SERVER['REMOTE_ADDR'] );
}
if ( $updatesarray ){
foreach ($updatesarray as $data){
$post_iD = $data['post_iD'];
$orimessage = $data['message'];
$message = tolink(htmlcode($data['message']));
$time = $data['created'];
$mtime = date("g:i", $time);
$username = $data['username'];
$uploads = $data['uploads'];
$uiD = $data['uid_fk'];
?>
<div class="wrap">
<div class="item" id="stbody<?php echo $post_iD;?>">
<div class="loop-post">
<div class="loop-post-content">
<div class="loop-post-image">
<a href="" class="post-link">
<?php
if ($uploads){
$s = explode(",", $uploads);
foreach ($s as $a){
$newdata = $Wall->Get_Upload_Image_Id($a);
if ($newdata) echo "<a href='uploads/" . $newdata['image_path'] . "' rel='facebox'>
<img src='uploads/" . $newdata['image_path'] . "' width='520' height='245' class='imgpreview attachment-top_story_post wp-post-image' /></a>";
}
echo "</div>";
}
?>
</a>
</div>
<div class="loop-post-byline">By <a rel="author" title="Posts by Emil Protalinski" href=""><?php echo $username;?></a>
<span class="date"> — <?php echo $mtime;?></span>
</div>
<a class="post-link">
<?php echo clear($message);?>
</a>
<div class="post_comment">
<?php $x=1; include_once 'load_comments.php'; ?>
<div class="commentupdate" id="commentbox<?php echo $post_iD;?>">
<div class="stcommentimg">
<img src="<?php echo $photo;?>" class="small_face">
</div>
<div class="stcommenttext">
<form method="POST" action="">
<textarea name="comment" class="comment" id="<?php echo $post_iD;?>" value="<?php echo $post_iD;?>"></textarea> #57
<input type="submit" value="comment">
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php } } else echo '<h3 id="noupdates">No Updates!</h3>';?>
You are never actually setting the post_iD variable anywhere. If you want to use it in the $_POST array you need to set it in the form first.
<form method="POST" action="">
<input type="hidden" name="post_iD" value="<?php echo $post_iD; ?>" />
<textarea name="comment" class="comment" id="<?php echo $post_iD;?>" value="<?php echo $post_iD;?>"></textarea> #57
<input type="submit" value="comment">
</form>
You need to do this...
<textarea name="comment" class="comment" id="comment-<?php echo $post_iD;?>"></textarea>
<input type="hidden" id="post_iD" name="post_iD" value="<?php echo $post_iD;?>" />
Cuz youre never passing the post_iD anywhere....this will pass it in hidden form...
And the value for your textarea wont be $post_iD, it will likely be a comment/post of some type....I assume you just had that for debugging

Categories