adding user photos to database - php

my question is on adding the file paths to images to a user's slot in a database. here is a sample, this is the page where the photos are to be chosen:
require_once("script.php");
<form method="post" action='golf.php'>
<?php
require_once("golf_phot.php");
?>
</div>
<input id="butt" type="submit" value="add"/>
</form>
here are the contents of golf_phot.php:
$query="SELECT category_id FROM categories WHERE category_name='golf'";
$resultt=mysql_query($query);
$row=mysql_fetch_array($resultt);
$do=$row['category_id'];
$query2="SELECT photo FROM all_photos WHERE all_photos.category_id='$do'";
$result=mysql_query($query2);
while ($row=mysql_fetch_array($result))
{
$photo=$row['photo'];
echo "<input type=\"checkbox\" name=\"addlist[]\" value=\"".$photo."\">"."<img src=\"".$photo."\">";
echo "<br>";
echo "<br>";
echo "<br>";
}
i already did the mysql connection and database selection, i won't post that but it has no issues. here are the contents of "script.php":
if(isset($_POST['addlist']))
{
$pics=$_POST['addlist'];
$n=count($pics);
//now, to open the database user_info, using the stored session
//make the session variable legit
if(isset($_SESSION['user']))
{
$user=$_SESSION['user'];
}
//get the user's id from the user_info table
$querya="SELECT * FROM user_info WHERE user_info.fb_id='$user'";
$result1=mysql_query($querya);
//now that we have the id, we can add the photos to
//user_photos, using their id as a foreign key
if(mysql_num_rows($result1)>0){
$rowa=mysql_fetch_array($result1);}
$user_id=$rowa['USER_INFO_ID'];
//before we add them, we'll need to see whether they exist or not.
//adding time:
for($i=0;$i<$n;$i++){
$data=$pics[$i];
$queryb="SELECT * FROM user_photos";
$result3=mysql_query($queryb);
if(mysql_num_rows($result3)>0){
while($rowa=mysql_fetch_array($result3))
{
$data2=$rowa['USER_PHOTOS'];
if($data==$data2)
{ $var='exists'; }
else{
$queryb="INSERT INTO user_photos(USER_PHOTOS_ID,USER_INFO_ID,USER_PHOTOS) VALUES('NULL','".$user_id."','".$data."')";
$result2=mysql_query($queryb);
}
}
}
}
// selected photos added to user's gallery!
}
the user data variables are all set as i use them elsewhere and they are successfuly added to the database, above, i include a way to see if the photo already exists, i don't add it if it does(maybe there's an issue with that?) so basically, the page with photos is loaded, the user checks on the photos they want and then they send it to the same page, where "script.php" is supposed to process the data and add it to the database. no photos are added to the database, i really can't tell what's the issue here. i kindly ask for help, even though this is probably an easy question, if you need me to clarify something, kindly ask so, meanwhile, can anybody help? thanks in advance.

One solution for check the picture is same or not is, using a hash algorithm on the pictures to determined the same pics.
i.e: (pseudo code)
$hash=sha1_file('pic-filename');
$sql='select * from image_table where hash_col ='.$hash;
if(num_rows($sql)>0)
//don't save pic.
else
// save the pic and it's hash value.
hash_col is a column in your image table that get the hash value of the particular image.

