Making like buttons for multiple images - php

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");

Related

mysql - Query to display record just added

I have two pages. One is a form that I use to simply input data that will be sent to my database and the second page that actually takes the data inputted into the form and sends it to the database and is supposed to display the information that I've just added.
Everything works fine, however I'm struggling with the query slightly. What I need it to do is display all the information for the last data inputted to the database.
The query I currently have just displays the data with the highest ID:
$sql = "SELECT * FROM Results ORDER BY ID DESC LIMIT 1";
So as an example I would be left with the following information after completing my form:
Success! Data being saved:
ID = 900 Amount = 206 Date = 2016-12-26
This is obviously just showing the data with the highest ID, but since the ID and all the data fluctuates, I need it to just show the data that has just been inputted.
I came accross this: Query to select newly added records only. But I don't believe this soultion to be viable as the database is external and I don't want to be creating new tables.
I was thinking that it might be possible to assign a hidden value to each newly added record via the query. e.g. New 1, New 2, New 3 etc. Then printing the latest record for New. However, I couldn't find anything on how to do this.
Any help would be greatly appreciated!
You must use this method to have very correct value:
Input form must send to another file that do inserting (we call it here insert.php)
insert.php must insert the data after validation and after that you can fetch the last ID number from database. Depending on the method you are working with it can be different. for example if you are using PDO you can get it by PDO::lastInsertId
after getting the ID you need to forward it to the viewing or editing page. for example view.php?id=LastInsertId. This forward have some reasons:
Codes can be cleaner.
We prevent refresh and resend inserting. for example if you do inserting inside view.php and user hit F5 to refresh the page, The insertion happening again.
This is the whole idea. you can use this method for only one page:
page.php?do=new
page.php?do=insert
forward to the page.php?do=view&id=lastInsertID
why you trying to get just inputted data from database? you can do it using HTTP POST/GET method easily.just send data as parameters and show them in second page.
If you already have the data you are inserting, you don't need to run a query to get it back from the database again, you could just ensure that the query was successful and display the data directly. Anyways:
You can get the insert ID from the last insert using the MySQLi object. For example:
$sql = "<your insert statement>"
$conn->query($sql);
$last_id = $conn->insert_id; //Id of the row you just inserted
$sql = "SELECT * FROM Results WHERE id=$last_id";
This is assuming you do the insert in the same page that you display the result.

Match single posted data with two column is mysql

I have a login form that works like if user email password and 2 pic is correct then echo logged in but problem is my email is match password is match but how can i match images with single [select html tag]. here is my html form....
<select name="image" multiple="multiple">
<?php
for($i=0;$i<5;$i++)
echo"<option data-img-src=\"$pic[$i]\" value=\"$pic[$i]\" ></option>";
?>
</select>
And mysql query is here .......
$mysql=mysql_query("SELECT * FROM `table` WHERE `email`='$email' AND `password`='$pass' AND `image1`='$image' AND `image2`='$image'") or die(mysql_error());
if(mysql_num_rows($mysql) ==1){
$_SESSION['user']= $email;
header("location: home.php");
} else {
echo "error";
session_destroy();
}
If both images are match then he is successfully logged in otherwise not
The idea would be that each 'image' is tied to an ID in your code and/or database.
When a person selects an image they're actually selecting the ID which that image represents.
Users, setting up their profile, go through a similar process, selecting an image (which saves the image's ID in their user row).
When it comes to logging in, it's just a simple case of comparing the ID of the image selected to the ID stored in the user's row.
This is the BASIC premise, and doesn't cover the security aspect of this feature.
I also see that your HTML supports the user being able to select multiple images (though you only use/reference up to two in your SQL query). The implementation for that doesn't change much compared to selecting a single image, so this answer still applies.
(Please excuse my terminology)
As Sean's answer suggests, every image should be tied with an id.
During registration, before inserting the values into database, you can generate a random number and rename the image to that generated number and add that number into the database.
File structure would be something like this
users/images/random_id.jpeg
How i would go about doing the login process is,
On change of input, i would perform an ajax request to fetch the unique id associated with the user's email or username, and image associated with the that id and four other random images.
Then the rest is simple, the user would select an image. We'd of course be matching its unique identifier to the identifier that exists in the database.
If its a match, log in.
This is just the logical approach.
Unless this is a learning exercise, switch to prepared statements.

MySQL update value +1 (increment) on button click

I know this question has been answered over a million times, but I'm very new to the whole programming scene and I just can't get it to work. Sorry, I hope you can help me!
HTML:
<div class="the_score">+76</div>
<div id="increment_value">Like</div>
I have a MySQL connection and I can fetch the data, but I want the score to update with +1 when someone clicks the Like div. I have a table "websites" with row "WebScore" that has the function int(10) (?? I hope that is correct).
I use this to fetch the data and show it on my website:
$r = rand(2,3);
$sql = "SELECT * FROM websites WHERE ID = $r";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
I presume you have a column, not a row, called WebScore.
You need the query
UPDATE websites SET WebScore = WebScore + 1 WHERE ID = $r
As you can see, it finds the right row of your table and updates the value of the WebScore column.
This sort of things can only be done from a PHP program. It can't be done directly from a Javascript method invoked within a web browser. So, if you want to react to a user click, you'll need to post a form or invoke an Ajax style call to a php endpoint. How to do that is the province of another question.
Keep plugging away; you'll figure out this database stuff.

How to restrict user from updating same row twice+

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.

How do I populate the values of form fields with data from another page?

I'm trying to insert variables from an SQL result into a HTML form in a way that the user can open a form and auto populate the values based on selected data.
I am displaying a table with query results, I'd like the user to be able to open a form that populates certain fields with data from a link in the table row.
This is what I have so far:
<?php
$result = mysql_query("SELECT * FROM numbers WHERE username = '$user_name' order by id DESC");
while($row = mysql_fetch_array($result))
{
echo $row['group_name'] . " " . $group_numbers = $row['group_numbers'] = 'Click here to insert numbers' . '<br/><br/>';
?>
I was then going to try and pick up the POST variable on account_group.php and then insert the numbers into form fields when opened.
Basically, I need a way to list all of the groups which contain numbers, and then have the ability to select which group of numbers you want to use (so to add them to the form).
While your question isn't really clear, I think I understand what you're trying to do, which is make links in a table that open a page with a form, having some fields preset by the values that you chose when clicking the link.
To do this is simple, just encode the values from your query in the links after they are displayed. E.g:
Click here to insert numbers
Then have form.php pick up the GET variables:
<input type="text" value="<?php echo isset($_GET['field1']) ? $_GET['field1'] : '';?>">
I would recommend iterating over GET variables that form.php expects to check them for sanity and set friendly variable names. E.g. $_GET['foo'] once confirmed set and checked for special characters and stuff could just become $foo.
You could also store them in the session for easy retrieval later. Note also that you'll want to make sure your links are properly encoded (via urlencode() when displaying the links, and urldecode() when consuming the variables in the form page).
This could be done with POST if you wanted, or lots of other ways. I suggested GET because it would be the simplest to implement.

Categories