please i need come help i have a form of check boxes i want to save the name and value of the boxes that registered user selects into a table ,now i have registered users information saved in a table ,how the table that saves the registered users selection is to be created to have a relation with the table of users????
my registered users table
<?php
$connect=mysql_connect("localhost","root") or die (mysql_error());
mysql_select_db("login") or die (mysql_error());
$query="CREATE TABLE users(
userid int not null auto_increment primary key,
username varchar(20),
password varchar(40),
usertype varchar(20),
firstname varchar(30),
lastname varchar(30),
street varchar(50),
city varchar(50),
country varchar(50),
postcode varchar(10),
gender varchar(6),
dateofbirth date,
telnumber varchar(50),
email varchar(50),
insertdate date,
vals text,
comment text
)";
$result=mysql_query($query,$connect) or die('Cannot Create User');
mysql_close();
print " DataBase created well" ;
?>
Let's say you have table of users like this:
**users**
------------------------------
userid username etc...
1 billy ...
2 joe ...
Now you have to create table like this:
**users_checkboxes**
------------------------------
id user_id name value
1 1 newsletter 1
2 1 send me spam 0
3 2 newsletter 0
4 2 send me spam 0
This information means that billy chosen to receive newsletter and no spam while joe does not want to receive anything.
The key is to have userid from the first table here, this is called foreign key. You can read more about it at Wikipedia.
You might like to reword your question so it's easier to read, here's what I think you meant:
How can I update user's data in the database using a form of checkboxes?
Checkboxes are inputs and will come up like text inputs in your GET or POST array (you're more likely to use POST for this).
E.g.:
<form action="update.php" method="post">
<p><input type="checkbox" name="showDate" /> Show the date on every page.</p>
<p><input type="submit" value="Update user record" /></p>
</form>
Then in your PHP you would use something a little like this:
<?php
// Check form has been submitted
if (isset($_POST['showDate'])) {
// Assuming the user is updating their own profile and their
// user id is registered in a session
$update = 'UPDATE users SET showDate = %d WHERE userid = %d';
// It's better to use prepared statements for this, see http://php.net/mysqli
mysql_query(sprintf($update, $_POST['showDate'], $_SESSION['userid']));
} else {
// show the form
echo $form;
}
Hope this makes sense (and is what you were looking for) - your question was unclear to me.
Related
Conditions:
1. Let's say, I have a table like this:
create table users (
id int not null auto_increment primary key,
first_name varchar(255),
last_name varchar(255),
email varchar(255)
);
And I have a simple form users/add with 2 input fields - user and email - and submit button
What I want to do is the following: I want to insert Form data based on what is typed inside user field. I mean if I type a word all, cakePHP will insert the same email for all users in that table. If I type only one digit (i.e. id), cakePHP will insert email only for a user with this id.
How do I do that?
here is some controller code that might help you out.
function add()
{
if ($this->request->data['inputName'] == 'all') {
$this->User->updateAll(
array('User.email' => value)
);
} else {
$this->User->id = $this->request->data['inputName'];
$this->User->saveField('email', value);
}
}
saveField
updateAll
Im creating a website for booking activities. I have 3 centres. The customer is cant book the same activity twice neither in a different centre. Im using a table in mysql which i store the infos provided by the costumers. Is there any way to filter or to check in my php code if a customer has already booked the same activity more than one time and echo an error msg?
my table(and the info im asking) contains these columns:
ID(Primary)
FirstName
LastName
Email
ContactNumber
ClassName
Week
Intensity
CentreName
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sql1="INSERT INTO loan (loan_id)
VALUES ('$values[loan_id]')";
$result = mysql_query($sql1);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
When you create the table add the unique attribute to the fields you want to prevent, something like this
CREATE TABLE Persons
(
P_Id INT NOT NULL AUTO_INCREMENT,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255),
UNIQUE (P_Id)
)
If you already have created the table just edit it like this
ALTER TABLE Persons
ADD UNIQUE (P_Id)
Hope this helps you; If you do not have a unique id i believe this will suit you best on what you need; Note that this is not the full code; You need to add some to other information to fit in your question;
// Checks if the value already exist on the database
$query = SELECT EXISTS(SELECT column_name FROM table_name WHERE
condition LIMIT 1)
// If condition is not met it will proceed with save
if (mysql_num_rows(!$query) > 0) {
echo "Activity Booked";
} else { // If condition is met it will echo an error message
echo "Unable to booked activity"; }
You need to create a unique (composite) index on the column(s) that you wish to be unique. You can disregard your PK when making your unique index. In your case your sql would look something like:
Alter table yourtablename
add unique index idx_unq(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`);
Then do an INSERT IGNORE INTO instead of an INSERT INTO.
This post may also help you.
"INSERT INTO .. ON DUPLICATE KEY UPDATE" Only inserts new entries rather than replace?
In order to see if record already exist in table you must first "test" to see if that exact record exist in your table. This is to be done before the 'Insert IGNORE Into' in your logic. Using the variables your code would look something like this:
$testcount = "Select count(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`)
from yourtablename
where
(LastName = '$LastName' AND FirstName= '$FirstName' AND Email= '$EMAIL' AND ContactNumber= '$ContactNumber' AND ClassName= '$ClassName' AND Week= '$Week' Intensity = '$Intensity' AND CentreName = '$CentreName' )";
This query will give you back (assuming there are no duplicates already in the table) a 0 or a 1 and store it in your $testcount variable. This can then be used to either determine based on the value to insert the record into the table or print a message to end user informing them that it already exist.
I am not sure how you want to structure the php code but the psuedocode would look something like:
If $testcount = 1 then do your insert.
else if $testcount = 0 then echo your message.
In database I already have this inside:
id | username | password
=========================
3 | John | happy
The same user register an account whose id of 3 is stored in PHP session. I want to store another row where the id is also 3 into the database.
The output will be something like this:
id | username | password
=========================
3 | John | happy
3 | Emily | sad
So far I got this:
abc.php
$result = mysql_query("SELECT id FROM account WHERE username='".$username."' LIMIT 1") or die(mysql_error);
while ($row = mysql_fetch_assoc($result))
{
$_SESSION['id'] = $row['id'] ;
}
<input type="hidden" name="custom" value="<?php echo $_SESSION['id'];?>">
cba.php
$id = $_POST['custom'];
mysql_query("INSERT INTO user (id, username, password) VALUES('".$id."', '".$username."', '".$password."')") or die(mysql_error());
I tried with the session where the id is 3 and try to insert into the database but nothing is inserted.
Very curious why you want to do this. Any who, you could try something like:
$sql = "INSERT INTO user (id, username, password)
SELECT MAX(id), '" . $username . "', '" . $password . "' FROM user";
Hope you're also not storing the password in plain text.
What you are trying to do is have "two unique" values that are the same. It can't be done. Else the values aren't unique anymore.
To answer you question, if the field you want to store the value in is not a field where you enforce uniqueness, then a simple insert should do it. Unless you want to fetch values from the database and make duplicates. It's hard to make out what you want. But just trying to insert a value you know is already in the field. It will work if it's not a unique or a primary field.
I think you need an update query. As the id is already present(user is registered as he session has an id), you need to update the existing user's info with new details.
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.
Below I have a $_POST variable for the teacher's firstname and surname:
if (isset($_POST['teacherforename'])) {
$_SESSION['teacherforename'] = $_POST['teacherforename'];
}
if (isset($_POST['teachersurname'])) {
$_SESSION['teachersurname'] = $_POST['teachersurname'];
}
Now the problem I have is that I want to insert this into the database but I don't want the firstname and surname to be inserted into the database, I want the teacher's username to be inserted into the database.
For example: John May has a username T1, Ben Watts has a username T2 and Jean Smart has a username T3.
So how can I get it so that it looks up the teacher's firstname and surname, find the teacher's username from that (field for username is TeacherId) and then insert the username in the 'TeacherId' field in the "Session" Table?
I have connection to database and all that. I just want to how to code it so that it finds a teacher's username (TeacherId) by its full name then insert it into the database?
Do you want Teacherid (like T1,T2,T2) by looking username which is obtained by selecting surname and forename??
SELECT TeacherId FROM (SELECT Username from teachers where forename='forename' and surname='surname')
Why not query database with WHERE name='$name' (combination of firstname.' '.lastname)
And use the returned ID in your script?