Please Try this code in your script.php. hoping this may work for you.
I Have removed the condition if(mysql_num_rows($result3)>0){
Code:
if(isset($_POST['addlist']))
{
$pics=$_POST['addlist'];
$n=count($pics);
//now, to open the database user_info, using the stored session
//make the session variable legit
if(isset($_SESSION['user']))
{
$user=$_SESSION['user'];
}
//get the user's id from the user_info table
$querya="SELECT * FROM user_info WHERE user_info.fb_id='$user'";
$result1=mysql_query($querya);
//now that we have the id, we can add the photos to
//user_photos, using their id as a foreign key
if(mysql_num_rows($result1)>0){
$rowa=mysql_fetch_array($result1);}
$user_id=$rowa['USER_INFO_ID'];
//before we add them, we'll need to see whether they exist or not.
//adding time:
for($i=0;$i<$n;$i++){
$data=$pics[$i];
$queryb="SELECT * FROM user_photos";
$result3=mysql_query($queryb);
while($rowa=mysql_fetch_array($result3))
{
$data2=$rowa['USER_PHOTOS'];
if($data==$data2)
{ $var='exists'; }
else{
$queryb="INSERT INTO user_photos(USER_PHOTOS_ID,USER_INFO_ID,USER_PHOTOS) VALUES('NULL','".$user_id."','".$data."')";
$result2=mysql_query($queryb);
}
}
}

Related

How to make a generated code expire after a few times of entering (PHP)?

I have been trying to write a code in PHP that generates a random code, stores it in the database and asks the user to enter it. if the code is entered more than 3 times, the code needs to be expired. this is my code:
<?php
include("ProcessCode.php");
$con = mysqli_connect("localhost","root","") ;
if(mysqli_select_db($con,"login"))
{
echo 'database selected' ;
}
$rand=rand();
echo $rand ;
$sql = "INSERT INTO random (number) VALUES ('$rand') " ;
if(mysqli_query($con,$sql))
{
echo 'inserted' ;
}
?>
$CodeCheck=$_POST['code'];
//Establishing Connection with server
$conn = mysqli_connect("localhost", "root", "");
//Selecting Database
$db = mysqli_select_db($conn, "login");
//sql query to fetch information of registerd user and finds user match.
$query = mysqli_query($conn, "select * from random WHERE number='$CodeCheck'");
$rows = mysqli_num_rows($query);
if (mysqli_num_rows($query) > 0)
{
echo " Code exists already.";
}
if($rows == 1)
{
header("Location: Success.php");
}
else
{
$error = " Code is Invalid";
echo $error;
}
could you please explain how to implement the expiry part?
in your table you could have a field for count. When use login and login is wrong, add + 1 to your count. When user login successfuly, reset the count. If count meet +3, reset the code.
i understand from your question that you need the logic on how to make the random_code expired after inserting from interacted users on your website 3 times ,assuming that , as long as the code is not expired he will be able to do his inserts and you may load it on your page .
i would do that through database queries .
Please follow this instruction listed below
instructions :
while your php page generate the random code , you may store it in database table with a auto reference key , for instance ,
assuming that you have randomly generated a code as below :
"Some random code here"
the above code which was generated by your php page have load it from mysql table called Random_Generated_Code , i would go to edit this table and add new field in it and call it generated_Code_Reference_Key ( could be auto serial number ) to avoid any duplication as well make additional field called Expire_Flag which we are going to use later.
so once your page have loaded the above example code , you should retrieve the generated_Code_Reference_Key along with it and keep it in hidden variable on your page
it should be loaded on the page based on expire_Flag value as a condition
select generated_code from Random_Generated_Code where expire_flag = ""
now once the user try to insert that generated code , in each time he insert it define another table in your database lets call it ( inserted_Codes_by_users) and store in it the username of whoever is doing that on your website as well you have to store the generated_Code_Reference_Key which we are storing in hidden variable as mentioned earlier to indicate which code was used while inserting.
now during page load or any event you want you can find expired code by make select statement from the inserted_Codes_by_users table
select count(generated_Code_Reference_Key) as The_Code_Used_Qty from inserted_Codes_by_users where username = username_of_that_user
so you can get how many times this user have inserted this specific generated_random_Code
retrieve result of the query in a variable and to make sense lets call it The_Code_Used_Qty and make if condition on page load event or any event you like
if The_Code_Used_Qty = 3 then
fire update statement to first table which loaded that random generated code
and update the expire_flag field for that code (Expired) based on reference_key
update Random_Generated_Code set expire_Flag = "expired" where generated_Code_Reference_Key = "generated_Code_Reference_Key" << the one u stored in hidden variable
end if
so now that will get you directly to the point of why we are loading random_generated_code table first time with that condition expire_flag = ""
as it will only retrieve the codes which is not expired .
hopefully this will help you to achieve what you want .
good luck and let me know if you need any help or if you face any confusion while reading my answer.
Good luck .

After login pull data for respective users from db

M building a web app here.The authentication php code looks like this (Please ignore the threats for time being) :
<?php
session_start();
if(isset($_POST['submit']))
{
mysql_connect('localhost','*****','******') or die(mysql_error());
mysql_select_db('cl29-demodb') or die(mysql_error());
$name=$_POST['name'];
$pwd=$_POST['password'];
if($name!='' && $pwd!='')
{
$query=mysql_query("select * from EmployeeTable where EmployeeName ='".$name."' and password='".$pwd."'") or die(mysql_error());
$res=mysql_fetch_row($query);
if($res)
{
$_SESSION['id']=$res['id'];
header('location: profileindex.php');
}
else
{
echo "user name and password are incorrect" ;
echo "<a href=index.php> click here to go back </a>";
}
}
if(!isset($_SESSION['id'])){
echo "Sorry, Please login and use this page";
exit;
}
}
?>
I am able to login successfully and reach the profile of the user.But I want the profile to display only the information for respective users.The profile looks like this:
I have written the php to retrive the name,designation,weekly points,overall points,weekly rank and overall rank respectively.
I tried to echo the variables in the html.
But I am not able to do so.It isnot pulling any data.I have column for all the above fields in the table.
Kindly help.
May be this is the cause
mysql_fetch_row() return the numeric array and you are accessing as $res['id']
either replace mysql_fetch_row with mysql_fetch_array or try numeric index of your id
$_SESSION['id']=$res[0]; or $_SESSION['id']=$res[1];
use mysqli_fetch_assoc so you could call the columns by name if you are using mysql_fetch_array you should call the columns by their index no the by the column name.
There is no need to start a session again in the profileindex.php as the session has already started in the login page.
print the sql and run it in the backend to check if you are getting the desired result in order to further debug this.

run another query after successful login

I need some help with my login script. I am just trying to self teach php and mysqli and stuck with this so any advice/help would be much appreciated.
The actual part that checks the login details works and directs the user a page if the match is found or back to login page if unsuccessful.
What I want to happen is once the username has been checked and the sessions set use the session 'user' to then find the same user from either the pupil or instructor table depending on the session 'member_type'. The session 'user' is set as the 'user_id' which is the same in the login table and the table the rest of the details are stored in and is the primary key of both tables.
<?php
include_once ("includes/dbconnect.php");
session_start();
$error="";
if ( isset($_POST['btn_signin']) ) {
// username and password received from loginform
$username=mysqli_real_escape_string($conn,$_POST['username']);
$password=mysqli_real_escape_string($conn,$_POST['user_password']);
$sql_checklogin="SELECT * FROM user_logins WHERE username='$username' and password='$password'";
$result=mysqli_query($conn,$sql_checklogin);
$login=mysqli_fetch_array($result,MYSQLI_ASSOC);
$count=mysqli_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count==1)
{
// Set Sessions
$_SESSION['logged_in']=TRUE;
$_SESSION['user']=$login['user_id'];
$_SESSION['member_type']=$login['reg_type'];
} else {
header("location:login.php");
$error = "Invalid Username or Password!";
}
}
//This part to be replaced with code that checks both tables to find the user details
if ( isset($_SESSION['member_type'])) {
header("Location:mydashboard.php");
}
?>
//The above code works and allows user to login but sends both member types to same page
Just now this works fine but I want to replace the last IF part of the script with something like this (or a better suggestion?).
//if ( isset($_SESSION['member_type'])=='pupil' {
//$sql_findpupil="SELECT * FROM pupils WHERE user_id='$_SESSION['user']'";
//$result=mysqli_query($conn,$sql_findpupil);
//$pupil=mysqli_fetch_array($result,MYSQLI_ASSOC);
Should I be putting another count function at this part?
//header("location:mydashboard.php");
//}elseif ( isset($_SESSION['member_type'])=='instructor' {
//$sql_findinstructor="SELECT * FROM instructors WHERE user_id='$_SESSION['user']'";
//$result=mysqli_query($conn,$sql_findinstructor);
//$instructor=mysqli_fetch_array($result,$MYSLQI_ASSOC);
And here?
//header("location:control_panel.php");
//}
//}
As I said, I am trying to teach myself some new skills at home so have probably made some basic school boy errors here and missed something obvious
isset() checks if a variable is set or not, but you want to check the value. So your if ( isset($_SESSION['member_type'])) is always true, for pupils and instructors. Try
if ($_SESSION['member_type'] == 'pupil') {
header("Location:mydashboard.php");
}
instead.
And another suggestion, refactor your database-design. Better don't use an instructor and a pupil table containing userIds, but a userType-Table containing only two rows (pupil / instructor) and then add a userTypeId to your user-table. And also add a foreign key from user.userTypeId to userType.id to make sure every user is linked to an existing userType.
Using that design you won't need another query, to determine if a user is a pupil or an instructor.

Get ID from PHP URL and use in a query

I've put certain values like a user id into the url e.g /index.php?id=1 in previous PHP files.
I have a HTML form that has an action like this:
<form name="staffResponse" method="post" action="respond_ticket.php?id=<?php echo $_GET['id']; ?>">
Which when you go to respond_ticket.php and simply echo the value for the id and look at the URL it does it successfully. Whats more the data that I am posting to that file is also done without problem. However I want to then write that information to a table but it does not seem to work.
Here is the respond_ticket.php file
<?php
include 'database/db.php';
$id = $_GET['id'];
$staffResponse = $_POST['staffResponse'];
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse') WHERE id='$id'";
$result = mysqli_query($connection, $sql);
if ($result === TRUE) {
echo '<p>Response ' . $staffResponse . ', has been added</p>';
}
else {
echo '<p class="warning">Unable to respond</p>';
}
?>
The db.php file has all the necessary information for connection to the database i.e name password etc. It also opens the question there too.
I keep just getting the warning message that I wrote.
you cant do an insert with a where modifier like this. change it to update ;)
UPDATE tickets SET staffResponse = '$staffResponse' WHERE id = '$id'
You are not supposed to use a WHERE clause with INSERT
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse')";
You may wish to set your tickets table up with auto increment so you dont need to insert an id if you haven't done that already.
use ON DUPLICATE UPDATE if it helps
INSERT INTO tickets (id,staffResponse) VALUES ('$id','$staffResponse')
ON DUPLICATE KEY UPDATE id=VALUES(id), staffResponse=VALUES(staffResponse)

