Delete an image using link/id from database - php

I want to delete an image by an button called 'DELETE'.
My image is saved on the server, my image link is saved into a database table.
To delete now works great, but every user can delete every users images right now by typing in the picture id in the URL.
uploads.php
<div id="myuploads">
<?php
//Configuration
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'myimg';
$salt = "u6d5u6mj65dehjum568nuu65umk57endjzu766imm57e8u5u56";
if(isset($_SESSION['username'])){
$hash = hash('sha224', $_SESSION['username']).$salt;
}
$conn = mysqli_connect("$host", "$user", "$pass", "$db");
//Script
if(isset($_SESSION['username'])){
$uid = $_SESSION['username'];
$dir = $uid . "/";
$alledateien = mysqli_query($conn, "SELECT * FROM imglinks WHERE uid='$uid'");
foreach ($alledateien as $datei)
{
echo "<div class='pictures'> \
<img class='pbild' src='" . $dir . $datei["link"] . "'><br/> \
<form action='functions/deleteimg.php'></div> \
<input class='deleteimg' type='submit' name='deleteimg' value='DELETE'> \
<input class='post' type='submit' value='PUBLISH'></form>";
}
}else{
header("Location: ../index.php");
}
?>
</div>
deleteimg.php
<?php
include '../config.php';
$uid = $_SESSION['username'];
$username = mysqli_query($conn, "SELECT uid FROM imglinks WHERE uid='$uid'");
foreach($username AS $name) {
if(isset($_GET['deleteimg']) && $uid = $name['uid']){
$sql = "SELECT * FROM imglinks WHERE id='".$_GET['deleteimg']."' LIMIT 1";
$filepath = mysqli_query($conn, $sql);
foreach($filepath AS $value) {
unlink($value['link']);
}
$uid = $_SESSION['username'];
mysqli_query($conn, "DELETE FROM imglinks WHERE id='".$_GET['deleteimg']."' AND uid='$uid'");
}}
The links given out coming out of the imglinks table of my database.
DATABASE STRUCTURE
If you need more detail, feel free to ask.

One thing that I would suggest / do when deleting I would use an anchor tag instead of a button to delete then on the anchor tag I will have action and id as query string. then on the deleteimg.php page I will query the action and the ID if the action is delete then delete the selected id.
Then you code will look like this :
uploads.php
<div id="myuploads">
<?php
//Configuration
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'myimg';
$salt = "u6d5u6mj65dehjum568nuu65umk57endjzu766imm57e8u5u56";
if(isset($_SESSION['username'])){
$hash = hash('sha224', $_SESSION['username']).$salt;
}
$conn = mysqli_connect("$host", "$user", "$pass", "$db");
//Script
if(isset($_SESSION['username'])){
$uid = $_SESSION['username'];
$dir = $uid . "/";
$alledateien = mysqli_query($conn, "SELECT * FROM imglinks WHERE uid='$uid'");
foreach ($alledateien as $datei)
{
echo "<div class='pictures'> \
<img class='pbild' src='" . $dir . $datei["link"] . "'><br/> \
<form action='functions/deleteimg.php'></div> \
<a class='deleteimg' href='functions/deleteimg.php?action=delete&id='".$datei['id']."'>DELETE</a><br>
<input class='post' type='submit' value='PUBLISH'></form>";
}
}else{
header("Location: ../index.php");
}
?>
</div>
Then deleteimg.php
<?php
// Your connection here...
// check if session is set here...
$action = $_GET['action'];
$img_id = intval($_GET['id']);
if($action === "delete"){
$sql = "DELETE FROM imglinks WHERE id='$img_id'";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
//image delete... do something else
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
}
mysqli_close($conn);
?>
This always works for me and always easy, hope you will find it useful.
NB: Read about mysqli prepared statements, against sql injections.. You can read here

