Ajax Setting Session ID Failing Coordination with PHP query - php

So I am trying to make a discussion board and I have a table of posts being queried in one column of a table on the discussion board page. I then have the buttons of those post set up to a function onclick (where I am passing the post ID and then posting it to set_id.php to set as $_SESSION['name'] = $_REQUEST['name']):
scripts.js:
function getcomments(id){
$("#success_child").empty();
$.post("discussion_topics/set_id.php", {
"name": id}).done($("#success_child").load("discussion_topics/comments.php",
function(responseTxt, statusTxt, xhr){
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
}));
}
The problem is, although the Post ID is being set correctly, the php file being loaded will load the previously set SESSION variable that is the post ID. I have absolutely no idea why.
Basically, the SEssion variable is being set properly, however, when a new post is clicked, it will query in the comments.php the old session ID, then when you click again it will query that last one that didn't show. Basically a delay somehow. But it is not a time delay because I have tried that.
HELP!
comment.php:
<?php
session_start();
echo $_SESSION['name'];
function draw_table(){
/* draw table */
$table = '<table cellpadding="0" cellspacing="0" class="discuss_table">';
//Connect To Database
$hostname="localHost";
$username="removed";
$password="removed";
$dbname="removed";
$usertable="replys";
mysql_connect($hostname,$username, $password) or die ("<html> <script>alert('Unable to connect to database! Please try again later.'),history.go(-1)</script>");
mysql_select_db($dbname);
# Check If Record Exists
$id = $_SESSION['name'];
$query = "SELECT * FROM $usertable WHERE post_id = $id";
$result = mysql_query($query);
if($result)
{
while($row = mysql_fetch_array($result))
{
//build table for post
$date = date("M d Y h:ia e", strtotime($row["date"]));
$table.="<tr>";
$table.= "<p class=\"discussion_title\">";
$table.= "<b>".$row["title"]."</b>"."<br>";
$table.=$row["name"].", ".$date." for topic ".$row["topic"]."<br>";
$table.=$row["content"]."<br>";
$table.="<button class=\"makecomment_buttons\">Reply</button>";
$table.="</p></tr>";
}
}
//end the table
$table.= '</table>';
//all done, return result
return $table;
}
echo draw_table();
echo "<br>";
?>
set_id.php
<?php
session_start();
$_SESSION['name'] = $_REQUEST['name'];
?>

Related

PHP Not deleting MYSQL Database row

I've spent a lot of time messing around with PHP and MYSQL and I've finally managed to create a "to do list" sort of thing that allows the user to submit a "to do" task and for it to add it to a database and then show it. I've followed many tutorials as I've tried to teach myself PHP blah blah. But for some reason i cannot get the delete script working.
echo "<td><a href='delete.php?=Delete" . $row['task_id']."'>Delete"."</a>"."</td></tr>" . "$record->ID";
Above is the code for the delete button
Here is the delete script apologies for the many commented out lines I've tried many 'solutions'.
$ID = $_GET['task_id'];
//$delete_query = "DELETE FROM Tasks WHERE ID = $ID" ;
$sql = "DELETE FROM Tasks WHERE task_id = $ID;";
echo $row['task_id'];
// $delete_query = "DELETE FROM Tasks WHERE task_id = ['task_id'] ";
/* if(isset($GET['task_id'])){
$delete = $_GET['task_id'];
mysqli_query($connect, "DELETE FROM Tasks WHERE task_id = '$delete'");
} */
echo("Succesfully deleted");
mysqli_close($link);
The script runs and it says "successfully deleted" but the entry still shows. In the F12 Menu/Network tab I get this
error
And when I click "view source" it shows the ID of the row. I can't seem to figure out what is wrong.
I am try to delete data using php pdo. and data can deleted successfully so you can try this code.
I have created 2 file. first req.php and second delete.php.
Here req.php file can fetch data and delete.php file can delete this data from send req.php file id.
req.php
<?php
require "connection.php";
//This is a fetch data from database
$sql = "SELECT * FROM test";
$select = $conn->prepare($sql);
$select->execute();
?>
<html>
<head>
<title>Data</title>
</head>
<body>
<table>
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>EMAIL</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
while($data = $select->fetch())
{
?>
<tr>
<td><?php echo $data['id']; ?></td>
<td><?php echo $data['student_name']; ?></td>
<td><?php echo $data['email_address']; ?></td>
<td><button onclick="return conformation();">Delete</button></td> <!-- This is a delete data button --->
</tr>
<?php
}
?>
</tbody>
</table>
</body>
</html>
<script>
//This is a conformation function if it will return true then data can delete otherwise data cannot deleted.
function conformation() {
let conform = confirm("Can you delete this data ?");
if (conform == true) {
return true;
} else {
return false;
}
}
</script>
delete.php
<?php
require "connection.php";
if(isset($_GET['id']))
{
$sql = "DELETE FROM test WHERE id = ?";
$deleteData = $conn->prepare($sql);
if ($deleteData->execute([$_GET['id']]))
{
header('location: http://local.test/req.php');
}
}
?>
The first issue is trying to get task_id from REQUEST params while you sending "Delete" key.
The second is you passed the task_id to db as a string, while I think it's an Integer type in the database.
So you have to do that:
echo "<td><a href='delete.php?task_id=" . $row['task_id']."'>Delete"."</a>"."</td></tr>" . "$record->ID";
$task_id = mysqli_real_escape_string($connect, $_GET['task_id']);
if (!empty($task_id)) {
$delete_query = mysqli_query($connect, 'DELETE FROM Tasks WHERE task_id = '.$task_id);
if ($delete_query) {
echo 'deleted successfully';
} else {
echo("Error: " . mysqli_error($connect));
}
} else {
echo 'task_id is empty !';
}
You can solve this or debug it by doing the following.
parse the right URL parameter
echo "<td><a href='delete.php?task_id=" . $row['task_id']."'>Delete"."</a>"."</td></tr>" . "$record->ID";
this will send a task_id value to the delete page.
checking and logging the response of my SQL in delete.php
if(isset($_REQUEST['task_id'])){
//escape to avoid SQL injection
$delete = mysqli_real_escape_string($connect, $_REQUEST['task_id']);
$process = mysqli_query($connect, "DELETE FROM Tasks WHERE task_id = '".$delete."'");
if($process){
echo("Succesfully deleted");
}else{
echo("Error description: " . mysqli_error($connect));
}
}else{
echo("no id supplied");
}
in your question, you also had this: $GET['task_id'], which I believe was null.

