I'm trying to make a little project for adding friends.
When you click the add friend button you are sending an Ajax call with the friend id & username (they are the id and name attributes of each add button) to the add.php file.
(The mysql structure is: 1 users table + X tables named the user's name(columns: friendid, ispending))
In the PHP file there are only 2 MySQLi queries: Here is the code for the add file:
session_start();
$friendid = $_POST['id'];
$myname = $_SESSION['username'];
$friendname = $_POST['name'];
$myid = $_SESSION['id'];
$add = new Mysqlconnect();
$add->db->query("INSERT INTO $myname VALUES($friendid, 'yes')");
$add->db->query("INSERT INTO $friendname VALUES ($myid, 'yes')");
$add->db_Close();
The Mysqlconnect class is required i just didn't want the code here to be too long.
Here's the Ajax call:
$('.add').click(function(){
var name = $(this).attr("name");
var id = $(this).attr("id");
$.ajax({
type: "POST",
data: "&name="+name+"&id="+id,
url: 'add.php',
success: function(){
alert("success");
}
});
});
THE PROBLEM :
When I click "add friend" it does alert "success" but only one table gets updated everytime or even no table at all.
Though one time I clicked it and it did work (I did not change the code that time, I tried clicking like every 20 seconds).
How can I solve this?
if i understood you correctly you seem to be creating a new table for each user's friends (1 users table + X tables named the user's name) this isnt a good approach and you'd be better off with just 2 tables: users and user_friends as follows:
drop table if exists users;
create table users
(
user_id int unsigned not null auto_increment primary key,
username varbinary(32) unique not null
)
engine=innodb;
drop table if exists user_friends;
create table user_friends
(
user_id int unsigned not null,
friend_user_id int unsigned not null,
created_date datetime not null,
primary key (user_id, friend_user_id) -- note clustered composite PK (innodb only)
)
engine=innodb;
A full example script can be found here : http://pastie.org/1242699
Hope this helps.
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
After looking around on stackoverflow, I'm still having a little trouble understanding the one-to-many relationship in mysql. I have a request coming in from the user (form submission) which will be stored in one table. This is a dynamic form that lets the user add extra fields therefore those will be stored in a separate table. So in short, in my db design, there will be one table for the users with PRIMARY KEY AUTO INCREMENT and there will be another table for the hostnames PER user (multiple fields -array) and using a foreign key that references to the primary key in the user table. Sorry if this is long but trying to make this a good question.
Example:
User Table: (ONE)
1. John Doe, blah, 11-12-15
2. Sally Po, blah, 11-14-15
3. John Doe, blah, 11-15-15
(these are three separate requests)
(numbers are primary key auto incr.)
Host Name Table: (MANY)
1. www.johndoe.com
1. www.johndoe2.com
1. www.johndoe3.com
2. www.sallypo.com
2. www.sallypo2.com
(these numbers (foreign key) should match the primary key for each request)
Code (Leaving out the actual queries + pretty sure I shouln't be using last_id):
$sql = "CREATE TABLE IF NOT EXISTS userTable (
id int AUTO_INCREMENT,
firstName VARCHAR(30) NOT NULL,
date DATE NOT NULL,
PRIMARY KEY (id)
)";
//query
$sql = "CREATE TABLE IF NOT EXISTS hostNamesTable (
id int NOT NULL,
hostName VARCHAR(90) NOT NULL,
FOREIGN KEY (id) REFERENCES userTable(id)
)";
//query
$sql = "INSERT INTO userTable (firstName, date)
VALUES ('$firstName', '$date')";
//query
$last_id = mysqli_insert_id();
for($i = 0; $i < sizeof($hostName); $i++){
$sql = "INSERT INTO hostNamesTable (id, hostName)
VALUES ('$last_id', '$hostName[$i]')";
//query
}
What am I doing wrong? (is this the right way to go about it?)
note: I was trying to get the last_id of the user Table so that I can use it in the hostName table as the foreign key
EDIT: I'm using MySQLi with php
EDIT 2:
After the changes, this is the error I am getting now: Cannot add or update a child row: a foreign key constraint fails (d9832482827984hb28397429.hostNamesTable, CONSTRAINT hostNamesTable_ibfk_1 FOREIGN KEY (id) REFERENCES userTable (id))Error: INSERT INTO hostNamesTable (id, hostName, ) VALUES ('', 'secondhost.net')
--Looks like the $last_id isn't even being recorded?
EDIT 3: Started working. Not sure what it was but I think it was because of some type.
why dont you just add an extra column in the hostNames table which is called "ref_user" and contains the ID of the user you are reffering to? So you can use unique IDs in both tables.
Make a query like:
SELECT * FROM hostNames WHERE ref_user = (SELECT id FROM userTable WHERE <uniqueColumn> = <uniqueIdentifierOfUser>);
But the included request must return only one line from users.
try adding mysqli $link as a parameter in your mysqli_insert_id
$last_id = mysqli_insert_id($link);
i presume you have this somewhere in your code
$link = mysqli_connect("localhost", "mysql_user", "mysql_password", "mysql_db");
if this doesn't work, try using mysql LAST_INSERT_ID() function
$last_id = $mysqli->query("SELECT LAST_INSERT_ID() AS last_id")->fetch_object()->last_id;
I have a table named users
fields:
ID INT
First_name VARCHAR
Second_name VARCHAR
National_ID INT
The ID field is an AUTO_INCREMENT.
I need to AUTO_INCREMENT the first 2000 users with just the ID and the other fields remain blank,so that the new users will start at 2001.
Kindly assist.
It's called auto increment, your ID column must be set to auto increment.
ALTER TABLE users AUTO_INCREMENT=2001;
Update
If you wish to actually create those rows (not just set the auto increment value) you can use PHP for this:
for($i=1; $i<=2000; $i++)
{
$query = 'INSERT INTO users (id) VALUES ('.$i.')';
//execute this query using your desired PDO or sql extension
}
This question already has an answer here:
Mysql - Add auto_increment to primary key
(1 answer)
Closed 9 years ago.
I have a form that sends the data it captures in to a database, i have a primary key attached to my table (form_id) which i want to autoincrement everytime a new form is submitted and consequently added into my database table. Currently it is just adding a 0 for the first form submitted then anymore forms i submit after do not show as it gives me a message saying you can not have two rows with the same id as zero, which is correct so i would like to change this?
Below is my php code that submits the data into the database:
public function action_claimincentive() {
$this->template->content = View::factory('crm/uk/claim_incentive_form');
$this->template->content->thanks = false;
$this->template->content->val = '';
$this->template->content->post = '';
if ($this->request->post('form')) {
$post = $this->request->post('form');
$stmt = DB::query(Database::INSERT, 'INSERT INTO `claim_incentive_form_data` (`Claimant Name`, `Claimant Postcode`, `Purchase Order No.`, `Claimant Email Address`, `Storename`, `Storetown`, `Date of Sale`, `Date of Delivery`, `Tempur Acknowledgement No.`, `Tempur Product`)
VALUES (:claimantname, :claimantpostcode, :orderno, :email, :storename, :storetown, :dateofsale, :dateofdelivery, :acknowledgementno, :tempurproduct)');
$stmt->param(':claimantname', $post['claimantname']);
$stmt->param(':claimantpostcode', $post['claimantpostcode']);
$stmt->param(':orderno', $post['orderno']);
$stmt->param(':email', $post['email']);
$stmt->param(':storename', $post['storename']);
$stmt->param(':storetown', $post['storetown']);
$stmt->param(':dateofsale', $post['dateofsale']);
$stmt->param(':dateofdelivery', $post['dateofdelivery']);
$stmt->param(':acknowledgementno', $post['acknowledgementno']);
$stmt->param(':tempurproduct', $post['tempurproduct']);
try {
$stmt->execute();
$this->template->content->post = $post;
$this->template->content->thanks = true;
} catch (Exception $e) {
FB::error($e);
}
}
}
This sounds more like a MySQL issue rather than anything else. Make sure you have your Primary Key setup to auto increment. Try altering the table to add the auto increment feature:
ALTER TABLE [table name] MODIFY COLUMN [column name] [column type] PRIMARY KEY AUTO_INCREMENT;
In the above example. Replace the keys in brackets with their appropriate names. Replace [table name] with the name of your table, [column name] with the name of the column and [column type] with the type of the column (SMALLINT, INT, etc).
For more information, see this answer posted by roman.
For more information on the AUTO_INCREMENT feature, check out the MySQL Development Documentation here.
You need to add AUTO_INCREMENT to the primary key column on the table check this http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
you should be able to alter the table with something like this
ALTER TABLE claim_incentive_form_data CHANGE id id INT(10)AUTO_INCREMENT PRIMARY KEY;
Just make sure you change the id column and the datatype if yours are diffrent from that.
You have to set the auto_increment setting in the table within mysql.
ALTER TABLE `claim_incentive_form_data` MODIFY COLUMN `your_primary_column` int(4) PRIMARY KEY AUTO_INCREMENT
Refs:
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
http://dev.mysql.com/doc/refman/5.0/en/alter-table.html
you have to set form_id as primary key, auto increment and not null.
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.