How to get a message id based on the ticket id - php

I'm making a ticket system and trying to add an edit feature.
and I was wondering how do I get the selected message-id that I have chosen to select.
The far as I have got is hard coding the id into the code.
<?php
session_start();
if($_SESSION['loggedin'] == true)
{
require '../../config.php';
$ticketMsg = $conn->query("SELECT * FROM ticket_msgs WHERE ticket_id='".mysqli_real_escape_string($conn, $_GET['id'])."'");
$edit = $conn->query("UPDATE `ticket_msgs` SET `ticket_msg` = 'Testing' WHERE `ticket_msgs`.`id` = ");
if($edit)
{
header("location: ./index.php");
}
else
{
}
}
?>

With mysql PDO:
$sql = 'UPDATE ticket_msgs SET ticket_msg=:msg WHERE id=:id';
// prepare statement
$statement = $conn->prepare($sql);
// bind params
$statement->bindParam(':msg', $ticketMsg);
$statement->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
// execute the UPDATE statement
if ($statement->execute()) {
// updated, go to your index page
header("location: ./index.php");
}

Related

Checking if value is stored in the database with isset()

I want to display a page, if user doesn't pay for content (via Stripe) and therefore have to check in DB if he paid or not. If he paid, I store string "ok" into status and if he doesn't it's just blank.
Now I'm not sure why the following code doesn't work:
<?php
if(!isset($_SESSION["username"])) {
?>
Login to watch Satellite data.
<?php
$query = 'SELECT status
FROM users
WHERE username="'.$_SESSION["username"].'"';
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$status = $row["status"];
if ($status !== "ok") {
$status_notpaid = true;
}
}
} elseif(isset($_SESSION["username"]) && isset($status_notpaid)) {
include("notpaid.php");
} else {
?>
<?php
$query = 'SELECT id
FROM users
WHERE username="'.$_SESSION["username"].'"';
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
?>
Hello <strong><?php echo $_SESSION["username"];?></strong> |
<?php
while ($row = $result->fetch_assoc()) {
echo $row["id"]; }
?>
I'm not sure why elseif(isset($_SESSION["username"]) && isset($status_notpaid)) { include("notpaid.php"); } doesn't work.
I am assuming the login script sets $_SESSION["username"] if login is successful.
It would make more sense to put the id of the users table, as I assume that is the primary key. You can keep username in session as well if you like and that would save you running some of this code at all.
<?php
if(!isset($_SESSION["userid"])) {
# user not logged in direct to login, and nothing else
echo 'Login to watch Satellite data.';
}
if (isset($_SESSION["userid"])) {
# then we are logged in
# So now we check if they paid
$query = 'SELECT status
FROM users
WHERE id=?';
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $_SESSION["userid"])
$stmt->execute();
$result = $stmt->get_result();
# we had better only be getting one row as a resut of that query
# so a loop is totally unnecessary
$row = $result->fetch_assoc();
$status = $row["status"];
if ($status !== "ok") {
include("notpaid.php");
}
}
?>
Hello <strong><?php echo $_SESSION["username"];?></strong> | $_SESSION['userid']

Update value using php

I want to update the marks of a student in php.
All the values are fetching properly from the table.
But after changing the value it is not updating.
<?php
session_start();
error_reporting(0);
include('includes/config.php');
if(strlen($_SESSION['alogin'])=="")
{
header("Location: index.php");
}
else
{
$stid=intval($_GET['stid']);
if(isset($_POST['submit']))
{
$rowid=$_POST['id'];
$ct=$_POST['ct'];
$wt=$_POST['wt'];
$pro=$_POST['pro'];
$ter=$_POST['ter'];
foreach($_POST['id'] as $count => $id)
{
$c=$ct[$count];
$iid=$rowid[$count];
for($i=0;$i<=$count;$i++)
{
$sql="update tblresult set ct=:c,wt=:w,pro=:p,ter=:t where id=:iid ";
$query = $dbh->prepare($sql);
$query->bindParam(':c',c,PDO::PARAM_STR);
$query->bindParam(':w',w,PDO::PARAM_STR);
$query->bindParam(':p',p,PDO::PARAM_STR);
$query->bindParam(':t',t,PDO::PARAM_STR);
$query->bindParam(':iid',$iid,PDO::PARAM_STR);
$query->execute();
$msg="Result info updated successfully";
}
}
}
}
?>
enter image description here
It looks like the values you're using for bindParam aren't correct.
$query->bindParam(':c',c,PDO::PARAM_STR); for example looks like it should be:
$query->bindParam(':c', $ct, PDO::PARAM_STR);
I would also look at being more consistent with your variable names and maybe the 'Result info updated successfully' message is possibly a little presumptuous.

This sample delete code wont delete items from database

