Creating Link For User To Delete Row - php

I'd like to ask two things for this particular user ability. The first is how to delete a row upon user clicking a button. The second is....would this be a good idea? How can I create a safe environment for someone to do this. This is what I've got so far :
<?php
include_once "db_conx.php";
if($_POST['wall'] == "post") {
//open if($_POST['wall'] == "post")
$id = mysqli_real_escape_string($db_conx, trim($_POST['id1']));
if($id == " ")
{
exit();
}
else
$sql = "SELECT FROM courseprogress WHERE userid='$id' LIMIT 1";
$results = mysqli_query($db_conx, $sql);
$sidebar = mysqli_num_rows($results);
if($sidebar > 0) {
//close if($sidebar > 0)
while($row = mysqli_fetch_assoc($results))
{
$sql = mysqli_query("DELETE FROM courseprogress WHERE userid='$id'");
$results = mysqli_query($db_conx, $sql);
}
//close if($sidebar > 0)
}
else
{
echo 'Already Complete!';
echo "<pre>";
var_dump($sql);
echo "</pre><br>";
}
//close if($_POST['wall'] == "post")
}
?>
Right now I'm in the process of dumping out variables, but can't seem to get my id variable right.
The idea is to "start over" in a sense. The table holds the user progression and settings. Once they've decided they need to start over they will be allowed to do so by simply deleting the row. When the begin again the row will be created again.
A little more information:
The small form script I was trying to use is:
<div class="userInfoContain"><div class="positionRight"><div id="form"> <form><div class="submit"><input type="hidden" id="id" value="'.$id.'" /><input type="submit" name="button" id="button" value="Start Over" onclick="return false" onmousedown="javascript:wall();"/><img src="images/loading.gif" alt="" width="15" height="15" id="loadingstart" /></div></form></div></div></div>
<script type="text/javascript">
$(document).ready(function(){
$('#loadingstart').hide();
});
function wall(){
$('#loadingstart').show();
var id = $('#id').val();
var URL = "./includes/start-over-user.php"; /////post.php will be equal the variable "comment"
$.post(URL,{wall:"post",id1:id},function(data){//parameter wall will be equal "post", name1 will be equal to the var "name" and comment1 will be equal to the var "comment"
$("#result").prepend(data).show();// the result will be placed above the the #result div
$('#loadingstart').hide();
});
}
</script>

1) Safely allow user to delete: The safest way is to not allow delete permissions on the MySQL user that is being used by the website. A method called soft delete is much safer for deleting rows in MySQL tables. This involves adding a column named "is_deleted" to the table where you are making this update. When is_deleted is set to 0, allow the row to act normally. When a user sets is_deleted to 1, it should act as if it doesn't exist. In this example, I am assuming you have set $is_deleted to the column is_deleted in your table:
if($is_deleted == '1')
{
// Don't display
}
else
{
// Display
}
2) How to implement: The best way to do this is with:
UPDATE tablename SET is_deleted = '1' WHERE id = '".$id."'
which should be executed through AJAX command or a link that will execute the MySQL query.

to delete I advice you to use ajax , it's perfect and you can have more control on this action
the other Problem i need more explanation i didn't understand you good

Related

Comparing user input data to mysql db

so i've recently got a job at a market, and they got a lot of PLU's that i need to know. So for helping me, i'm trying to do something to help me.
I've created a database with some of the items that look like this:
id art img plu_code
and in my index.php, after connecting to database and selecting a random id to show
$query = "SELECT * FROM produto ORDER BY RAND() LIMIT 1";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$imagem_produto = $row["imagem"];
$nome_produto = $row["artigo"];
$plu_produto = $row["plu"];
echo '<center><tr>
<td><img height="150" width="150" src="'.$imagem_produto.'"></td><br>
<td>'.$nome_produto.'</td><br>
<td>'.$plu_produto.'</td>
</tr></center>';
}
$result->free();
if ($plu_produto === $_GET['U']) {
echo "Correct. Please wait!";
header("Refresh:3");
}else{
echo 'Wrong.';
}
}
?>
<html>
<body>
<form method="post">
<input type="text" name="U"/>
<input type="submit" />
</form>
</body>
</html>
How do i compare the user input to the db and then show if it's correct or wrong? Thank you!
It is not like comparing the user input to the db.
Your code
if ($_POST['U'] === $plu_produto) {
compares with the last row read by the while loop which is not as expected.
After connecting to the database, have code to show all data which will show up in the first run. And after the user input you should select the relevant rows from the database itself which matches with "U" where there should not be any while loop but the sql select itself should return only one row.
You should just query for the specific PLU, not the entire table.
You also need to use $_POST, not $_GET, since the form has method="POST".
if (isset($_POST['U'])) {
$plu_produto = $_POST['U'];
$stmt = $mysql->prepare("SELECT 1 FROM produto WHERE plu = ?");
$stmt->bind_param("s", $plu_produto);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
echo "Correct. Please wait!";
header("Refresh:3");
}else{
echo 'Wrong.';
}
exit;
}

