firstly I apologise I am really new to PHP MySQL so if I am really off track please dont grill me!
I have a membership area and two tables. The first table is the members data and the second table will hold services that the members choose.
The table layout looks like the following:
Table: members
id = Primary Key
username
email
etc
Table: services
id = Primary Key
members_id = Foreign Key
serviceone
servicetwo
etc
What I am trying to achieve at this point is to update data into the child table based on the logged in user linked by the foreign key. My PHP looks like the following:
<?php
require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
//define page title
$title = 'Members Page';
//include header template
require('layout/header.php');
$userId = $_SESSION['id'];
if(isset($_POST['submit'])){
$sql3 = $db->prepare
("UPDATE services SET serviceone = :serviceone, servicetwo = :servicetwo WHERE members_id = :id");
$sql3->execute(array(
':serviceone' => 'variablehereoneday',
':servicetwo' => 'liketheabove',
':id' => $userId
));
}
?>
I am hoping someone may be able to point me in the right direction on how the concept of updating the child table with the logged in user looking at the primary key from the members table works.
Once again sorry if I am totally off track.
Thank you
Related
I am working on source code where there is a table called tvseries (id = foreign key, tvs_id = primary key). what i want to achieve is that when user gets logged in for first time and submit a form related to tv series info it should insert a new row in table with related data but when again user submits that form it shouldn't create new row instead it should update the existing row.
Simply, only first time when user submits form it should insert details submitted and afterwards it should be updated whenever submitted.(i just want only one row to be inserted and latter updated with that form).
I have written a code which only inserts a new row with related data each time it is submitted
This is my code (Insertion part)
$query = "INSERT INTO Tvseries SET Tvseries_fav=?, Tvseries_rank=?, Tvseries_rewatch=?,
Tvseries_status=?, Tvseries_rec=?, id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('siissi', $tvsfav, $tvsrank, $tvsrewatched, $tvsstatus, $tvsrecommend, $id);
$result = $stmt->execute();
if ($result) {
$tvs_id = $stmt->insert_id;
$stmt->close();
$_SESSION['message'] = 'Details have been submitted successfully!';
$_SESSION['type'] = 'alert-success';
header('location: Tvseriesinfo.php');
} else {
$_SESSION['error_msg'] = "Database error: Could not update details";
}
}
Extra info :
I have another table called users (where id = primary key),
Am using session variables.
How should i change my code so that i can achieve my objective which is mentioned in first two paragraphs.
I have searched stack overflow for related solution but haven't found satisfactory solution. Any help from you will be appreciated.
And one more thing my form contains only selcect boxes.
Thank you
I am working on an employee database which will store useraccount information. I have created the forms and am now working on getting the data from the forms into the database. My Users table has fields for first name, last name, email, etc. as well as foreign keys organization_id, supervisor_id, etc. So far I have the following code for inserting into the non-foreign-key fields:
$f_name = $_POST['firstName'];
$l_name = $_POST['lastName'];
$user_type = $_POST['userType'];
//etc...
$insert = "INSERT INTO Users(f_name, l_name, user_type, email, empl_status_id, reliab_status_id, secr_status_id, ";
$values = "VALUES($f_name, $l_name, $user_type, $email, $empl_status, $reliab_status, $secr_status, ";
if($w_username) {$insert .= "w_username, "; $values .= "'$w_username', ";});
$sql = $insert . $values;
All of those fields are required, except for w_username which may be left blank. Organization and Supervisor may also be left blank.
The problem is, when they are NOT null, I am not sure how to insert them into the database. In the form, the user may enter their organization in a text field which is linked to a datalist. The datalist should be populated by Organizations that have been previously entered. If a new Organization is entered, it should be added to the database, and consequently, the datalist.
So do I insert the OrganizationID if it's selected from the datalist? How do I do that? I thought maybe I would have to iterate through the list, but then if the list becomes very long eventually, wouldn't that be a problem?
Note: Please explain like I'm 5, I'm really new to this!
Try Something like below
<?php
//take OrganizationID as text from form (leave auto complete as it)
$sql = "select OrganizationID from org where Organization_name LIKE '".$_POST['OrganizationName']."'";
//execute it .....
if(mysql_num_rows()>0){
$id = $row['id']; //and put in foreign table
}
else{
// insert to org here and get last inserted id calling mysql_insert_id() ;
// and put in foreign table
}
?>
I have created this code in order to register users in my database. What I cannot manage to do, is to prevent adding the same user again and again. Here is my code:
connectDB();
$safe_fullname = mysqli_real_escape_string($mysqli,$_POST['fullname']);
$safe_email = mysqli_real_escape_string($mysqli,$_POST['email']);
$safe_password = mysqli_real_escape_string($mysqli,$_POST['pass']);
$addStatement="Insert into Users (Fullname,Email,Password,Is_Admin) values ('".$safe_fullname."','".$safe_email."','".$safe_password."','N')";
$result = mysqli_query($mysqli,$addStatement) or die(mysqli_error($mysqli));
Add unique to you table for (if it is meant to be unique) email or Username column:
ALTER TABLE Users ADD UNIQUE (Email);
OR
ALTER TABLE Users ADD UNIQUE (Username);
This way database only accepts one record with same email address or Username.
Other way to do this, is to select values from DB with given details. For example, let's use Email column:
$res = mysqli_query($mysqli, "SELECT Email FROM Users WHERE Email = '{$_POST['email']}'");
if(count($res) > 0) {
//exists => do stuff
} else {
//doesn't exist => do stuff
}
I wonder if someone can help?
I am new to PHP and have started creating a membership based website as a project to try and learn some new PHP and I was wondering what the correct syntax would be to auto-create a table?
Here is my current code, I am looking to create an individual table for each user however upon trying and trying I can't seem to get it to work!
Any suggestions/corrections?
<?php
require("dbconnection.php");
if(empty($_SESSION['username'])) {
header("Location: index.php");
die("Redirecting to index.php");
}
$user = $_SESSION['username'];
$sql = "CREATE TABLE $user (id int(5) NOT NULL)";
$result = mysql_query($sql);
if(!$result) {
echo "FAILED";
}
echo "CREATED";
?>
The dbconnection.php file is working correctly as all my other pages call it in order to carry out other tasks.
DO NOT DO THAT !
Why not inserting a new row in a single table that hold all data of all the users ?
$sql = "INSERT INTO users (username) VALUES ('".$sql."')";
Based on my experience, It's highly not recommendable to create each table for each user because it's very expensive in terms of space and resources. If Facebook were doing the same thing, they would be having 1.1 billion tables on their database! Instead of that they have 1 table for all these members. Use one table, then keep a Primary Key column e.g. Id to be used to identify the person. e.g.
$sql = "CREATE TABLE IF NOT EXISTS users (
id INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
names VARCHAR(100),
email VARCHAR(100),
password VARCHAR(200)
)";
mysql_query($sql) or die(mysql_error());
Then as user signs up, the id column auto increments, thus he/she will have a unique Id that you can use to trace him/her, like this;
$res = mysql_query("SELECT * FROM users WHERE id ='".$id."'") or die(mysql_error());
$data = mysql_fetch_assoc($res);
echo $data['names']." ".$data['email']; /* names, email, password ... etc */
This is much better. Rather than creating 1 million tables, you can just have 1 table for all the 1 million people.
Regards!
If we wanted to show each user which users of the opposite sex have viewed their profile, what would be the best way to keep track of all those views in MySQL?
Each user has a unique userid from the main Users table, which also stores their sex.
We would want to show each user the users that viewed them in order of most recent view to oldest view.
We would obviously not want to show the user themselves if they happened to view their own profile.
We would want to show guys only the girls that viewed them, and the girls only the guys that viewed them.
How would we setup the table of ProfileViews to do that?
What indexes would we use?
What would be the query we would need to show each user who has viewed them?
This is a simple example that I will make for you, hope this helps.
SQL:
CREATE TABLE user
(
user_id BIGINT NOT NULL AUTO_INCREMENT,
sex VARCHAR(10) NOT NULL,
CONSTRAINT PK_USER PRIMARY KEY (user_id)
) ENGINE=INNODB;
CREATE TABLE profileview
(
profileview_id BIGINT NOT NULL AUTO_INCREMENT,
user_id BIGINT NOT NULL,
visitor_user_id BIGINT NOT NULL,
date_time DATETIME NOT NULL,
CONSTRAINT PK_PROFILEVIEW PRIMARY KEY (profileview_id)
) ENGINE=INNODB;
ALTER TABLE profileview
ADD FOREIGN KEY FK_PROFILEVIEW_USER(user_id)
REFERENCES user (user_id);
ALTER TABLE profileview
ADD FOREIGN KEY FK_PROFILEVIEW_VISITOR(visitor_user_id)
REFERENCES user (user_id);
PHP:
This is a simple example of the user profile page - www.domain.com/profile.php?id=xxx.
At this point you need to define two variables in session when the user logs into the site:
$_SESSION['user_id'] (int) / $_SESSION['user_logged'] (boolean)
<?php
if ($_GET && isset($_GET['id']){
if(isset($_SESSION['user_id']){
$profile_user_id = $_GET['id'];
// the user that visits the profile has a session with his/her id on it.
session_start();
$visitor_user_id = $_SESSION['user_id'];
} else {
// if visitor specified an id but there is no session, redirect to login.
header("location: login.php");
}
} else {
// if no id passed redirect to index
header("location: index.php");
}
?>
<html>
<head>
<title>Your title</title>
</head>
<script src="scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
//here you will store the visit with jquery.
$(document).ready(function(){
// store the values from php.
var profile_user_id = <?php echo $profile_user_id ?>;
var visitor_user_id = <?php echo $visitor_user_id ?>;
// here, the user information goes to the visit.php file.
$.post('visit.php' { profile_user_id:profile_user_id, visitor_user_id:visitor_user_id } );
});
</script>
<body>
Here print user information from a SQL select or something of the id passed in the GET.
</body>
</html>
Now, the visit.php file to store data:
<?php
if ($_POST && isset($_POST['profile_user_id']) && isset($_POST['visitor_user_id'])) {
session_start();
// this will end the execution of the script if there is no session from user logged
if ($_SESSION['user_logged'] != true) {
exit();
}
// everything is ok, do the process:
// functions.php contains your SQL connection, I suppose you know how to do it.
include('../cgi-bin/functions.php');
$link = dbconn();
$profile_user_id = mysql_real_escape_string($_POST['profile_user_id']);
$visitor_user_id = mysql_real_escape_string($_POST['visitor_user_id']);
// this will store the data in profileview including date and time if id's are not equal.
if($profile_user_id != $visitor_user_id){
$sql = "INSERT INTO profileview (user_id, visitor_user_id, date_time) VALUES ($profile_user_id, $visitor_user_id, NOW())";
mysql_query($sql, $link);
}
}
?>
EXTRA: if you don't know what functions.php do, here it is:
<?php
function dbconn() {
if(!include_once('db.php')) {
die('Error include file.');
}
if (!$link = mysql_connect($db['hostname'],$db['username'],$db['password'])) {
die('Error connecting.');
}
if (!mysql_select_db($db['database'])) {
die('Error selecting.');
}
return $link;
}
?>
The above file will need this file too: setup here your connection parameters to your db.
db.php
<?php
$db = array(
'hostname' => 'localhost',
'username' => 'root',
'password' => 'mysql',
'database' => 'mydb'
);
?>
I suggest you to put this in the cgi-bin folder of your hosting for better practices as you can see in visit.php file code.
Now, create another file called visitors.php?id=xxx and do a select * from of your profile views according to the user_id. At this point you will be able to:
Get the user_id information and if it is men (for example)...
Select visitors by sex and do a rule to list only female visitors.
List visitors according to the time stored in profileview table.
profileviews:
profile
userwhoviewed
timestamp
Index the profile column.
So when your user views the page, check if it's the profile owner, get the sex of the profile owner, check the sex of the viewer, if different, update the table with the viewer and the timestamp.
When querying the results, just select all rows matching the target profile, ordered by timestamp desc, and iterate to build your links back to those profiles.
I normally use INT data types in these fields (keeps the rows smaller and speeds up the lookups), then have a user table that generates those UID's as an auto_increment primary key. That will hold your gender and preference fields, too, as well as any other ancillary user data, and makes it easier to change login names, if desired.
But you're leaving out your gay users. Better to just log them all and let the user filter based on their preferences. :)
UsersTable
UserID Sex
1 Boy
2 Girl
3 Girl
UsersViewsTable
UserID View Unixtimestamp
1 2 342143243432
1 3 142143243432
2 3 242143243432
3 1 442143243432
When you visite the user profile, you'll use this :
IF CurrentUserSex != UserProfileSex
INSERT INTO UsersViewsTable (UserID, View, Unixtimestamp) VALUES (CurrentUser, CurrentProfileUserID, time)
Now, you want to fetch this on a page to see last seen from opposite sex ?
SELECT * FROM UsersViewsTable LEFT JOIN UsersTable USING (UserID) WHERE Sex != CurrentUserSex GROUP BY View ORDER BY Unixtimestamp DESC
EDIT :
IF CurrentUserSex != UserProfileSex {
$Res = SELECT CurrentProfileUserID FROM UsersViewsTable WHERE UserID = CurrentUserID AND View = UserProfileID LIMIT 1
if($Res['Count'] == 1){
// Exist
UPDATE UsersViewsTable SET Unixtimestamp = time WHERE UserID = CurrentUserID AND View = UserProfileID LIMIT 1
} elseĀ {
// Doesnt exist
INSERT INTO UsersViewsTable (UserID, View, Unixtimestamp) VALUES (CurrentUser, CurrentProfileUserID, time)
}
}
Just check n compare for each user profile page with the visitor id and profile id. If two are different store in a visit table with date and time and your required info. Before inserting just check the table row
if prof id, vistor id already exists then update the time else just insert the data.
Thanks.