PHP prevent URL input to delete row in database

I’m working on a blog website where the idea is that the current user that is logged in can edit and delete their own posts. I finally got it to work, but my question is how I can prevent that a user can write the following input in the URL and do the same actions as my delete.php action.
(Example) Manual URL input with topic_id:
/delete.php?del=133
Do anyone know how I can edit my existing code or know a better solution to the problem I will be much grateful!
This is how my code looks:
Profile.php:
if (#$_GET['id']) {
$check_d = mysql_query("SELECT * FROM users WHERE id ='".$_GET['id']."'");
while ($row_d = mysql_fetch_assoc($check_d)) {
echo "<div class='spacer'></div><h2 class='headertext'>Inlägg skapade av : ".$row_d['username']."</h2>";
$check_u = mysql_query("SELECT * FROM topics WHERE topic_creator='".$row_d['username']."' ORDER BY topic_id DESC");
while ($row_u = mysql_fetch_assoc($check_u)) {
$id = $row_u['topic_id'];
echo "<tr>";
echo "<td class='postmain'><a href='topic.php?id=$id' class='links'>".$row_u['topic_name']."<br /></a></td>";
echo "<td class='postmain'><p class='text'>".$row_u['topic_creator']."</p><br /></td>";
echo "<td class='postmain'><p class='text'>".$row_u['date']."</p><br /></td>";
if($_SESSION['username'] === $row_u['topic_creator']) {
echo "<td class='postmain'><a href='edit.php?edit=$id'><button>Redigera</button></a>";
echo "<a href='delete.php?del=$id'><button>Ta bort</button></a></td>";
}
echo "</tr>";
}
}
}
The highlighted code shows that only the current session (user) who made the post can edit and delete their own posts.
Delete.php:
if (isset($_GET['del'])) {
//getting id of the data from url
$id = $_GET['del'];
//deleting the row from table
$sql = "DELETE FROM topics WHERE topic_id='$id'";
$res = mysql_query( $sql );
//redirecting to the display page
header("Location:admin.php");
}
Using isset function is solution here . The isset function will check that whether user clicked the delete/modify link or not(i.e he pasted delete.php directly in link) . So your code will only execute when user clicks the link .
if (isset($_GET['del']))
{
// your profile.php code here
}
else
{
// error message
}
You can use the same $_SESSION logic to ensure anyone accessing the delete.php has the appropriate permissions.
if (isset($_GET['del'])) {
//getting id of the data from url
$id = $_GET['del'];
// Get the author for the specified post to ensure they are permitted to do so
// TODO
// Check that the author is the same as the $_SESSION user
if($_SESSION['username'] === $postAuthor) {
//deleting the row from table - FIX THIS (see below)
$sql = "DELETE FROM topics WHERE topic_id='$id'";
$res = mysql_query( $sql );
} else {
// User is not authorized, create error handling
// TODO
}
//redirecting to the display page
header("Location:admin.php");
}
Unrelated, beware of SQL injection. Bobby Tables is a good guide and you should not be using the mysql_ functions and should be using prepared statements.