php - How to keep image buttons state after refresh

I am having a problem keeping the state of some image buttons after refresh or log out. I have a favourite button on each article on page that a user can click to favourite it. I use the following jquery function to send the unique id of the post to a mysql table:
$('.faver').on('click',function() {
var articleId = $(this).closest('.row').attr('id');
$.ajax(
{
url: "favscript/addremove",
method: "POST",
data: { favourite: articleId },
success: function()
{
alert(<?php echo $favid ?>);
}
});
});
then in the recieving php file i get the session variable like this:
session_start();
if(isset($_SESSION['id']) AND isset($_POST['favourite'])){
$user = mysql_real_escape_string($_SESSION['id']);
$_SESSION['favourite'] = $_POST['favourite'];
$favid = mysql_real_escape_string($_SESSION['favourite']);
and then I insert values into mysql table like so:
// Firstly, check if article is favourite or not
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE user=$user AND favid=$favid");
$matches = mysql_num_rows($query);
// If it is not favourited, add as favourite
if($matches == '0'){
mysql_query("INSERT INTO ajaxfavourites (user, favid) VALUES ('$user', '$favid')");
}
// Instead, if it is favourited, then remove from favourites
if($matches != '0'){
mysql_query("DELETE FROM ajaxfavourites WHERE user=$user AND favid=$favid");
}
}
Now all of the above is working but my problem is that I can't seem to figure out a way for each button to remember its state once the user refreshes or logs out. if I set $favid to $_SESSION['favourite'] it will just set the button state the same for all buttons after refresh.
this is how i check what the button state should be:
<!--Favourite Button-->
<div id="favouritediv">
<?php
$user = $_SESSION['id'];
$favid = $_SESSION['favourite']; // <- problem here
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE user=$user AND favid=$favid");
$matches = mysql_num_rows($query);
if($matches == 0){
?>
<img id="button" class="faver fave0 tog" src= "favscript/images/0.jpg" onclick="" width="54" height="49">
<?php
}
if ($matches == 1) {
?>
<img id="button" class="faver fave0 tog" src= "favscript/images/1.jpg" onclick="" width="54" height="49">
<?php
}
?>
</div>
<!--Favourite Button END-->
if i set $favid to the id of the article directly like: $favid = 3; it will work perfect but I can't get my head around how to do it properly with a $session variable or something that will get the article id for each button separately and only effect each button by itself.
I hope this makes sense, I am new to php and any help on how I should do this will be much appreciated.
thanks.
If you want sessions even after user logged out , simply Store login activities in separate table. like columns User ID and Session IDs. finally get the last row of the activity table.
Happy coding !
I think your query should be to fetch all the favids for a user:
$query = mysql_query("SELECT favid FROM ajaxfavourites WHERE user=$user");
while($row = mysql_fetch_assoc($result)){
$allFavIds[] = $row['favid'];
}
Now using $allFavIds array you can check for each button if its "favid" exists in this array.
<img id="button" class="faver fave0 tog" src="favscript/images/<?php echo in_array($individualFavId, $allFavIds) ? '1.jpg' : '0.jpg' ; ?>" onclick="" width="54" height="49">
Of-course the $individualFavId will be replaced by your individual favids.
Sample Code:
<img id="button" class="faver fave0 tog" src="favscript/images/<?php echo in_array(3, $allFavIds) ? '1.jpg' : '0.jpg' ; ?>" onclick="" width="54" height="49">

PHP help: Follow System in Microblogging