What query do I need to determine if a user has favourited another?

I apologise for the simpleton question but I am having a complete blank, hence why the wording of the title is vague.
I have built a simple PHP/MySQL user favouriting system that works fine, except for one part. Once the user has favourited another user, I cannot think for the life of me how to show the user that they have already favourited that user.
This is what I have so far:
if (($user_data['username'] == $profile_data['username']) === false) {
if () { ?>
// Favourite user
<?php } else { ?>
//See whether favourited or unfavourite user
<?php } } ?>
The table structure of favourites is simply two columns, favouritee being the profile favourited and favouriter being the current user favouriting. This table is joined to a main users table and the columns are populated by username strings.
EDIT
This is what I have got so far:
$username = $user_data['username'];
$favouritee = $profile_data['username'];
$check_fav = mysqli_query("SELECT `id` FROM `favourites` WHERE (`favouritee` = '$favouritee' AND `favouriter` = '$username')");
if (mysqli_num_rows($check_fav) == 1) {
// Favourite user
} else {
//See whether favourited or unfavourite user
}
(Posted on behalf of the OP):
Working code:
if (($user_data['username'] == $profile_data['username']) === false) {
$username = $user_data['username'];
$favouritee = $profile_data['username'];
$check_fav = mysqli_query("SELECT `id` FROM `favourites` WHERE (`favouritee` = '$favouritee' AND `favouriter` = '$username')");
if (mysqli_num_rows($check_fav) == 1) {
// Favourite user
} else {
// Unfavourited/check
}
}
To find whether a user has favourited another user, assume $myUsername as the logged-in user's username from the session, and assume $otherUsername coming from a profile page of another user (or perhaps a paged list of users).
SELECT 1 FROM favourite
WHERE favouriter = :favouriter AND favouritee = :favouritee
You can then inject parameters $myUsername into :favouriter and $otherUsername into :favouritee and if you get a row, you already have a favourite connection, and if you get zero rows, there is no favourite connection.
This is just the raw query, so of course you'll need to add PHP database code around this. If you're not familiar with this, take a look at the docs for PDO or MySQLi at php.net - both sections will give enough information to get you up and running.
That said, assuming usernames are stored in the user table, I'd be inclined to switch the two columns in the favourite table to integer foreign keys - it'll be faster and will save disk space. I'd call these from_user_id and to_user_id to make it clear what they are foreign keys of, and the direction of the favourite.

Categories