You can:
Add a boolean field to your imglinks table named say 'show', and modify your query accordingly. In this case you'll be even able to 'undelete' accidentally deleted images.
If you're short on disk space then modify <input class='deleteimg' type='submit' name='deleteimg' value='DELETE'> to <input class='deleteimg' type='submit' name='deleteimg' value='".$image_to_delete."'> so that you'll see this link in your postdata and will be able to process it

It's not so complicated, just use like this :
*Root is your root directory !
$path = root/$uid/$imgname;
$query("DELETE FROM imagetable WHERE imgname = $imgname");
And to delete the image :
unlink($path);
And just use a form to submit imgname to your script !
*For more security, you can also add $uid to your query !

You need to change your buttons like this:
foreach ($alledateien as $datei)
{
echo "<div class='pictures'> \
<img class='pbild' src='" . $dir . $datei["link"] . "'><br/> \
</div><form action='functions/deleteimg.php'> \
<input type='hidden' name='img_id' value='".$datei["id"]."'> \
<input class='deleteimg' type='submit' name='deleteimg' value='DELETE'> \
<input class='post' type='submit' name='publish' value='PUBLISH'></form>";
}
Then on deleteimg.php, get the image id and execute a delete query:
if(isset($_POST['deleteimg']) && $_POST['deleteimg'] == 'DELETE'){
$img_id = $_POST['img_id'];
mysqli_query($conn, "DELETE FROM imglinks WHERE id='$img_id'");
}

Thanks for all answers, now i've completed it myself.
deleteimg.php
<?php
include '../config.php';
$uid = $_SESSION['username'];
if(isset($_GET['deleteimg'])){
$sql = "SELECT * FROM imglinks WHERE id='".$_GET['deleteimg']."' LIMIT 1";
$filepath = mysqli_query($conn, $sql);
$test = mysqli_fetch_array($filepath);
if($test['uid'] == $uid){
unlink($test['link']);
mysqli_query($conn, "DELETE FROM imglinks WHERE id='".$_GET['deleteimg']."' AND uid='$uid'");
echo 'File successfully deleted.';
header ("Refresh: 2; ../index.php");
} else {
echo 'You do not have the permission to delete this file.';
header ("Refresh: 2; ../index.php");
}
}

Related

Image Click Counter, data base Row update, and Order by hits

Im trying to make an image click counter, so that when some one click on an image it updates hit column by 1.
Im having trouble with the syntax, as far as getting the row number that needs to be updated.
Later i want to use this hit column to sort the order that the images are displayed on the site.
If you feel like throwing me a bone and telling how to do that as well it would be much appreciated :)
connect.php
<?php
$servername = "*******";
$username = "********";
$password = "********";
$dbname = "********";
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
?>
art.php
<?php
require 'connect.php';
$sql = "SELECT * FROM art";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class='art'>
<a href='img/".$row["name"].".jpg '
//part that I need help with
onclick='
<?php
include 'update_hits.php';
update_hit('$row');
?>'
target='_blank'>
<img src='img/".$row["name"]."_tnail.jpg' alt='".$row["name"]."' title='".$row["name"]." • ".$row["year"]." • ".$row["type"]."'/>
</a>
<p>
".$row["name"]." • ".$row["year"]." • ".$row["type"]."
</p>
</div>"
;
}
} else {
echo "0 results";
}
$conn->close();
?>
update_hits.php
<?php
require 'connect.php';
function update_hit($row){
$query = "SELECT 'hits' FROM 'art'";
if(#$query_run = mysql_query($query);){
$count = mysql_result($query_run, '$row' , 'hits');
$count_inc = $count + 1;
$query_update = "UPDATE 'art' SET 'hits' = '$count_inc'";
#$query_update_run =mysql_query($query_update);
}
}
?>
Finally got it to work
<?php
require 'connect.php';
$image = $_GET['image'];
//need to check whether file exists also
if(!empty($image)){
echo "<img src='".$image.".jpg'>"; // prefix full path if needed
$imagename = explode("/", $image);
$sql = "UPDATE `art` SET `hits`=`hits` +1 WHERE `name` = '".$imagename[1]."'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
?>
This is only the logic, your code is not perfect it needs many validation and additional checks. I have not tested this code check for syntax errors. Its only for you to get the logic on how to do this.
modified art.php
<?php
require 'connect.php';
$sql = "SELECT * FROM art";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class='art'>
<a href='displayImg.php?image=".$row["name"]."' target='_blank'>
<img src='img/".$row["name"]."_tnail.jpg' alt='".$row["name"]."' title='".$row["name"]." • ".$row["year"]." • ".$row["type"]."'/>
</a>
<p>
".$row["name"]." • ".$row["year"]." • ".$row["type"]."
</p>
</div>"
;
}
} else {
echo "0 results";
}
$conn->close();
?>
new displayImg.php
<?php
require 'connect.php';
$image = $_GET['image'];
//need to check whether file exists also
if(!empty($image)){
echo 'img/'.$image.'jpg'; // prefix full path if needed
$sql = "UPDATE 'art' SET hits=hits+1 where name = ".$image;
$result = $conn->query($sql);
}
?>