I'm making a site similar to Instagram. I am very new to php. I created a follow button in the user's profile.
How do you make the follow button disappear when you already followed the user?
How do you replace it with unfollow button?
// my php code for following
if (isset($_POST['addfriend'])){
$fromuser = $user;
$touser = $username;
if($fromuser == $username){
$Msg = "You cannot follow yourself<br/>";
}
else
{
$getID= mysql_query("SELECT userID FROM user WHERE username='$user'");
$get_ID_row = mysql_fetch_assoc($getID);
$ID_db = $get_ID_row['userID'];
$sql = "insert into following (userID, fromUser, toUser)
values ('$ID_db','$fromuser', '$touser')";
$result = mysql_query($sql);
$Msg= "Success! <br/>";
}
}
else{
//Do nothing
}
//my code for the follow button
<form action="<?php $user;?>" method ="POST">
<?php echo $Msg; ?>
<input type = "submit" name ="addfriend" value = "Follow"/>
</form>
On the page where you are going to show the Follow or Unfollow button, first run a MySQL query to find out if you are already following the person:
$sql = "select * from following
where userID = $user
and fromUser = $fromUser
and toUser = $toUser";
$result = mysql_query($sql);
if( $result) {
if( mysql_num_rows($result) > 0) {
// if we get here we know we are already following that person
....[see below]
Now dynamically create whichever button you need:-
if( mysql_num_rows($result) > 0) {
// if we get here we know we are already following that person
echo '<input type = "submit" name ="removefriend" value = "Un-follow"/>';
}
else
{
echo '<input type = "submit" name ="addfriend" value = "Follow"/>';
}
And on the following page where you are getting the form results, check for both buttons:
if (isset($_POST['addfriend'])) {
...[do what you already have]
}
else
if (isset($_POST['removefriend'])) {
...[do SQL to remove the record from the following table]
}
Please be aware also that as of PHP v5.5 this style of MySQL is deprecated. At some stage in the future you will have to convert your programs to the MySQLi or PDO_MySQL extensions, before they eventually discontinue support. See the PHP manual about this at eg http://php.net/manual/en/mysqlinfo.api.choosing.php.
Would be easier with OO PHP. However, if you chose procedural, let's assume we have a table of friends. Which keeps the id of each of my friends.
e.g.: Smith follows John
Then you do something like
$following = mysql_query("SELECT COUNT(*) FROM followers WHERE followerid = ".$_SESSION['id']." AND followeeid = ".$username);
Check if You follow the person already:
if($following){//$following == true
}

update database with checkbox

My database table has 2 fields: id (int) and state (enum -> 0,1).
What I need to do is to update my database (my state field) with the state of a checkbox (0 for empty, 1 for checked).
To show each of the fields in my database, I use a loop:
Loop:
<?php
foreach ( $posts_array as $module )
{
?>
<h2><?php echo $module->titre; ?></h2>
<input type="checkbox" name="chkbx_<?php echo $module->id; ?>"> id="chkbx_<?php echo $module->id; ?>" class="onoffswitch-checkbox"> On/Off <br />
<?php
}
?>
My update file:
foreach ($_GET['onoffswitch-checkbox'] as $id => $state)
{
// $_GET['onoffswitch-checkbox'] = class for all my checkboxed
// $id = my database row id
// $state = on/off
$query = mysql_query("UPDATE records SET id='$id' WHERE state='$state'", $conn) or die (mysql_error($conn));
$id++;
}
Where I need help is the AJAX part of the code. I'm guessing it looks something like this, but it doesn't seem to work:
AJAX
$(document).ready(function() {
$("onoffswitch-checkbox").click(function() {
var id = $(this).attr('id');
$("#state_span").load("module_update.php?"+id);
}
}
I've been looking around, seen a few examples where the we could do so with a submit button, but none where the information is automatically recorded when clicking the checkbox.
Try this:
AJAX
$(document).ready(function() {
$(".onoffswitch-checkbox").click(function() {
var id = this.id; //changed here also, just because jQuery is not needed here
var state = this.checked ? 1 : 0;
$("#state_span").load("module_update.php?id="+id+"&state="+state);
}
}
Changed 3 things:
added a dot in $("onoffswitch-checkbox") so its now $(".onoffswitch-checkbox")
added id= after module_update.php? and before id value.
since you need state also I added that also with a & to separate the values for $_GET in php to separate them
PHP
I don't know what you mean with $_GET['onoffswitch-checkbox'] in the php, maybe a mistake? My suggestion does not need it anyway, neither does your mysql query.
Since you will be only clicking one at a time I see no need for the foreach loop in php, so you could do this:
$id = $_GET['id'];
$state= $_GET['state'];
// $_GET['onoffswitch-checkbox'] ?? I don't think you need this...
// $id = my database row id
// $state = on/off
$query = mysql_query("UPDATE records SET id='$id' WHERE state='$state'", $conn) or die (mysql_error($conn));
$id++;

submit one or another query

I'm continuing to hack away at my newbie php/mySQL 'Invoicer' app.
I now have a form page in which I want to run one of two queries - either an INSERT or an UPDATE, depending on whether an ID is present. When present,
the ID is used to retrieve the record and pre-populate the form accordingly, which I have working. My problem now is that my conditional bits are
obviously not right because in either case when submitting the form the INSERT query is run, can't get the UPDATE to run, and I've exhausted my
understanding (and guess-ology).
I'd love to know why this ain't working, even if it's not the best approach, and I'm definitely open to suggestions to move the queries to a process.php,
etc. I'm also wondering if I should use 'if(isset($_GET['ID'])' to simply include one block or the other.
Many thanks in advance for any help or suggestions. (p.s. my intention is to overhaul for best practices/security once I've got the broad strokes wired up)
cheers, s
<?php
// CASE I: 'EDIT RECORD':
// If there's an ID ...
if (isset($_GET['ID']) && is_numeric($_GET['ID'])) {
$id = $_GET['ID'];
echo "<p class=\"status\"><strong>ID IS SET ... ergo we're editing/UPDATING an existing record</strong></p>";
// ... retrieve the record ....
$query = sprintf("SELECT * FROM Invoices WHERE ID = %s", $id);
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
// ... assign variables to pre-populate the form
$id = $row['ID'];
$invNumber = $row['invNumber'];
$invDate = $row['invDate'];
// [ snip: more variables > field data ]
// on submit: get the form values ...
// no worky: if (isset($_GET['ID']) && isset($_POST['submit'])) {
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
// ... and UPDATE the db:
$qUpdate = "UPDATE Invoices SET invNumber='$invNumber', invDate='$invDate', projNumber='$projNumber', client='$client', task='$task', issueDate='$issueDate', subTotal='$subTotal', tax='$tax', invTotal='$invTotal', datePaid1='$datePaid1', datePaid2='$datePaid2', comments='$comments' WHERE ID='3'";
$result = mysql_query($qUpdate) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: RECORD UPDATED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE I: ID present
// CASE II: 'NEW RECORD'; query = INSERT
elseif (empty($_GET['ID'])) {
echo "<p class=\"status\"><strong>No ID ... ergo we're INSERTING a new record:</strong></p>";
// on submit: get the form values ...
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
$qInsert = "INSERT INTO Invoices (invNumber,invDate,projNumber,client,task,issueDate,subTotal,tax,invTotal,datePaid1,datePaid2,comments)
VALUES('$invNumber','$invDate','$projNumber','$client','$task','$issueDate','$subTotal','$tax','$invTotal','$datePaid1','$datePaid2','$comments')";
$result = mysql_query($qInsert) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: NEW RECORD INSERTED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE II: No ID present
?>
and:
<form id="invoiceData" method="post" action="/html/form.php">
When you submit the form, you need to include the ID again, otherwise it is silently dropped off since you are posting to the hard-coded value /html/form.php (with ID removed). This will cause the empty($_GET['ID']) part to match and run, causing the INSERT. You can simply include the ID value back into the action of every form post like this:
<form
id="invoiceData"
method="post"
action="/html/form.php?ID=<?php echo $_GET['ID']; ?>"
>
This should work in both the cases of the UPDATE and the INSERT, because if there was no ID to begin with, this will render as /html/form.php?ID=, which will match the case of ID being empty, I believe. You may want to test this logic out for sure.
Hope this helps!
$_GET[ID] will be set if you pass it as a URL parameter. So if you change your <form> action to
<form id="invoiceData" method="post" action="/html/form.php?ID=12">
Where 12 is whatever ID you want, you should be getting the results you're wanting -- as long as you do have a <input type="hidden" name="submit" value="1" /> (value can be whatever) in your form somewhere as well.

Categories