This a sample delete code I created to delete entries MySQL database. When I execute this code, Successful message displays but entries wont delete from the database. Records are kept track the primary key in the 'events' table 'id'
<?php
require 'dbconnect.php';
session_start();
$id=$_SESSION['id'];
$id = "0";
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( !empty($_POST)) {
// keep track post values
$id = $_POST['id'];
// delete data
$sql="DELETE * FROM events WHERE events.id='$id'"; //mysqli query
$result=mysqli_query($conn,$sql); //connection string and mysqli query variable
if($result==true)
{
echo "<script type='text/javascript'>alert('successfully DELETED!')</script>"; // javascript message for Successful delete
echo "<script>setTimeout(\"location.href = 'list_events.php';\",15);</script>"; // return page
}
else
{
echo "<script type='text/javascript'>alert('failed to DELETE RETRY!')</script>"; //failed to delete message
echo "<script>setTimeout(\"location.href = 'list_events.php';\",15);</script>"; //return page
}
header("Location: list_events.php"); // header page
}
?>
You can use this
$sql="DELETE FROM events WHERE events.id='{$id}'"; //mysqli query
Just to be safe.
Do check if you are getting some value in $id and it also exist in database.
Use DELETE FROM instead of DELETE * FROM and you can use the following commands for more security:
$sql="DELETE FROM events WHERE events.id=?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('d',$id);
/* execute prepared statement */
$result = $stmt->execute();

How to delete the image path from a server using unlink in PHP?

I've almost finished my project but I'm stuck on a small problem I'm hoping to get help with. This is my first PHP/mysqli project and I'm still very "green". Any help is much appreciated.
I have been able to successfully upload and delete images from my database, however I can't seem to get the unlink command to delete the images from my server.
Please find below the code I am using in the background (hotel-imgdelete.php):
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
// confirm that the 'id' variable has been set
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get the 'id' variable from the URL
$id = $_GET['id'];
// delete image from server
$path = "../hotels/";
$image = "name";
unlink($path.$image);
// delete record from database
if ($stmt = $mysqli->prepare("DELETE FROM hotels WHERE id = ? LIMIT 1"))
{
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: could not prepare SQL statement.";
}
$mysqli->close();
// redirect user after delete is successful
header("Location: ../home.php");
}
else
// if the 'id' variable isn't set, redirect the user
{
header("Location: ../delete-hotel-images.php");
}
?>
This is the code I am using to view and select the images to delete
(delete-hotel-images.php)
<?php
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM hotels ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
$row->id;
echo "<div id='partner'><img src='hotels/" . $row->name . "'></a><br><br>";
echo "<center><a href='#' onclick='delete_user(". $row->id . ")'>Delete</a></center></div>";
}
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
?>
I'm not entirely sure what your filesystem looks like, or what the file is supposed to be, but it looks like you're trying to delete "../hotels/name", since $image is set to the string "name".
I'm assuming this wasn't intentional so that could be the problem there. If, however, you are trying to delete a directory (since it appears to have no file extension) you will need to use "rmdir" and not "unlink".
How are the images laid out on your filesystem?
sorted
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get the 'id' variable from the URL
$id = $_GET['id'];
if ($stmt = $mysqli->prepare("SELECT id, name FROM hotels WHERE id=?"));
{
$stmt->bind_param("i", $id);
$stmt->execute();
}
$stmt->bind_result($id, $name);
$stmt->fetch();
$path = "../images/hotels/";
$image = $name;
unlink($path.$image);
$stmt->close();
include_once 'db_connect.php';
include_once 'functions.php';
// delete record from database
if ($stmt = $mysqli->prepare("DELETE FROM hotels WHERE id = ? LIMIT 1"))
{
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: could not prepare SQL statement.";
}
$mysqli->close();
// redirect user after delete is successful
header("Location: ../home.php");
}
else
// if the 'id' variable isn't set, redirect the user
{
header("Location: ../delete-hotel-images.php");
}

Causing a redirect loop, can't figure out why or a better way to achive the same goal

