I have a table with the following fields: wall_posts, group_id, id, and user_id.
Wall_posts is user entries, group_id is imported from another table and is just a unique group id, id is just a simple counter, and user_id gets the user id from the session.
My code gets rid of all the wall_posts if you press the delete button by comparing the user id to the user in session. I'm trying to find a way to delete individual posts and not all the posts by the user.
Here is the code:
if (isset($_POST['delete'])) {
$current_user = $_SESSION['user_id'];
$result = mysql_query("SELECT * FROM group_posts");
while ($user_id = mysql_fetch_array($result)) {
$id = $user_id['user_id'];
}
if ($current_user == $id) {
mysql_query("DELETE FROM group_posts WHERE $current_user = $id") or die(mysql_error());
}
}
How can I bound the delete button to individual posts instead of deleting all the posts made by the user currently in session?
Your SQL query above doesn't make sense - the WHERE statement should be in the form WHERE column_name = value.
Assuming id is the primary key for group_posts, as you're displaying posts, create a link for each post created by the author, e.g. Delete This Post for post with id 3. Then you'd do a query like this:
DELETE FROM group_posts WHERE id = postIdValueHere
Using the code pattern you have above:
if (isset($_POST['delete']) && $_POST['delete'] > 0) {
$current_user = $_SESSION['user_id'];
$post_id = (int) $_POST['delete'];
if ($current_user == $id) {
mysql_query("DELETE FROM group_posts WHERE id = $post_id AND user_id = $id") or die(mysql_error());
}
That query ensures that only posts with a given ID, created by the current author, can be deleted.
Does that answer your question?
Once you get more comfortable with SQL, you might also want to look into using prepared statements with mysqli or PDO. That will help your code clean and secure.
I'm assuming your delete buttons are simple links. Your links must contain all the information to delete a post. One way would be to pass a post id as a GET variable (e.g. link="myurl.com/posts/delete?id=#").
Your script would then at first make sure the current user is allowed to delete the post. For example:
$user_id = $_SESSION['user_id'];
$post_id = (int) $_GET['id'];
if(canDelete($user_id, $post_id))
{
// assuming post_id is unique for every post
$sql = sprintf("DELETE FROM group_posts WHERE id = %d", $post_id);
mysql_query($sql);
}
Of course, you'd have to implement canDelete($user_id) yourself.
By the way, "DELETE FROM group_posts WHERE $current_user = $id" always deletes every record in your table. At first you're comparing if $current_user equals $id and if they do happen to be equal, your query would look something like WHERE 1 = 1. I think you mean "DELETE FROM group_posts WHERE user_id = '$id'"
EDIT: It seems you want to use ajax for deleting your posts. I recommend using jQuery or any other proper javascript framework as it saves you time. Here is a link from the jQuery documentation describing how to make an ajax call to the server and a similar question to help you understand better.
Related
So I have the following JSON:
[{"username":"User1","password":"Password"},
{"username":"User5","password":"passWord"},]
Generated from:
<?php $username = $_POST["username"]; ?><br>
<?php $password = $_POST["password"]; ?><br>
<?php
$currentData = file_get_contents('UserJSON.txt');
$array_data = json_decode($currentData, true);
$extra = array(
'username' => $username,
'password' => $password
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('UserJSON.txt',$final_data)) {
print("working");
}
?>
After the user logs in they have the ability to make a post, how would I go about creating a post array for each user and how would I add to it dynamically ?
This is all I have and I have tried many different ways, but cant seem to figure out how to make it dynamic.
<?php
$urlText = $_REQUEST["urlText"];
$currentData = file_get_contents('UserJSON.txt');
$array_data = json_decode($currentData, true);
//for loop
$array_data[i]['Posts'] = $urlText;
//end for loop
$final_data = json_encode($array_data);
if(file_put_contents('UserJSON.txt',$final_data)) {
}
?>
In this situation though, posts is not an array, it just simply overwrites what already there.
[{"username":"User1","password":"Password","Posts:{"This is a post"}},
{"username":"User5","password":"passWord"},"Posts:{"This is a post2"}}]
Therefore, how do I add a posts array and how do I add to it dynamically ? I have not been able to figure such a simple thing out for a very long time
File get contents from like "posts/useridhere.txt", or allposts.txt
You will also need to use unique post IDs.
Json decode your posts JSON
Add post content to array
Json encode array
Write new json to the users post file
Ultimately I do not recommend this. If you want a paid internship I'll teach you how to use MySQL. We make websites :) but if you want to do it this way, you'll need a JSON file to store unique post IDs or even store all posts in one file. The problem is that you'll have a limit of how many posts can be stored in that single JSON array. I hope this answer is enough to help you. It's all the steps needed
$posts = file_get_contents($postsFile);
$posts = json_decode($posts);
$newPost = array(
"user"=>$user,
"postTitle"=>$string,
"text"=>$content
);
$posts[] = $newPost;
$newPostID = count($posts); // will not work properly (for linking posts) once you delete a post - you need unique post ids generated!
$posts = json_encode($posts);
// Overwrite your posts file with $posts. It will have all posts you need :)
Let's say there is a site that has a button that uses javascript to increase the value of the javascript variable "javascriptx" by +1 each time it is clicked. UserA (id=1 on the MySql table) logs in to the website and presses the button 3 times, so javascriptx = 2.
The next time UserA logs in, I want javascriptx to still equal 2 (assuming the button hasn't been pressed any more times), so I need to convert that javascript variable to a php variable and send it to MySql. As far as I understand, this is the correct way to do that:
Add the following to the javascript code:
var xhr = new XMLHttpRequest();
xhr.open("get","/path/to/php/page.php?phpx=javascriptx");
xhr.send();
Now, the php variable "phpx" has the same value as the javascript variable "javascriptx"
Then, that php variable needs to be sent to the MySql table, so the following is added to the php code:
($_GET['phpx'])
From here, I get lost. Where does phpx get stored in the MySql table? More specifically, how does it know to put this in the same row as user with id=1?
You should connect to the MySQL database using something like mysqli:
$database = new mysqli(db_host, db_username, db_pass, db_name);
Then you can make queries to your database with prepared statements to read/write data. In this rough example, the data will return a JSON response to your web application or wherever you make the request from:
//set user id from post variable
$uid = $_POST['uid'];
//store sql query as string
$sql = "SELECT phpx FROM users WHERE uid=?";
//initiate new prepared statement
$stmt = $database->stmt_init();
$stmt->prepare($sql);
//pass uid var to statement
$stmt->bind_param('s', $uid);
//store result as var
$stmt->bind_result($phpx);
$stmt->execute();
//catch errors
if ($stmt->errno) {
die("error: " . $stmt->error);
} else {
//store result and send as response
$stmt->store_result();
if($stmt->num_rows){
while($stmt->fetch()){
$phpx_packet[] = array(
"uid" => $uid,
"phpx" => $phpx
);
}
echo json_encode($phpx_packet);
}
}
//close statement
$stmt->close();
This is my first time on here so I'm sorry if I'm not quite up to snuff with all of you.
In the process of learning AJAX so I'm brand new, but need to get a page done for our staff website.
I have a page (php) which builds a list through a mysql query of all patients. I have absolutely no problem with this. However, I'm stuck on this part.
When a user clicks a specific row (aka Patient Name), I want it to pull up the details of that patient associated with it in our mysql database on the right-hand side so the page doesn't have to refresh and they aren't directed to any other pages.
I have seen examples like this when it came to customers, like you click the name and a div appears to the right containing email, phone, etc. etc.
Does anyone have any good starting points? I have searched as far as I can, and I'm beginning to think I'm not using the right language when searching for my answer.
Thanks ahead of time... Matt
Use jQuery.
First you need to make a web service on your server. The web service will accept a, let's say, POST parameter which will be either patient name or the patient ID. Based on this id/name you will query your MySQL database, fetch all the details and return as json.
On the front end, you can use jQuery.post(). You will need to pass the appropriate URL and the data. In return, you will get JSON data. In the success callback method of jQuery.post/$.post you can create a div on the right and display those data.
If you are going to return the data in json format, you can also just use $.postJSON()
Please make sure to set the appropriate headers in your PHP webservice. These two are probably the most important
Content-Type: application/json // if you are gonna return the data in JSON format
Access-Control-Allow-Origin: * // to let the browser pass the data to the DOM model. This is to allow CORS (Cross Origin Resouce Sharing)
SAMPLE:
example.php
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
if (isset($_POST['patientID'])) {
$patientID = $_POST['patientID'];
$data = array();
// Enter the appropriate details below
$mysqli = new mysqli("host", "username", "password", "db_name");
/* check connection */
if ($mysqli->connect_errno > 0) {
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
$statement = $mysqli->prepare("SELECT * FROM `patients` WHERE `patientID` = ? LIMIT 1");
$statement->bind_param('i', $patientID);
$statement->execute();
// You need to write a variable for each field that you are fetching from the select statement in the correct order
// For eg., if your select statement was like this:
// SELECT name, COUNT(*) as count, id, email FROM patients
// Your bind_result would look like this:
// $statement->bind_result($name, $count, $id, $email);
// PS: The variable name doesn't have to be the same as the column name
$statement->bind_result($id, $name, $email, $phone);
while ($statement->fetch()) {
$data["id"] = $id;
$data["name"] = $name;
$data["email"] = $email;
$data["phone"] = $phone;
}
$statement->free_result();
echo json_encode($data);
}
example.html
Patient #123
example.js
function getPatientData(element) {
var patientID = $(element).attr("id");
$.post("example.php", {"patientID": patientID}, function (data) {
// display the data in appropriate div
}, 'json');
return false;
}
You should do an jquery ajax call on element click
$('.patientClass').on('click', function() {
var patientid = $(this).attr('id');
// attr('id') should be the patients id
$.ajax({
url: "getPatientDetailsURL.php",
type: "post",
data: {
id: patientid
},
success: function(response) {
// create div with response details or append parsed json to existing div
}
});
)}
And on the backend get the patiend id with (int)$_POST['id']
Also you on the backend you can set the page to respond only to ajax calls like this:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//code here
} else {
// not ajax call
}
I'm new with questions and generally with "Stack Overflow", so forgive me if it is not formatted well.
So, I have problem with transferring some informations from one page to another. It is a value of <a> tag from an php while loop.
At the moment I have something like this:
$query = mysql_query("SELECT DISTINCT `a`.`id`,`o`.`first_name` , `o`.`last_name` , `a`.`name` FROM `owner` AS `o` , `animal` AS `a` WHERE `o`.`id` = `a`.`fk_current_owner` AND `o`.`fk_user` = '".$_SESSION['user_id']."'");
while($row = mysql_fetch_assoc($query)){
$pet_id = $row['id'];
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$pet_name = $row['name'];
echo 'Owner: <strong>'.$first_name.' '.$last_name.'</strong> ';
echo 'Pet: <strong>'.$pet_name.'</strong><br>';
}
So you can assume that this will display names of pets that logged user got.
So I linked their names and I need to get ID of selected name on another page so I can display details of pet on page viewPet.php.
You can also send the pet id along as a GET parameter with the link.
echo ''.$pet_name.'';
On the viewPet.php page you'd access it by $_GET['id']
you can put the link in a cookie:
setcookie(name, value, expire, path, domain);
that is the code to set the cookie and then to receive the cookie you can do $_COOKIE['name'];
or you can do a session.
session_start();
$_SESSION['name']=value;
I'm trying to write a registration form, and when the user press the "submit" button, I want to check if the username already exists - and if so, to show a pop-up window that says "user name already exists - please change it".
when the user closes that pop-up window using Javascript - I want the rest of the fields that the user inserts to stay in their place (I mean, only the username will be deleted - but the first name for example, will stay)
here's the code I wrote:
$con=mysqli_connect("localhost","root","","shnitzale");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$check="SELECT count (username) as num FROM registered_clients WHERE username=$_GET[User]";
if (!mysqli_query($con, $check))
{
echo "Username already exist";
}
else
{
$sql="INSERT INTO registered_clients (Username, Password, First_name, Last_name,
Day, Month, Year, Gender, Address, City, Phone_Number1, Phone_number2, Email)
VALUES
('$_GET[User]','$_GET[Password]','$_GET[Fname]','$_GET[Lname]','$_GET[Day]',"
. "'$_GET[Month]','$_GET[Year]','$_GET[gender]','$_GET[Address]','$_GET[City]',"
. "'$_GET[Phone1]','$_GET[Phone2]','$_GET[Email]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Thank you $_GET[Fname] $_GET[Lname]";
}
mysqli_close($con);
all of this is in a seperate php file that I go to after I press the "submit" button,
I understand that I need to check the username validation before I get to this page, but I don't really know how...
Thank you!
You either need AJAX http://www.w3schools.com/ajax/ and check, if the username is available without loading another page or you can set the register form's action to the register page and insert all valid form data again.
Don't forget to sanitize your user data before!
Your current username check isn't working due to this:
if (!mysqli_query($con, $check))
{
echo "Username already exist";
}
This will never occur. Your current query will always return a valid result, even if no usernames are found. num will simply be 0.
Here's one way to do it:
$username = mysqli_real_escape_string($con, $_GET['User']); // Do some minimal sanitization at least!
$check = "SELECT username FROM registered_clients WHERE username='$username'";
$result = mysqli_query($con, $check);
if(mysqli_num_rows($result)) {
echo "Username already exists";
}
This way you are pulling the actual usernames found, and counting them. Alternatively you could still use your count (username) as num query, but then you'd have to fetch the results of the query and look at the value of num.
Note that your INSERT query is still wide open to SQL injection. You need to sanitize all of those $_GET parameters before using them in your query.
If you want to do this with ajax: Create a seperate page (for now ill call it) usernamecheck.php
/*
$database_connection = database connection and stuff
Also, does your table have a primary key 'id'? I'd highly recommend it.
*/
$username = mysqli_real_escape_string($database_connection, $_GET['username']; // Use $_GET or $_POST depending on the AJAX request.
if (strlen($username) > 3){ // Only check if the username string is bigger than 4 characters. No point in checking an empty username.
$UserCheck = mysqli_query("SELECT id FROM registered_clients WHERE username = '$username' LIMIT 1");
if (mysqli_num_rows($UserCheck) > 0){
die('<p style="color: red;">The username '.$username.' is already taken.</p>');
} else {
die('<p style="color: green;">The username '.$username.' is available.</p>');
}
}
If you target your AJAX request to usernamecheck.php?username=superman and display the output of the page directly under the username field, the user would get a live update from the server.
You can also change the output of the script to a 1 or 0, so that you can pick it up in javascript.