MySQL Query Issue - PHP variable not passed through includes

So as the title suggests, I am having trouble executing a MySQL query. The query works almost successfully, as all data fields are stored into my database except for one. The query itself is a commenting system for signed in users to comment on any given blog post. The issue I am having is that the variable '$post_id' is not recognized, and therefore '$comment_post_ID' is not stored in my database.
'$post_id' is defined in blogs.php, and after echoing this variable it does exist and is successfully defined. However, this variable is not passed onto commentsubmit.php, which is included in the same file where the variable is defined. Why is this happening?
Here are all the pieces of my code:
blogs.php (shows all posts from all users, or just one post if ?id is set in the url. If ?id is set, users can comment on the single post they are viewing.)
<?php
if (isset($_GET['id'])) {
$conn = mysqli_connect("localhost", "root", "mypassword", "mydbname");
if (mysqli_connect_errno($conn)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
$post_id = mysqli_real_escape_string($conn, $_GET['id']);
$blog_post = "SELECT * FROM blogs WHERE id = '$post_id'";
$blog_query = mysqli_query($conn, $blog_post);
while ($row = mysqli_fetch_array($blog_query)) {
$title = $row['title'];
$body = $row['body'];
$author = $row['author'];
$author_username = $row['author_username'];
$datetime = time_ago($row['datetime'], $granularity=2);
}
include ("./fullpageblog.php");
if (isset($_SESSION['id'])) {
include ("./blogcomment.php");
include ("./commentsubmit.php");
}
echo "$post_id";
mysqli_close($conn);
}
?>
blogcomment.php (form for users to make a comment)
<div class="row col-sm-12">
<div id="fullPageBlog">
<div id="center-border"></div>
<form action="commentsubmit.php" method="post">
<textarea maxlength="1000" id="blogComment" name="content" placeholder="Write your response..."></textarea>
<input type="submit" name="comment" value="Publish" />
</form>
<script type="text/javascript">$('#blogPost').elastic();</script>
</div>
</div>
commentsubmit.php (comment query itself)
<?php
session_start();
if (isset($_POST['comment'])) {
$conn = mysqli_connect("localhost", "root", "mypassword", "mydbname");
if (mysqli_connect_errno($conn)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
$comment_post_ID = $post_id;
$comment_author = $_SESSION['full_name'];
$comment_author_email = $_SESSION['email'];
$comment_author_username = $_SESSION['username'];
$comment_date = date("Y-m-d H:i:s");
$comment_content = mysqli_real_escape_string($conn, $_POST['content']);
$user_ID = $_SESSION['id'];
$comment_submit = "INSERT INTO comments (comment_ID, comment_post_ID, comment_author, comment_author_email, comment_author_username, comment_date, comment_content, user_ID) VALUES ('', '$comment_post_ID', '$comment_author', '$comment_author_email', '$comment_author_username', '$comment_date', '$comment_content', '$user_ID') ";
$comment_query = mysqli_query($conn, $comment_submit);
mysqli_close($conn);
header("Location: blogs.php");
die();
}
?>
You don't include/require the blogs.php script from the commentsubmit.php script, so the code in blogs.php would never be run after a POST that is made directly to commentsubmit.php unless you have some other request processing (i.e. a server-side rewrite or similar) that happens automatically on the server before the request ultimately reaches the portion of code shown in commentsubmit.php above.
<?php
$con = mysql_connect("localhost","root","password");
$con=mysql_select_db("database_name");
error_reporting(0);
session_start();
if(isset($_POST["submit"])){
$comment_author = $_POST['full_name'];
$comment_author_email = $_POST['email'];
$comment_author_username = $_POST['username'];
$sql="select * from table_name where `full_name`='"$comment_author "',`email`='"$comment_author_email "',`username`='"$comment_author_username "'";
$qur=mysql_query($sql);
$row= mysql_fetch_array($qur);
$num= mysql_num_rows($qur);
}
if($num>0){
$_SESSION["full_name"]=$full_name;
$_SESSION["email"]=$comment_author_email;
$_SESSION["username"]=$comment_author_username;
}
else{
echo"Username and Password are wrong";
}
?>

How to get Mysqli image in database to show up in div

The div that I want the image to be displayed in (form is sent to send_post.php):
<div style="width:200px ; height: 200px ; border:1px dashed red ; display:inline-block ; margin-top:5px ; margin-left:5px" class="postedBy"></div><!--end image-->
This aforementioned div is located inside this container div:
<div style="height:800px ; width:800px ; border:1px dashed black ; margin-left:200px ; float:left ; margin-top:50px" id= "profilePosts"></div>
Code from send_post.php:
<?php
session_start();
if(!isset($_SESSION['username'])) {
header('location: mustLogin.php');
} else {
$username = $_SESSION['username'];
}
$title = $_POST['title'];
$description = $_POST['description'];
$image = $_POST['image'];
$dateAdded = date('Y-m-d');
$addedBy = $username;
if (!empty('title') && !empty('description') && !empty('image')) {
//establish connection to SQL
$conn = mysqli_connect("localhost", "root", "") or die ("Couldn't connect to SQLI");
//connect to DB
mysqli_select_db($conn, "accounts") or die ("Couldn't find DB");
$sqliCommand = "INSERT INTO `posts` (title, description, image, date_added, added_by) VALUES ('$title', '$description', '$image', '$dateAdded', '$addedBy')" or die ('Info couldnt go to database');
mysqli_query($conn, $sqliCommand) or die ('MySQLI error');
header('location: profile.php?user='.$username);
} else {
header('location: error.php');
}
?>
The info get's sent to the database just fine, but can someone explain to me how I can get the images added by the user (all of them) to display in the first div I listed?
You need to create a separate url just to return the retrieved image from DB by image type in header
So after your selection in a for loop you can have something like
<?php
$sqliCommand = "SELECT * FROM `posts` WHERE `added_by` = '{$this->username}'";
$result = mysqli_query($conn, $sqliCommand);
while ($row = mysqli_fetch_assoc($result)) {
?>
<div style="width:200px ; height: 200px ; border:1px dashed red ; display:inline-block ; margin-top:5px ; margin-left:5px" class="postedBy">
<img src="/imgView.php?imgId=<?php echo $row['id'] ?>"
</div>
<?php
}
?>
Now what you need is to create a page for imgView.php which contains something like
<?php
$imgId = $_GET['imgId'];
if (!empty($imgId)) {
$sqliCommand = "SELECT `image` FROM `posts` WHERE `id` = '$imgId'";
$result = mysqli_query($conn, $sqliCommand);
$row = mysqli_fetch_assoc($result));
header("Content-Type: image/jpeg"); // or whatever the correct content type is.
echo $row['image']; //if your image is encoded you can decode it here, too.
}
?>
I would also recommend to save the MIME type while you are inserting so that you be able to use a proper header Content-Type
Upload form:
<form action="/image_upload.php" method="POST" enctype="multipart/form-data">
<label>Title:</label>
<input type="text" name="title">;
<label>Description:</label>
<textarea name="description"></textarea>
<label>Upload Image:</labe>
<input type="file" name="avatar" accept="image/*">
<button type="submit">Upload</button>
</form>
Upload script (image_upload.php):
session_start();
if(!isset($_SESSION['username']))
{
header('location: mustLogin.php');
exit;
}
else
{
if($_FILES != null) //uploaded files are held in $_FILES array
{
$username = $_SESSION['username'];
$title = $_POST['title'];
$description = $_POST['description'];
$dateAdded = date('Y-m-d');
$addedBy = $username;
if ($title != "" && $description != "" && !empty($_FILES))
{
$new_file_name = uniqid() . "-" . $username . "-upload";
$file_path = 'images/' . $new_file_name; //images haves to be a directory in the same directory that this script runs
$uploaded_file = move_uploaded_file($_FILES['tmp_name'], $file_path );
if($uploaded_file == TRUE)
{
$conn = mysqli_connect("localhost", "root", "") or die ("Couldn't connect to SQLI");
//connect to DB
mysqli_select_db($conn, "accounts") or die ("Couldn't find DB");
/* You should change this while query to a prepared statement for security reasons */
$sqliCommand = "INSERT INTO `posts` (title, description, image, date_added, added_by) VALUES ('$title', '$description', '$file_path', '$dateAdded', '$addedBy')" or die ('Info couldnt go to database');
mysqli_query($conn, $sqliCommand) or die ('MySQLI error');
header('location: profile.php?user='.$username);
}
else
{
echo "Could not upload file.";
}
}
else
{
echo "Missing title or description, or file array is empty.";
}
}
else
{
echo "No file uploaded.";
}
}
Display images in profile:
session_start();
$username = $_SESSION['username'];
$conn = new mysqli("localhoast", "root", "", "accounts") or die('Connect Error (' . $conn->connect_errno . ') ' . $conn->connect_error);
$sql = "SELECT * FROM `posts` WHERE added_by = ?";
$query = $conn->stmt_init();
$query = $query->prepare($sql);
$query->bind_param('s',$username);
$query->execute();
$images = $query->get_result();
if($images->num_rows > 0)
{
while($image = $images->fetch_assoc())
{
?>
<div style="width:200px ; height: 200px ; border:1px dashed red ; display:inline-block ; margin-top:5px ; margin-left:5px" class="postedBy">
<img src="<?php echo $image['image']; ?>">
</div><!--end image-->
<?php
}
}
You should upload the images to a directory, then keep track of where these images are in the database. Then just link to those images from the information you get out of the database. I didnt test this but the algorithm should all be there. I would suggest changing your insert query to a prepared statement, like i used in the profile section, and you might want to look into something like https://github.com/samayo/bulletproof to make sure people don't upload files which are not actually images.

how to display an auto increment value in a textbox using session

Login.php
session_start();
<?php
$username = "root";
$password = "tiger";
$hostname = "localhost";
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
/* #var $selected type */
$selected = mysqli_select_db($dbhandle,"sample")
or die("Could not select sample");
$name=(\filter_input(\INPUT_POST,'name'));
$phone=(\filter_input(\INPUT_POST,'phone'));
$email=(\filter_input(\INPUT_POST,'email'));
//$custno=(\filter_input(\INPUT_POST,'custno'));
if(!empty(\filter_input(\INPUT_POST,'continue')))
{
echo "<script type='text/javascript'>\n";
'check()';
echo "</script>";
$sql="insert into customersignin(name,phone,email)values('$name','$phone','$email')";
$result=mysqli_query($dbhandle,$sql) or die(\mysqli_error($dbhandle));
}
else
{
$sql1="insert into customersignin(custno)values(NULL)";
$result1=mysqli_query($dbhandle,$sql1) or die(\mysqli_error($dbhandle));
}
$sql2="select custno from customersignin";
$result2=mysqli_query($dbhandle,$sql2) or die (mysqli_error($dbhandle));
$row= mysqli_fetch_array($result2);
if(mysqli_num_rows($result2)>0)
{
echo "$_SESSION['custno']";
unset($_SESSION['custno'];
header('Location:customersvsoup.php');
}
mysqli_close($dbhandle);
$_SESSION[name]=(\filter_input(INPUT_POST,'name'));
customer.php
<body>
<?php session_start(); ?>
<input type="text" style="position: absolute;top:200px;" value="<?php echo $_SESSION["custno"]?>">
</body>
In the php file the customer log in is done,the custno is the auto generate field,i have 2 buttons called continue and skip,for both the auto generate works fine,after any of the button action is done,i need to display the custno in the text box of the next page using session.But the problem is the text box is empty when i run this code.But the session['name'] is working..Please help.
Your session_start(); should come at the beginning of the file in login.php. I see you using $_SESSION[custno] before it's called. That's why your textbox is empty.
Also it should be:
$_SESSION['custno']
$_SESSION['name']note the single quotes
Regarding your logical problem (in the comments) try:
$_SESSION['name'] = (filter_input(INPUT_POST, 'name'));
if (!empty(filter_input(INPUT_POST, 'continue')))
{
echo "<script type='text/javascript'>\n";
'check()';
echo "</script>";
$sql = "insert into customersignin(name,phone,email)values('$name','$phone','$email')";
$result = mysqli_query($dbhandle, $sql) or die(mysqli_error($dbhandle));
$sql2 = "select max(custno) as last_custno from customersignin";
$result2 = mysqli_query($dbhandle, $sql2) or die(mysqli_error($dbhandle));
if (mysqli_num_rows($result2) > 0)
{
$row = mysqli_fetch_assoc($result2);
$_SESSION['custno'] = $row['last_custno'];
header('Location:customersvsoup.php');
}
}
else
{
$sql1 = "insert into customersignin(custno)values(NULL)";
$result1 = mysqli_query($dbhandle, $sql1) or die(mysqli_error($dbhandle));
//since this bit of code is repeating,
//you could even use a function to shorten it
$sql2 = "select max(custno) as last_custno from customersignin";
$result2 = mysqli_query($dbhandle, $sql2) or die(mysqli_error($dbhandle));
if (mysqli_num_rows($result2) > 0)
{
$row = mysqli_fetch_assoc($result2);
$_SESSION['custno'] = $row['last_custno'];
header('Location:customersvsoup.php');
}
}
And please put the session_start(); inside after <?php. All php code should be within the PHP tags.
you have error in insert query:
$sql="insertintocustomersignin(name,phone,email)values('$name','$phone','$email')";
should be :
$sql="insert into customersignin(name,phone,email) values ('$name','$phone','$email')";
you should use quotes in array index :
$_SESSION[custno], $_SESSION[name] should be $_SESSION['custno'], $_SESSION['name']

passing and receiving string variables using php

I am passing the string value through link in the URL to the next page like this <a href="ApplicationRegister.php?plan=trial">
In the ApplicationRegister.php page, i am getting this value like this $plan = $_GET["plan"];
and i will put this into a session variable like this $_SESSION['plans'] = $plan;
Here i am getting the value. but after the if statement i am not getting the value for this plan even after using Session variable.
My complete code is like this
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plan'];
echo $_SESSION['plans'];
include('connect.php');
If (isset($_POST['submit']))
{
$CompanyName = $_POST['CompanyName'];
$CompanyEmail = $_POST['CompanyEmail'];
$CompanyContact = $_POST['CompanyContact'];
$CompanyAddress = $_POST['CompanyAddress'];
$StoreName = $_POST['StoreName'];
echo $plans;
$myURL ="$_SERVER[HTTP_HOST]";
$myURL =$StoreName.'.'.$myURL;
if (stripos($myURL, 'www.') !== 0) {
$myURL = 'www.' . $myURL;
}
if (stripos($myURL, 'http://') !== 0) {
$myURL = 'http://' .$myURL;
}
if(stripos($myURL, '.com') !== 0) {
$myURL = $myURL . '.com';
}
echo $plans;
$RegistrationType = $_POST['RegistrationType'];
$Status = "Active";
$sql = "select * from plans where planname = '$plans'";
echo $sql;
mysql_query($sql) or die (mysql_error());
$planID = $row['planid'];
$query1 = "select count(CompanyEmail) from ApplicationRegister where CompanyEmail = '$CompanyEmail'" ;
$result1 = mysql_query($query1) or die ("ERROR: " . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result1))
{
if($row['count(CompanyEmail)'] > 0)
{
$msg = "<font color='red'> <b>This E-mail id is already registered </b></font> ";
break;
}
}
if($msg == "")
{
$query2 = "select count(URL) from ApplicationRegister where URL = '$myURL' ";
$result2 = mysql_query($query2) or die ("ERROR: " . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result2))
{
if($row['count(URL)'] > 0)
{
$msg = "<font color='red'> <b>This Stroename is already registered </b></font> ";
break;
}
}
if($msg == "")
{
$sql = "INSERT INTO ApplicationRegister(planid, CompanyName, CompanyEmail, CompanyContact, CompanyAddress, RegistrationType, ApplicationPlan, ApplicationStatus, URL, CreatedDate) VALUES ('$planID', '$CompanyName', '$CompanyEmail', '$CompanyContact', '$CompanyAddress', '$RegistrationType', '$plans', '$Status', '$myURL', NOW() )";
mysql_query($sql) or die(mysql_error());
$id = mysql_insert_id();
$_SESSION['application_id'] = $id;
if($plans == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location : PaymentGateway.php");
exit();
}
}
}
}
?>
Only in the beginning it holds the value , if i try to display it within theIf (isset($_POST['submit'])) it shows blank value for plans. Do not know what to do. Plz suggest
EDITED
Even after using like this, its the same. i do not know what may be the problem :(
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plans'] = $plans;
echo $_SESSION['plans'];
// $plan = +$plan;
include('connect.php');
If (isset($_POST['submit']))
{
$CompanyName = $_POST['CompanyName'];
$CompanyEmail = $_POST['CompanyEmail'];
$CompanyContact = $_POST['CompanyContact'];
$CompanyAddress = $_POST['CompanyAddress'];
$StoreName = $_POST['StoreName'];
echo $_SESSION['plans'];
EDITED
In ApplicationRegister.php, i have passed the hiddenvalue which i got fro\m previous page like this
<input type="hidden" name="plan" value="<?php echo $plan ?>"/>
then POST method i have used this. Now i am getting the value for it. Thanks to all
EDITED
if($PlanName == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location : PaymentGateway.php");
exit();
}
It's because you're not calling session_start() at the top of the page. You need that for your sessions to persist across requests (which is the point of sessions)
As well as not calling session_start();, this code is wrong:
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plan'];
echo $_SESSION['plans'];
It should be:
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plans'];
echo $_SESSION['plans'];
You are setting $_SESSION['plan'] and then trying to access $_SESSION['plans'].
Also, are you clicking a link or submitting a form? You say that you have a link, yet your code tries to access values passed from a form.
If you are using a form, don't use links. Instead, use a select element to select a plan, and then change $plan = $_GET["plan"]; to $plan = $_POST["plan"];.
EDIT:
For the redirection problem, try this code:
echo "<pre>** Plan Name: **\n";
var_dump($PlanName);
echo "</pre>";
if($PlanName == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location: PaymentGateway.php");
exit();
}
and see what it outputs.
When someone clicks the link, it's going to set the variable properly. However, it's not going to hit the $_POST['submit'] logic, because it's not a post, just a get. Then, assuming your actually posting to that page at a later point, trying to access anything in $_GET will be null, and will then reset the session variable to null.
Your first page should have code something like this
<form action="ApplicationRegister.php" method="post">
<select name="plan">
<option value="trial">Trial</option>
</select>
<input type="submit"/>
</form>
Then, you check for $_POST['plan'] and $_POST['submit']

Categories