How to restrict user from updating same row twice+ - php

I'm trying to create a system similar to a Facebook LIKE button. I want to allow a user to like a picture, but only let them like it once. After they have liked it, they should only be able to unlike it.
My current code is:
<?php
$id = $_GET["picID"];
include 'db.php';
$colID = str_replace('_', ' ', $_GET['picID']);
$colID = mysql_escape_string($picID);
$sql = "SELECT * FROM picture WHERE id = $id";
$result = mysql_query($sql) or die (mysql_error()."<br/>".sql);
$row = mysql_fetch_array($result);
$update = "UPDATE picture SET likes=likes+1 WHERE id='$id'";
mysql_query($update) or die (mysql_error()."<br/>".update);
echo "Thank you";
?>
Currently I use a hyperlink to trigger the 'Like' action:
<a href='like.php?colID=$row[id]'>Like</a>
At the end I'd like to change this to AJAX so the user can simply click Like (as on Facebook) without any page change. I'm still reading up on how to do this. Is there a particular name for this task? Or can someone show me show I could do this?
EDIT:
The user needs to be logged in to be able to like a picture. I have two unlinked tables, User and Pictures. Currently a user can just keep clicking 'Like' and it adds 1 to the like column.

One method would be to create a table that contains columns for picture IDs and user IDs to show that a person has liked a particular picture. If a user ID is listed in the table with a picture ID, then you should not allow them to like the picture since they have already liked it. You can perform this check with a query to the database that will return a count of a 1 or a 0.

Make a string column in your database to indicate who liked the picture.
If the user is logged in (so can vote), search his name in the string by exploding it and looping it. Then remove his name from the string or add it.
Note that you could also save the array directly to the database using serialization: http://php.net/manual/en/function.serialize.php
For a fast loading, you could have an other column with the count of names of the first columns.

Related

Automatically edit a php table

I have a coins table in phpMyAdmin and I need it to be automatically updated when a user completes a purchase via PayPal. The way it is setup is that PayPal will automatically redirect them to a link I choose.
So, how can I run a script that takes the parameters from the URL and adds a new record to the table?
Thank you for all your help.
So that link would need to be a page called something like payment_success.php
On that page you would need to have a script that looks like this:
<?php
include 'credentials.php'; /*this is a file that will contain your database connection info
Then here you will establish the connection and enter the data into the desired table*/
$var1 = 'some information collected from paypal that you want to update';
$id = 'some identifiable information about your user that can connect them to the correct row in your table';
I won't hold your hand through all this but the SQL query you would need would be:
UPDATE table_name SET column_1 = '$var1' WHERE ID = '$id'
Set the confirmation PayPal link to increment the number of coins value in the MySQL table for the particular user....!!!
I hope that will work out..... If I could get a idea of your table or some more info, I could give you a clear idea about that.

Making like buttons for multiple images

I'm pretty new to php and MySql and am trying to make an image uploading website where the users upload the images. I'm storing all the images in a directory and storing the path to the images in my database.
Since I shall not know the number of images that have been uploaded, I am using a while loop to display them.
Now, I need to create "like" buttons for every image. Although I am able to create like buttons for every image, I am not able to understand how php will know the like button for which image has been pressed and once a like button has been pressed, how I should increment the "number of likes" value for that particular image not just in the database but also on the webpage itself.
I understand that I shall have to use php, MySql and Ajax for this. It could be great if you could help me with the code. Thanks a lot! :)
Here is the code that I have been able to write so far(in the code, I have not shown the creation of the like button for I am totally confused about it....the code only contains the displaying of images..it could be great if you could help me out with how to proceed with the creation of the like button and further of how to update the database and print the number of likes on the webpage without refreshing the whole page) :
$sql= "SELECT * FROM imagestable ";
$result=mysqli_query($conn,$sql);
//printing all the images one by one
while($row=mysqli_fetch_assoc($result)){
$imagelocation=$row['imageDestination'];
$imagetitle=$row['imagetitle'];
$uploader=$row['uploader'];
echo '<h1>'.$imagetitle.'</h1>
<img src="'.$imagelocation.'" style="width:600px;height:100%;">
<h1>Uploaded by:'.$uploader.'</h1>
<br>
';
}
Thanks!
You should probably have an Id column in your database to uniquely identify each image (they are usually automatically generated and incremented without you having to do anything, though I havent used MySql in ages).
$sql= "SELECT * FROM imagestable ";
$result=mysqli_query($conn,$sql);
//printing all the images one by one
while($row=mysqli_fetch_assoc($result)){
$imagid = $row['imageid'];
$imagelocation=$row['imageDestination'];
$imagetitle=$row['imagetitle'];
$uploader=$row['uploader'];
echo '<h1>'.$imagetitle.'</h1>
<img src="'.$imagelocation.'" style="width:600px;height:100%;">
<h1>Uploaded by:'.$uploader.'</h1>
<br>
// Here you add the button with the id from the database to identify the image
// Here likeimage(id) is assumed to be a javascript function that somehow updates
// the server that someone clicked the like button (and possibly updates the html DOM
// to the new number of likes.
<input type="button" onclick="likeimage($imageid);" />
';
}
If you don't have autoincrement field then please run this query, then 2 new fields will be added in your imagestable.
ALTER TABLE imagestable add column `id` int(11) unsigned NOT NULL AUTO_INCREMENT,add column totlikes INT(11) default 0;
Form where you want to like this image just pass the id (see auto increment field in ALTER script);
NOTE :- I have used POST method here.
$id=$_POST['id'];
mysqli_query($conn, "UPDATE imagestable set totlikes=totlikes+1 where id=$id");

Allow user that created entry to modify it only

