This may be a noob question. I have a table called user_thoughts. I am making a Delete button, which on click, will delete the "thought". I have two rows in my table:
Row 1:
id - 106
message - This is message 1
added_by - AliceP
Row 2:
id - 107
message - This is message 2
added_by - AliceP
Here is what I have so far (del_post.php):
<?php include("connect.php"); ?>
<?php
session_start();
if (!isset($_SESSION["user_login"])) {
header("Location: index.php");
} else {
$username = $_SESSION["user_login"];
}
/**************************/
// get id of all posts by logged in user
$get_id = "SELECT id FROM user_thoughts WHERE added_by ='$username'";
$run_query = mysqli_query($connect, $get_id);
while ($row_query = mysqli_fetch_array($run_query)) {
$tho_id = $row_query['id'];
$comment_assigned_to_id = ['message'];
$delete_query = mysqli_query ($connect, "DELETE FROM user_thoughts WHERE id = '$tho_id' '");
header ("Location: /profile_page/$username");
}
?>
If I want to delete the thought This is message 1, I click delete, and it will delete all the messages by AliceP. How can I get the id of the current message, and then delete just that message?
Step 1:
At the bottom of your script, create a form, and within the form (using results of the SELECT statement in a loop):
display the row
create a button with the name="delete" and the value=id (id of the row)
Step 2:
At the top of your script, add the code that will (when the form is submitted) extract the value of $_GET["delete"] or $_POST["delete"] (depending on whether you are using GET or POST form method).
If there is no value, skip the deleting portion.
Create & execute the delete statement based on the extracted value of the row id.
Related
With my code here, if the user checks a check box beside one of the names
the name gets saved into my review_shared table.
I'm trying to have my code so that if a box is unchecked, the name will be REMOVED from the review_shared table.
Does you know how I can do this, or where I should start ? So, If Paul Thompson and/or Dan Frain are unchecked, they will be removed from my review_shared table.
<?php
//here we want to save the checked contacts to the review_shared table ; that is,
//who the user wants to share reviews with
if(!empty($_POST['check_contacts'])) {
foreach($_POST['check_contacts'] as $check) {
//$check="";
//if the contact in review_shared is already checked, we don't want to save it multiple times
$already_checked = "SELECT * from review_shared WHERE user_id = '$user_id' AND contact_id = '$check' AND review_id = " .$_GET['id'];
$already_checked_result=mysqli_query($con,$already_checked);
$num_rows = mysqli_num_rows($already_checked_result);
if($num_rows >= 1) {
echo "This is already a contact";
}
else if ($num_rows < 1) {
//$_GET['id'] is the current review for which contacts are being edited, we are checking a contact to share that review with
$insert_review_shared_command = "INSERT INTO review_shared VALUES(NULL," .$_GET['id']. ", '$user_id','$check')";
//we want to save the checked contacts into the review_shared table
$insert_into_review_shared_table = mysqli_query($con,$insert_review_shared_command);
}
}
}
$con->close();
?>
The unique way to achieve what you need is to
delete all the entries
insert the checked options
While saving your form data.
To delete all the previous entries do something like this
$sql = "DELETE FROM review_shared WHERE your-conditions";
This because when you are posting checkboxes, you will receive ONLY the checked ones on the server side. Those ones are the data you need to store.
Thanks to Simone Cabrino above, I simply added this into my code :
$already_checked = "DELETE from review_shared WHERE user_id = '$user_id' AND review_id = " .$_GET['id'];
mysqli_query($con,$already_checked);
With my code here, if the user checks a check box beside one of the names
the name gets saved into my review_shared table, when the user clicks 'Save'.
But I want a checked value to be only saved
once into the table, the way it is now it gets saved multiple times - I mean if the user comes back to this page and the name is checked and the user clicks 'Save' again.
What can I add to the code for this to happen, so it will only be saved once in my review_shared table ? At present it looks like this, which saves it multiple times :
if(!empty($_POST['check_contacts'])) {
foreach($_POST['check_contacts'] as $check) {
//$_GET['id'] is the current review for which contacts are being edited, we are checking a contact to share that review with
$insert_review_shared_command = "INSERT INTO review_shared VALUES(NULL," .$_GET['id']. ", '$user_id','$check')";
//we want to save the checked contacts into the review_shared table
$insert_into_review_shared_table = mysqli_query($con,$insert_review_shared_command);
}
//go to the main page when changes have been saved
header('Location:volleyLogin.php');
}
$con->close();
I thought adding code like this into the above would help, but it doesn't, really :
if(!empty($_POST['check_contacts'])) {
//************************* added this in **************
$check="";
//if the contact in review_shared is already checked, we don't want to save it multiple times
$already_checked = "SELECT * from review_shared WHERE user_id = '$user_id' AND contact_id = '$check' AND review_id = " .$_GET['id'];
$already_checked_result=mysqli_query($con,$already_checked);
$num_rows = mysqli_num_rows($already_checked_result);
if($num_rows >= 1) {
echo "This is already a contact";
break;
}
//*******************************************************
foreach($_POST['check_contacts'] as $check) {
//$_GET['id'] is the current review for which contacts are being edited, we are checking a contact to share that review with
$insert_review_shared_command = "INSERT INTO review_shared VALUES(NULL," .$_GET['id']. ", '$user_id','$check')";
//we want to save the checked contacts into the review_shared table
$insert_into_review_shared_table = mysqli_query($con,$insert_review_shared_command);
}
//go to the main page when changes have been saved
header('Location:volleyLogin.php');
}
$con->close();
break; is used to come out of a loop(for, foreach,while and do-while) and switch structure, not from if block. You have to create an else block corresponding to that if block, and put your entire foreach loop there.
// your code
if($num_rows) {
echo "This is already a contact";
}else{
foreach($_POST['check_contacts'] as $check) {
//$_GET['id'] is the current review for which contacts are being edited, we are checking a contact to share that review with
$insert_review_shared_command = "INSERT INTO review_shared VALUES(NULL," .$_GET['id']. ", '$user_id','$check')";
//we want to save the checked contacts into the review_shared table
$insert_into_review_shared_table = mysqli_query($con,$insert_review_shared_command);
}
}
// your code
Here's the relevant reference:
http://php.net/manual/en/control-structures.break.php
I have a form that submits super basic information, just a new name (the name gets assigned a unique id). What I am trying to make happen is when the user submits the name it gets submitted into the database and they get redirected to a new page card.php where they can add more specific information. However the unique id associated with the row that was just submitted needs to follow in the URL (id=$id)
$query = "INSERT INTO name VALUES(NULL, '$name')";
mysqli_query($conn, $query);
$query2 = "SELECT * FROM name ORDER BY id DESC LIMIT 1";
$result = mysqli_query($conn, $query2);
while($row = mysqli_fetch_array($result)) {
$id = $row['id'];
}
header("Location: http://localhost/card.php?id=$id");
Process
addName.php -> user submits new name -> add to database -> redirect to card.php WITH unique id value of name that is just submitted
1.) Is there a way to retain the id of the row just submitted? In the fluke chance 2 or more people submit at the same time the second query of getting the last row inserted into the database will return the wrong row id
2). Having a while loop return 1 piece of info seems like a shitty way to do things, this might be the most basic of shit but i cant seem to return the 1 piece of data without doing this
Try using mysqli_insert_id which returns the AUTO_INCREMENT ID generated from the previous INSERT operation.
$query = "INSERT INTO name VALUES(NULL, '$name')";
mysqli_query($conn, $query);
$id = mysqli_insert_id();
header("Location: http://localhost/card.php?id=$id");
Reference: http://us1.php.net/manual/en/function.mysql-insert-id.php
You could use the mysqli function to retrieve the last inserted id (check mysqli_insert_id as suggested in a comment), but I wouldn't recommend you using the user id in the URL, people can try to get in, using other ids
also you can use the php function to generate a custom is check out: uniqid
This is the code for the user to post the post.
if(islet($_POST['submit'])) {
$name = $_POST['name'];
$keywords = $_POST['keywords'];
$description = $_POST['description'];
if(islet($_GET['user_id'])) {
$_SESSION['user_id'] = $_GET['user_id'];
} //Then I just have a inset into statement for my database with these 4 variables.
}
I have a web form that creates a post by the user. I now want to make the user able to go back to a page dedicated to that post for them to edit, add on to etc.
Here is the high level solution:
You need to create a page that expects a post_id as a parameter of the query string. That page will be accessed like this: http://yoursite.com/show-post.php?post_id=136
In PHP, retrieve that post_id: $_GET['post_id']
From that post id, pull from the DB the information associated to that id. Something like SELECT * FROM post WHERE post_id = $_GET['post_id'].
Then display the post using the information returned by the SQL query.
If you want to show a list of posts from the current user, create another page http://yoursite.com/my-posts.php.
From that page, write a SQL query based on the current user id: SELECT * FROM post WHERE user_id = $_SESSION['user_id'] (assuming you have a user_id in the post table, and the user has authenticated and his id was stored in the session).
That will fetch you a list of posts, loop through them to get their details.
Please note that you should escape the parameter passed in the query string. There are many ways to do this so I won't go into it here.
EDIT:
This is how you generate the links:
<?php foreach ($mysql_result as $row) { ?>
link
<?php } ?>
Then, in edit-post.php, you can get the post_id by doing $postId = $_GET['post_id'];, and then use it in the query to fetch ALL the information about that one particular post.
Make sure you have a unique ID column in your database - call it 'postid', and set it to autoincrement with every new entry.
That way you'll be sure to have a unique identifier for each entry you insert in to the database.
You then need to retrieve a list of items in the database, including the postid, and for each row in the database provide a link to display it.
If a postid is selected in the url, then display information for that post. If it isn't, then show a list:
<?
$dbh = new PDO('mysql:host=localhost;dbname=databasename;charset=utf8', 'username', 'password');
///No post id selected, display a list of everything
if(!$_GET['postid']) {
print "You're listing all the rows in the database<br/>";
$query = $dbh->prepare("SELECT `postid`,`name` FROM `table` ORDER by postid ASC");
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
print "".$row['name']."<br/>";
}
} else { //A post ID is selected
$postid = $_GET['postid'];
Print "Select from the database where postid = ".$postid;
$query = $dbh->prepare("SELECT `postid`, `name`, `keywords`, `description` FROM `table` WHERE `postid` = '$postid' LIMIT 1");
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$name = $row['name'];
$keywords = $row['keywords'];
$description = $row['description'];
print 'Displaying details for '.$name.': '.$keywords.', '.$description.' - create edit links here... <br/><br/>';
}
} //End post id is selected
?>
how can i update to database status = 1 where id =$id using an update statement after a login for example or a separate page
please any one how the string would look like?
this is for a member status script im trying to make it so online members can have there own page
this is just the viewing part and the updating part next
mysql_select_db("messages") or die(mysql_error());
$data = mysql_query("SELECT on_status FROM users WHERE id='$user_id'")
or die(mysql_error());
echo "<table border cellpadding=3 bgcolor=\"00FF00\">";
while($info = mysql_fetch_array( $data ))
{
echo "<tr>";
echo "<th>User:</th> <td>".$info['user_name'] . "</td> ";
echo "<th>Status:</th> <td>".$info['on_status'] . " </td></tr>";
}
echo "</table>";
?>
<p><br>
Go Back<p>
Add a field called status in users table. where users table containing all data of user.
UPDATE status to online when user login.. this code will be placed after validating the username and password..
// Eg: When you starting a session for the user write this update
When a user trying to logout UPDATE status to offline .. this code will be placed beside the session_destroy() statement
Try this update statement:
"UPDATE `users` SET `on_status` = 1 WHERE `id` = '$user_id'";
Though, if I may suggest this: Keep a timestamp of the last activity. That way, if the page hasn't been refreshed for more than 5 minutes (or longer), you can display the user as 'offline', even if the user hasn't hit the Logout button.