I'm trying to do a kind of friend request for my chat,
so I set a table called cyb_user_friendlist
then I've put some tables like that :
1 id_friendlist int(11) AUTO_INCREMENT
2 from int(11)
3 to int(11)
4 couple varchar(11)
5 accept int(11)
6 block int(11)
so for each friend request an insert is done to this table with id of sender into from and id of receiver into to, but to make sure that there is only one request per couple I added a field called couple in which there is the concatenation of from and to with a vertical separator |. this field has a uniq key because I want to prevent from multiple records.
the only thing is that it does not seems to work, actualy I added my uniq key to this fields and a primary key to the id_friendlist but it does not work, I can send many request as wanted...
my request $sql to do that is the one below :
$query = "INSERT INTO `cyb_users_friendlist` SET
`from` = {$from},
`to` = {$to},
`couple` = '{$from}|{$to}'";
I really do not know where I'm wrong...
anykind of help will be much appreciated.
$query = "INSERT INTO `cyb_users_friendlist` SET
`from` = $from,
`to` = $to,
`couple` = concat('$from','|','$to')'";
Why are you adding another field which is concatenated of two another when you can just add unique index?
mysql combined unique keys
ALTER TABLE `YOUR TABLE` ADD UNIQUE `unique` ( `from` , `to` )
Related
I try to update an existing table in mysql, but I get strange results, I explain my problem:
My table looks like this:
TABLE `myTable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`photoName` varchar(255) COLLATE latin1_general_ci NOT NULL,
`vote` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `photoName_2` (`photoName`),
)
and im trying to use saveVote.php that look like this:
$namePhoto = $_POST['name'];
$likePhoto = $_POST['like'];
mysql_connect("host","dbUser","psw");
mysql_select_db("db_is");
mysql_query("INSERT INTO `myTable` (`photoName`,`vote`) VALUES('$namePhoto','$likePhoto') ON DUPLICATE KEY UPDATE vote = vote + 1");
the 'vote' value is updated but every time when i call the "saveVote.php", for the first time he create an empty entry in my table with only the vote value and after, each time the "saveVote.php" is called
the vote value is updated for the right photoName but the vote value for the empty entry is also updated.
Why my request created this empty entry ?
Thanks for help.
It seems like your $namePhoto = $_POST['name']; is also returning a empty value. Try this:
if(!empty($_POST['name'])){
mysql_query("INSERT INTO `myTable` (`photoName`,`vote`) VALUES('$namePhoto','$likePhoto') ON DUPLICATE KEY UPDATE vote = vote + 1");
}
Keep in mind that this is just to test. This is not a fix. You need to figure out why you are sending a empty value.
I started developing chat application for my website.
First I did some javascript part, before I got to backend.
And Now just created database structure:
CREATE TABLE IF NOT EXISTS `wp_bp_my_chat` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`from` varchar(255) NOT NULL DEFAULT '',
`to` varchar(255) NOT NULL DEFAULT '',
`message` text NOT NULL,
`sent` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`recd` int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `to` (`to`),
KEY `from` (`from`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Now, having this databse, I want to make a request to see all messages grouped by "from" OR "To"
Think of it as facebook messages, when you go to actual page, there is a left sidebar with messages grouped by conversation.
the output should be like:
conversation between "user_1" and "user_2" (unread) 2 hours ago
conversation between "user_1" and "user_3" (unread) 3 hours ago
converstation between "user_1" and "user_5" 5 hours ago
so my messages are grouped like conversations.
I might have 10 message from user_2 but it should be displayed as one (and info from last one)
Any Ideas how I go next?
As I have not done any php side yet You can even suggest changing database to adjast for your solution.
Thanks.
I assume you would run this for one person ('user_1') for their conversations, which means they can be either the from or the to. I also assume that it make no difference if they are the from or the to, but to group by the other person in the conversation. If so, try this. (You should put some sample data in SQLFiddle for testing)
SELECT MostRecent.MainPerson AS MainPerson
, MostRecent.OtherPerson AS OtherPerson
, MostRecent.Sent AS Sent
, IF(wp_bp_my_chat.recd = 0, 'Unread','Read') AS Status
FROM wp_bp_my_chat
JOIN (
SELECT 'user_1' AS MainPerson
, IF(msgs.`from` = 'user_1',msgs.to, msgs.`from`) AS OtherPerson
, MAX(msgs.sent) AS sent
FROM wp_bp_my_chat AS msgs
WHERE msgs.`from` = 'user_1' OR msgs.`to` = 'users_1'
GROUP BY MainPerson, OtherPerson) AS MostRecent
ON (wp_bp_my_chat.`from` = MostRecent.MainPerson OR wp_bp_my_chat.`to` = MostRecent.MainPerson)
AND (wp_bp_my_chat.`from` = MostRecent.OtherPerson OR wp_bp_my_chat.`to` = MostRecent.OtherPerson)
AND MostRecent.sent = wp_bp_my_chat.sent
ORDER BY sent DESC
To get the results you described in your update, use:
SELECT count(*), max(sent)
FROM wp_bp_my_chat
WHERE to = 'name of recipient'
GROUP BY from
count(*) gives you the number of messages and max(sent) gives you the time of the latest message, which you can use to calculate the "hours ago" part of the output.
I don't see a flag in your table for whether the message has been read. You'd need to add that in order to add the "(unread)" text.
This can be done with a simple group by query:
SELECT * FROM `wp_bp_my_chat` WHERE `to` = {my_id} GROUP BY `from`
This will give you all the chats that I as a user have had.
Hey how would I be able to duplicate my only auto increment key to another key, basically I want my (' id ') to display the same information on my (' user_id '), here is the code:
CREATE TABLE IF NOT EXISTS `".$db_table_prefix."users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(10) NOT NULL,
`user_name` varchar(50) NOT NULL,
`username` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`id`)
How would I be able to input the same information from my id to my user_id?
Not sure what you mean but if you want to have the same value repeted two times in the same record It's pointless and redundant.
You can use the SQL aliases to achive what you want:
SELECT id as user_id FROM ...
If you really need to sync up the two field of your table you can do:
UPDATE table SET user_id = id WHERE user_id != id
Not sure why you would want to do this, but if you want to duplicate the information after an INSERT you would need to fetch the new ID and then perform an UPDATE
// get the newly inserted ID
$new_id = $db->insert_id;
// perform the update on the table
$db->query("UPDATE users SET user_id=".$db->escape($new_id)." WHERE id=".$db->escape($new_id));
Also, in your table definition the fields don't match: int(11) vs. int(10).
If I log in with my email and password in table 'students', how can I get the data from the table 'data' where the emailadresses match?
CREATE TABLE `students` (
`email` varchar(150) NOT NULL,
`password` varchar(150) NOT NULL
)
CREATE TABLE `data` (
`student_id` varchar(50) NOT NULL,
`studygroup_id` varchar(50) NOT NULL,
`applied_courses` varchar(50) NOT NULL,
`study_results` varchar(50) NOT NULL,
`email` varchar(150) NOT NULL
)
Well, the easy answer would just be to execute a query like
SELECT * FROM data WHERE email = '$emailAddress'
Where $emailAddress is the email address that has been used to log in.
But you should really think about your schema design. Perhaps go and read some books/tutorials on the basics and there are a number of possible issues with what you have. You should probably have a numeric primary key on your "students" table and reference this as a foreign key in your other table. You should also think about renaming the second table. "Data" doesn't really describe what it does; everything (or very nearly) in a database is data! Plus all your id columns are varchars. Unless you have alphanumeric ids you should make these columns the correct type for the data they hold.
Please clarify question. Where's the password coming from? A script in PHP?
SELECT * FROM data WHERE student.email = "$my_email" AND student.password = "$my_password"
Students table should also contain the student_id
alter table student add column student_id int auto_increment primary key
then the query
select a.email, a.password,b.studentgroup_id, b.applied_course,b.student_result
from student a inner join
data b
on a.student_id=b.student_id
If you want to confirm login and get data in one query, use a LEFT JOIN, which in the following example will give you a result from the students table, even if there is nothing in the data table for that email address.
$query = "SELECT * FROM `students`
LEFT JOIN `data` ON `students`.`email` = `data`.`email`
WHERE `students`.`password` = '" . $password . "'
AND `students`.`email` = '" . $email. "'";
Note: if there are multiple rows in the data table for the email address, each row will be returned and will contain identical student.password and student.email values.
I have created this database schema and with help from several users on here, I have a database which takes user submitted business entries stored in the business table, which are additionally grouped under one or several of about 10 catagories from the catagories table, in the tbl_works_catagories table by matching the bus_id to the catagory id.
For example, bus_id 21 could be associated with catagory_id 1, 2, 5, 7, 8.
CREATE TABLE `business` (
`bus_id` INT NOT NULL AUTO_INCREMENT,
`bus_name` VARCHAR(50) NOT NULL,
`bus_dscpn` TEXT NOT NULL,
`bus_url` VARCHAR(255) NOT NULL,
PRIMARY KEY (`bus_id`)
)
CREATE TABLE `categories` (
`category_id` INT NOT NULL AUTO_INCREMENT,
`category_name` VARCHAR(20) NOT NULL,
PRIMARY KEY (`category_id`)
)
CREATE TABLE `tbl_works_categories` (
`bus_id` INT NOT NULL,
`category_id` INT NOT NULL
)
Now, what i want to do next is a search function which will return businesses based on the catagory. For example, say one of the businesses entered into the business table is a bakers and when it was entered, it was catagorised under Food (catagory_id 1) and take-away (catagory_id 2).
So a visitor searches for businesses listed under the Food catagory, and is returned our friendly neighbourhood baker.
As with all PHP/MySQL, i just can't (initially anyway) get my head around the logic, never mind the code!
You should setup foreign keys in your tables to link them together.
CREATE TABLE `business` (
`bus_id` INT NOT NULL AUTO_INCREMENT,
`bus_name` VARCHAR(50) NOT NULL,
`bus_dscpn` TEXT NOT NULL,
`bus_url` VARCHAR(255) NOT NULL,
PRIMARY KEY (`bus_id`)
)
CREATE TABLE `categories` (
`category_id` INT NOT NULL AUTO_INCREMENT,
`category_name` VARCHAR(20) NOT NULL,
PRIMARY KEY (`category_id`)
)
CREATE TABLE `tbl_works_categories` (
`bus_id` INT NOT NULL,
`category_id` INT NOT NULL,
FOREIGN KEY (`bus_id`) REFERENCES business(`bus_id`),
FOREIGN KEY (`category_id`) REFERENCES categories(`category_id`)
)
Then your search query would be something like:
SELECT b.*
FROM business b, categories c, tbl_works_categories t
WHERE
b.bus_id = t.bus_id AND
c.category_id = t.category_id AND
c.category_id = *SOME SEARCH VALUE*
which using JOIN would be written as:
SELECT b.*
FROM business b
JOIN tbl_works_categories t
ON b.bus_id = t.bus_id
JOIN categories c
ON c.category_id = t.category_id
WHERE c.category_id = *SOME SEARCH VALUE*
Maybe you want something like this:
SELECT `bus_id` FROM `tbl_works_categories` WHERE `category_id` = *some id from the search*
AND `category_id` = *some other id from the search*;
Although you'd need those ids- there are a few ways to do this, I'll describe probably the most straight forward...
You get categories from $_POST, so let's just say you have 2 of them entered. (Food, and take-away). Parse these however you want, there are multiple ways, but the point is they're coming from $_POST.
execute this sort of thing for each one you find:
SELECT `category_id` FROM `categories` WHERE `category_name` LIKE '%*the name from $_POST*%';
Store these results in an array...based on how many you have there you can build an applicable query similar to the one I describe first. (Keep in mind you don't need and AND there, that's something you have to detect if you return > 1 category_id from the second query here)
I'm not going over things like security..always be careful when executing queries that contain user submitted data.
An alternate solution might involve a join, not too sure what that'd look like off the top of my head.
Good luck.
If you want all businesses that are related to the given category-id, your SQL-statement would look something like this:
SELECT `business`.`bus_name`
FROM `business`
WHERE `business`.`bus_id` = `tbl_works_categories`.`bus_id`
AND `categories`.`category_id` = `tbl_works_categories`.`category_id`
AND `categories`.`category_id` = 1;
Where 1 in this case is your food-category, but could be your PHP variable where the ID of the category the user selected is stored.
And one hint: Be sure to name your tables either in plurar or in singular. You are mixing both and could get confused.