Im trying to make a cart page, simple but im causing a redirect loop and can't figure out why.
what im trying to do:
make items sent to cart.php as cart.php?item={id}
Send them to login if they are not already logged in, but temporarily save what they are trying to add so it can be complete once they login.
It then checks for a cart, if no cart exists it should make one and resend the request again.
if they have a cart, it should add the item to 1_cart_items.
what is happening?
A redirect loop is happening, and the cart is being made with each redirect. Noting that idealy a user should only have 1 active cart at a time.
(Note that the redirect loop only happens when logged in, and when the query string ?item={id} is sent.
<?php
include 'globals.php';
global $dbh;
//include 'member_func.php';
$vartomatch = hash('sha1', "{$_SERVER['REMOTE_ADDR']}");
if (!$_SESSION['logged_in']) {
if ($_GET['item']) {
$_SESSION['active_cart_item'] = $_GET['item'];
}
header("location: login.php");
exit;
}
if (isset($_SESSION['active_cart_item'])) {
$adding = $_SESSION['active_cart_item'];
unset($_SESSION['active_cart_item']);
header("location: cart.php?item=$adding");
}
else if ($_SESSION['ip'] !== $vartomatch) {
header("location: account.php?act=logout");
}
else {
$userid = $_SESSION['user'];
$stmt = $dbh->prepare("SELECT * FROM `1_members` WHERE id=? LIMIT 1");
$stmt->bindValue(1, $userid, PDO::PARAM_INT);
$stmt->execute();
$ir = $stmt->fetch(PDO::FETCH_ASSOC);
}
if (isset($_GET['item'])) {
// item set, see if they have active cart to add item too...
if (isset($_SESSION['active_cart'])) {
// they do. check db for cart.
$stmt = $dbh->prepare("SELECT * FROM `1_cart` WHERE `belongs_to`=? AND `complete`=?");
$cartid = $_SESSION['active_cart'];
$stmt->bindValue(1,$cartid,PDO::PARAM_INT);
$stmt->bindValue(2,'0',PDO::PARAM_INT);
$stmt->execute();
if ($stmt->rowCount()) {
//Got thier cart. Now Check it is thiers.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row['belongs_to'] !== $_SESSION['user']) {
die('hack attempt');
}
// good stuff, now we are ready for the item id.
//Should we set a session variable to identify cart or just do db the normal way?
$itmid = $_GET['item'];
$stmt = $dbh->prepare("SELECT * FROM `3_types` WHERE `id`=?");
$stmt->bindValue(1,$itmid,PDO::PARAM_INT);
$stmt->execute();
if (!$stmt->rowCount()) {
echo '
Sorry you are trying to add an item that does not exist or that has been deleted
and is no longer in existance.';
exit;
die('<br /> See above.');
}
$r=$stmt->fetch(PDO::FETCH_ASSOC);
$thiscart = $_SESSION['active_cart'];
$serv_name = $r['serv_name'];
$serv_title = $r['serv_title'];
$serv_price = $r['serv_price'];
$warranty_type = $r['warranty_type'];
$image = $r['image'];
$turn_around = $r['turn_around'];
// should this be in a while loop when we only expect 1 result?
$stmt = $dbh->prepare("INERT INTO `1_cart_items` (`origid`,`forid`, `name`, `title`, `price`, `warranty`, `image`, `turn_around`)
VALUES(?,?,?,?,?,?,?,?)");
$stmt->bindValue(1,$itmid,PDO::PARAM_INT);
$stmt->bindValue(2,$thiscart,PDO::PARAM_INT);
$stmt->bindValue(3,$serv_name,PDO::PARAM_STR);
$stmt->bindValue(4,$serv_title,PDO::PARAM_STR);
$stmt->bindValue(5,$serv_price,PDO::PARAM_INT);
$stmt->bindValue(6,$warranty_type,PDO::PARAM_INT);
$stmt->bindValue(7,$image,PDO::PARAM_STR);
$stmt->bindValue(8,$turn_around,PDO::PARAM_STR);
$stmt->execute();
header ("location: cart.php");
}
else {
// THE SESSION VARIABLE LIED! THEY DON'T GOT A CART!!!!!
unset($_SESSION['active_cart']);
// reload the page...
// make them send the same get request.
header ("location: cart.php?{$_SERVER['QUERY_STRING']}");
}
}
else {
// make a cart for them.
$stmt = $dbh->prepare("INSERT INTO `1_cart` (`belongs_to`, `complete`) VALUES (?, ?)");
$stmt->bindValue(1, $userid, PDO::PARAM_INT);
$stmt->bindValue(2,'0',PDO::PARAM_INT);
$stmt->execute();
$_SESSION['active_cart'] == $userid;
header("location: cart.php?{$_SERVER['QUERY_STRING']}");
}
}
1: What is causing the redirect loop?
2: Have I done this the long way / any cleanups to suggest?
Right at the top of your code after your first and second if you just redirect, perhaps you forgot your else?
if (!$_SESSION['logged_in']) {
if ($_GET['item']) {
$_SESSION['active_cart_item'] = $_GET['item'];
} else {
header("location: login.php");
exit;
}
if (isset($_GET['item'])) {
// item set, see if they have active cart to add item too...
...
...
header("location: cart.php?{$_SERVER['QUERY_STRING']}");
}
So each time you are in ?item=x your script will redirect to ?item=x until forever, because every time you visited http://example.com?item=x your QUERY_STRING will be item=x and $_GET['item'] will be set

Categories