I have been googling for some time now with out success primarily because the way i am asking is most probably the wrong way.
What i want to know
I have made some PHP scripts that allow users to add data to a table (In a MYSQL datanase) and its displayed on a website, now i am working on the ability to edit and delete the entry however the script i have allow anyone to do this to anyone's entry's.
Now i don't know if there are PHP or Mysql functions that help with this, like i said my goggling has been in vain. So if i could be pointed to a webpage that has this information or better yet an example syntax chunk that will only allow the user that created the entry to modify the entry.
I am assuming there is some type of while or if statement to achieve this.
Example scenario
A user comes along adds an entry the entry is given an id can the user be linked to that id so only he can edit it ?.
Note
I am adding PHP to a word press site so as for the users login information a word press widget is controlling that however i can see the entries are still put in a database field when I'm strolling threw the databases.
What i am asking
Do you know of a webpage/example syntax or tutorial that will show me what i need to know or if ya got enough time explain it to me :).
Thanks
Ben
Update the new entry with the current user's id, where $entry_id is the ID of the new entry
$current_user_id = get_current_user_id(); // current user logged into WordPress
mysql_query("UPDATE `table` SET `user_id`='$current_user_id' WHERE `id`='$entry_id'") or die(mysql_error());
UPDATE: You could also insert the entry with the user_id at the same time with the rest of the data.
mysql_query("INSERT INTO `table` ([other column names], `user_id`) VALUES ([other values], '$current_user_id')") or die(mysql_error());
Check if the current user ID is equivalent to the allowed edit user ID in your database.
$query = mysql_query("SELECT * FROM `table` WHERE `id`='$entry_id' LIMIT 1") or die(mysql_error());
$data = mysql_fetch_array($query);
$allowed_user_edit_id = $data['user_id']; // user id who is allowed to edit
$current_user_id = get_current_user_id(); // current user logged into WordPress
if ($current_user_id == $allowed_user_edit_id) {
// Your code for editing the entry
}

pull specific table row column data to output in html using php

how do i pull data from my database table and put that data into a readonly textinput in a form for a user to see.
<input readonly type="text" name="em1" id="em1"/>
for this specific field i want to pull the data from a column called wmyt000 in the row of the currently logged in user using a $username variable with session that i created to get the current logged in users username in a table called cash_flow_plan
im using mysql and php
i havnt attempted to try anything yet. i was looking into mysql_fetch_array but that wants to display all of the users information for their row.
i havnt attempted to try anything yet.
ya. well, if you had, you'd know that you can do more with it than you think.
if you write a query limiting your results, then you're going to get what you want.
$query = "SELECT wmyt000 FROM cash_flow_plan WHERE username = '$username'"
$row = mysql_fetch_row($query);
print_r($row); // now you can see the structure of your array. access it accordingly.

How to create a Profile URL for a user using $_GET['id']

Can someone advise me if I am performing the below steps correctly:
When a user wants to register on the website, register.php handles his/her request. Below is some of the code from register.php:
$sql="INSERT INTO Members (fldFullName, fldEmail, Password, Gender, DOB)
VALUES
('$fname','$email','$pass', '$gender', '$date')";
Particularly when I wrote the above code, I was somewhat new to PHP/MySQL and still am. Therefore, I made all of the fields above manually in the table via phpmyadmin. Furthermore, I also added the ID field manually via phpmyadmin, as the first field with auto increment and primary key of course. Why I did it manually, I can't remember the reason of. But I'm pretty sure that this may be the reason why I'm having problems.
What I'm trying to do is, when a user registers on the website, I want a profile URL to be created for him/her. For example, the field in the table could be named ProfileURL, whereas the actual value could be http://www.domain.com/profile.php?id=1, where the id is inherited from the actual ID in the table. How can I do this with my above code? Did I do something wrong when I decided to save all the fields manually via phpmyadmin? Note: I've also been creating tables, databases, fields manually via phpmyadmin. However, its values are INSERTed automatically of course. Am I even on the right track?
Thank you.
As stated above, you don't need to save a profile URL to the database. I'm guessing all profile URLs are going to follow some standard form (i.e. www.example.com/profile.php?id=1)?
Well, if you saved all of those in your database and then you decided you were going to change the format to something like www.example.com/profile/1 you're going to have a lot of out-of-date data in your database. You're going to have to go through each record and update it, and that could be dangerous on a database table with say, millions of rows.
Therefore, the solution is to have a script that takes a parameter. Say profile.php. As above, you would check for the profile using the data in the $_GET array:
<?php
if (isset($_GET['id'])) {
$id = mysql_real_escape_string($_GET['id']);
$sql = "SELECT * FROM members WHERE id = '$id' LIMIT 1";
$res = mysql_query($sql);
if (mysql_num_rows() > 0) {
$member = mysql_fetch_object($res);
// handle displaying of member's profile here
}
else {
// member does not exist with ID
}
}
?>
That way, if you decide to change the script name or use search engine-friendly URLs, you don't need to change your database structure.
In profile.php, check for $_GET['id'], then if it exists, use a SELECT query for the same ID in the database. It would look something like this.
<?php
if (isset($_GET['id']))
{
$id = (int) $_GET['id'];
$sql = 'SELECT * FROM Members WHERE ID = ' . $id;
// Then the rest of the code to check the results goes here
}
?>
A user with an ID of 1 would be profile.php?id=1
You are doing right. Now write SQL like this:
$sql = sprintf("SELECT * FROM Members WHERE ID=%d", mysql_real_escape_string($_GET['id']));
And you'll be able to get userdata by $_GET['id']. Remember to use mysql_real_escape_string to protect your queries against SQL injection. sprintf is also a good thing to substitute right data types like numbers or strings.
You don't heed to save profile url.
You have to build it dynamically.
Because most of the url remains the samy, only id is changing.
So, get id from the database and add it to the url.

Categories