execute mysql DELETE query on click

i'm kind of a new player in php and sql field.
i'm trying to delete identity from my persons table when clicking on the remove link (or button)
can somebody tell me what am i doing wrong?
this is my php code:
<?php
$db = new DB();
$cg_id = $_SESSION['cg_id'];
$cg_address_id = $_SESSION['cg_address_id'];
$sql ="SELECT f_name, phone, c.id as idc
FROM contacts as c
WHERE c.cg_id = '$cg_id'";
$result = $db->mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<article class='contactArea'>";
echo "<a href='contacts2.php?del=".$row["idc"]."' class='deleteContact' name='remove' value='remove'>Remove</a></article>";
if(isset($_POST['idc'])){
$idco = $_POST['idc'];
$removeQuery = "DELETE FROM contacts as c WHERE id=".$idco." ";
$resultt = mysql_query($removeQuery);
if($resultt) {
header('Location: '.$_SERVER['REQUEST_URI']);
}
echo "<script>window.location.reload(true);</script>";
}
}
}else {
echo "Please edit senior profile for monitoring!";
}
?>
Try this (obviously replacing "localhost", "dbuser", "dbpassword" and "database_name" with the details for your mysql server and database):
<?php
$db = new mysqli("localhost","dbuser","dbpassword","database_name");
$cg_id = $_SESSION['cg_id'];
$cg_address_id = $_SESSION['cg_address_id'];
// I've moved the deletion code to BEFORE the select query, otherwise the
// query will be shown including the to-be-deleted data and it is then deleted after it is displayed
if(isset($_GET["del"])){ // <--- this was $_POST["del"] which would have been unset
$idc = $_GET["del"];
if($db->query("DELETE FROM contacts WHERE id=$idc")){
echo "deleted";
} else {
echo "fail";
}
}
$sql ="SELECT photo, f_name, phone, street, street_num, city, l_name, c.id as idc FROM contacts as c, address as a WHERE c.cg_id = '$cg_id' and a.id = c.address_id";
$result = $db->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<article class='contactArea'>";
echo "<article class='contact5 lior'>";
echo "<img class='CSImage' src='" .$row["photo"]."'>";
echo "<section class='generalFormTextW nameCPosition'> " .$row["f_name"]." ".$row["l_name"]."<br></section>";
echo "<section class='generalFormTextW phoneCPosition'> " .$row["phone"]."<br></section>";
echo "<section class='generalFormTextB addressCPosition'>".$row["city"].", <br> ".$row["street"]." ".$row["street_num"]. "<br></section>";
echo "<a href='contacts2.php?del=".$row["idc"]."' class='deleteContact' name='remove' value='remove'>Remove</a></article></article>";
}
}
?>
Notice that I'm changing the way you're using mysqli so that you are using it directly rather than as a member of the DB object which is the way I've seen it used elsewhere - It looks to me as if you don't actually open the database connection (although maybe you just didn't include it because it showed your password?)
**EDIT: I've changed $_POST["del"] to $_GET["del"] -- because you are setting del in a url ("contacts2.php?del=") this will be GET not POST.
**EDIT: I've moved the deletion code so that it fixes the problem where you have to refresh the page to see the data with the record deleted - previously the information was shown and THEN deleted, we want to delete THEN show.

Checkbox that updates dynamically

I have a checkbox that dynamically updates a MySQL database when it is checked/unchecked using PHP and Ajax.
I am now trying to pass the users name so that the Ajax script can update the database with the users full name.
I have the name held in a variable called $full_name. I cannot seem to get this working though. Please see the code below:
Javascript:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function chkit(uid, chk) {
chk=document.getElementById("chk").checked;
$.ajax({
type: 'GET',
url: 'ajax.php',
data: { chkYesNo: chk, record_id: uid, full_name: user},
success:function(data){
// successful request; do something with the div background color
if(data==1)
{
$("#replace").addClass("checked_div_status").removeClass("replace");//removing first class and adding second class
}
else
{
$("#replace").addClass("replace").removeClass("checked_div_status");//removing second class and adding first class
}
}
});
}
</script>
HTML:
<?php
$record_id = $_GET['veh_id'];
include '../dbconnect.php';
//fetching data from database
$select=mysql_fetch_array(mysql_query("select invoice_checked from vehicle_details where veh_id = '$record_id' "));
?>
<!--The checkbox whose enable to change div his background color and onclick call function to update database-->
<table width=“100%”>
<td id="replace2" class="<?php if($select['invoice_checked']==1) { echo 'checked_div_status2'; } else{ echo 'replace2'; } ?>">
<input name="chk2" type="checkbox" id="chk2" value="1" onclick="chkit2(<?php echo $record_id;?>,'chk2');" <?php if($select['invoice_checked']==1) { echo 'checked'; } else{ echo ''; } ?> />
Invoice Checked
</td>
</table>
Ajax.php:
<?php
mysql_connect("server", "username", "password") or die("Could not connect: " . mysql_error());
mysql_select_db("database");
//here $get variable receive checkbox value true(1) either false(0)
$get=$_GET['chkYesNo'];
//here $get_id variable receive value of current id that you passed
$get_id=$_GET['record_id'];
$get_user=$_GET['full_name'];
if($get=="true")
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='1', check_user='".$get_user."' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
else
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='0', check_user='0' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
?>
Any help would be greatly received.
Thanks,
John
Some debug lession for you. Please, check my comments:
// Do not need to replicate your code, if the same things happens in it.
//instead, use a condition to set your variables, and use these variables later.
if ($get == "true") {
$hpi_registered = 1;
//Escape your variable to avoid sql injection
$checkUser = mysqli_real_escape_string($conn, $_GET["full_name"]);
} else {
$hpi_registered = 0;
$checkUser = 0;
}
//Store your query in a variable, so you can debug / dump it
//Let's dump it, see, what is your query, and try to run in directly in sql.
//Maybe it has syntax error.
$sql = "UPDATE vehicle_details SET"
. " hpi_registered='" . intval($hpi_registered) . "',"
. " check_user='" . $checkUser . "'"
. " WHERE veh_id='" . intval($get_id) . "'";
mysqli_query($conn, $sql);
//What happens, if you run it directly in sql? If this fails, now here is your
//error.
$sql = "SELECT hpi_registered"
. " FROM vehicle_details"
. " WHERE veh_id='" . intval($get_id) . "'";
//Do the same like previous query.
$res = mysqli_query($conn, $sql);
$select = mysqli_fetch_array($res);
echo $select['hpi_registered'];
DO NOT use mysql functions, because they are deprecated. Use mysqli or PDO instead.
Avoid sql injection by escaping your variables.

updating a flag in mysql via radiobutton onclick handler in php

I want to update a column in a table in mysql. Basically the column is the flag for the entries of that db table.
The modification of the column is resetting all values to 0 and setting the desired row to 1, for this reason I have post.php file which looks like
<?php
require_once('class.uuid.php');
$connection = mysql_connect("---logindetailshere---");
$db = mysql_select_db("---dbnamehere---",$connection);
switch($_REQUEST['action']){
case ...
break;
case ...
break;
case 'changeDisp':
changeDisp($_REQUEST['uid']);
break;
}
mysql_close($connection);
...
function changeDisp($uid){
global $connection, $db;
$q_string = "UPDATE Questions SET Displayed = 0";
$query = mysql_query($q_string,$connection) or die( sendError(mysql_error() . '<br/><br/>' . $q_string) );
$q_string = "UPDATE Questions SET Displayed = 1 WHERE Uid='${uid}'";
$query = mysql_query($q_string,$connection) or die( sendError(mysql_error() . '<br/><br/>' . $q_string) );
}
?>
on the webpage I display the items and radiobuttons next to the items, the purpose is to select the radiobuttons and post to set the flag 1 for the selected item, for this reason I have a item.php file
<?php
$i = 1;
foreach ($qitem as &$q) {
$options = explode(";", $q["Options"]);
$displayed = '';
if ($q["Displayed"] == 1) { $displayed='checked="yes"'; }
echo("<div class='item' name='".$q["iUid"]."'>");
echo("<div class='count'>".$i.".</div>");
echo ("<div class='radio'><input type='radio' onclick='changeDisp("".$q["Uid"]."")' name='disp' ".$displayed."></div>");
echo("<div class='left'>");
echo("<h4>".$q["Value"]."</h4>");
echo("<div class='details'>Typ: ".$q["Type"]."</div>");
echo("<div class='details'>Skala: ".$options[0]." / ".$options[1]."</div>");
echo("</div>");
echo("</div>");
$i++;
}
?>
here I am using radiobuttons to select the related item, I checked the unique id values using firebug the values are fine, I just want to click on any radiobutton and want to trigger the onclick=changeDisp() function.
I have no idea why the page doesn't reload itself and change the selected flag to 1. Could you please help me to solve this problem?
Thanks in advance.
You cannot use an onclick function to call php function without going there with a javascript, jQuery or ajax call. You could create an ajax script to call the post.php From the item.php page and return the results to you.
Here is an example of creating the function you want. This assumes that $uid is coming from a radio button and not an actual user input. If the user can directly input something you need to use a prepared statment
function changeDisp($uid)
{
$Mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($Mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $Mysqli->connect_errno . ") " . $Mysqli->connect_error;
$Mysqli->close();
}
$query = "UPDATE Questions SET Displayed = 1 WHERE Uid='".$uid."'";
$update = $Mysqli->query($query);
if($update)
{
return true;
}
return false;
}

Categories