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.
Related
I have this MySQL Structure:
CREATE TABLE Fields (
ID INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
ForUser VARCHAR(255) NOT NULL,
ForCategory VARCHAR(100) NOT NULL,
FieldName VARCHAR(100) NOT NULL
);
CREATE TABLE Content (
ID INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
ForUser VARCHAR(255) NOT NULL,
ForCategory VARCHAR(100) NOT NULL,
ForField VARCHAR(100) NOT NULL,
FieldContent VARCHAR(255) NOT NULL
);
Now I want to make SQL Query that list results in HTML Table. As Head Table I want to list FieldName from Fields, and as Table Body I want to list FieldContent from Content. Also in WHERE clause must be ForUser AND ForCategory... to list Content for each field. I'm tried with SQL Join, but I'm spend 3 hours without success. Can, please, someone write me an example how to display this.
If I understand this request correctly (you're a little light on detail), you will need a use a few components to achieve your goal:
Two sql queries (one for the table header and one for the table body)
Some php or another scripting language to display your results as html.
Your first query will just bring back the field names, filtered by user and category:
select ID, FieldName from Fields where ForUser = 'some_user' and ForCategory = 'some_category' order by ID;
IN your php or other code, you need to iterate through the results and display each result wrapped in the html tags, eg:
echo '<table><tr>';
$fields = # mysql_query ("select ID, FieldName from Fields where ForUser = 'some_user' and ForCategory = 'some_category' order by ID;", $connection);
while ($fields_result = mysql_fetch_assoc($fields)) {
echo '<th>' . $fields_result['FieldName'] . '</th>;
}
echo '</tr>';
Then run a second sql query to bring back the contents:
select
FieldContent
from
Content c join
Fields f on
c.ForField = f.FieldName and
c.ForUser = f.ForUser and
c.ForCategory = f.For Category
where
f.ForUser = 'some_user' and
f.ForCategory = 'some_category'
order by ID;
And in a similar fashion, iterate through the results in php to build the content rows in the table.
Note that I'm ordering on the PK in the Fields table to ensure that the content comes back in the same order as the fields. This approach might not suffice, you may need to add a "sequence" field if you need a specific field order.
Also note my prevous comment that you would do well to revise your database structure. You don't need to repeat all the fields in the Content table, you can just add a foreign key referencing the ID of the Field record
Table join query:
SELECT
a.ID,
a.ForUser,
b.ForUser,
a.ForCategory,
b.ForCategory,
a.FieldName,
b.ForField,
b.FieldContent
FROM
Fields a,
Content b
WHERE
a.ForUser = '' AND b.ForCategory = ''
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` )
I'm dealing with this problem. There is tableorders(oid,datetime,quantity,title,username,mid).
The table orders is updated from php code as far as the features oid,datetime,quantity,title,username are concerned. The problem is that I want to classify each entry based on both datetime and username so as to gather these entries under an order code in order to make an ordering entry. (I can't think of anything else at the moment).
The question is how can I select those entries that are corresponding to the same username and the same date time.
For example the if I have 3entries (freddo espresso,latte,freddoccino) belong to the same order procedure (are posted by the same username, tha exact same datetime) and I need to present them to my user as a completed order.
Here is the structure of table orders:
CREATE TABLE IF NOT EXISTS `orders` (
`oid` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`datetime` DATETIME NOT NULL,
`quantity` INT NOT NULL,
`sum` FLOAT(4,2) NOT NULL,
`title` VARCHAR(30) COLLATE utf8_unicode_ci NOT NULL,
`username` VARCHAR(30) COLLATE utf8_unicode_ci NOT NULL,
`mid` VARCHAR(30) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`oid`),
KEY `username`(`username`,`mid`,`title`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=10000;
The feature title is foreign key from table products:
CREATE TABLE IF NOT EXISTS `products`(
`title` VARCHAR(30) COLLATE utf8_unicode_ci NOT NULL,
`descr` TEXT(255),
`price` FLOAT(4,2) NOT NULL,
`popularity` INT NOT NULL,
`cname` VARCHAR(20) COLLATE utf8_unicode_ci NOT NULL,
`mid` VARCHAR(30) COLLATE utf8_unicode_ci NOT NULL ,
PRIMARY KEY(`title`),
KEY `cname` (`cname`, `mid`)
)ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=10000;
Sorry If I'm a little uncomprehensive, though I really need some help to come to a conclusion. Any ideas?
Thanks in advance!
If you know what the datetime value and the username values are then you can simply use:
SELECT * FROM orders WHERE username = '$username' AND datetime = '$datetime'
However, what you would be better off doing is splitting this into two separate tables; something like:
Orders
OrderID
OrderTime
UserName
Items
ItemID
OrderID
Title
Then you would search in the following way:
SELECT Orders.OrderID, Orders.UserName, Items.Title
FROM Orders
INNER JOIN Items ON Orders.OrderID = Items.OrderID
WHERE
Orders.UserName = '$username'
AND
Orders.OrderDate = '$datetime'
When adding orders you add a record to Orders first, and then use that OrderID and add it to each item inserted in Items...
Insert Example
$mysqli; //Assuming your connection to the database...
$items; //Assuming an array of items for the order like: array('Coffee', 'Tea')
$username; //Assuming the user name to be inserted for the order
$mysqli->query("INSERT INTO Orders(`OrderTime`, `UserName`) VALUES(NOW(), '$username')");
$orderid = $mysqli->insert_id;
foreach($items as $item){
$mysqli->query("INSERT INTO Items (`OrderID`, `Title`) VALUES($orderid, '$title')");
}
NOTE: You should make sure to sanitize data before inserting to database...
Storing JSON
Storing JSON in a database is going to require you to make sure that you use a field data type that is an appropriate length (e.g. a blob).
You mentioned that you retrieve the titles as an array from a form so I'm now going to refer to that as $titles.
Saving to database
$username = '...'; // Username or id to store in database with order
$titles = array(.....); // Array of titles from form
$encodedTitles = json_encode($titles); // Convert to JSON
$mysqli->query("INSERT INTO table_name (titles_field, username_field, date_field) VALUES ('$titles', '$username', NOW())"); // Save to database (assuming already open connection
Retrieve from database
$result = $mysqli->query("SELECT titles FROM table_name WHERE username = 'username_value' AND date_field = 'date_value'"); //Run query to get row
$row = $result->fetch_assoc(); // Fetch row
$titles = json_decode($row['titles']); // This is the same as the `titles` array from the from above!
SELECT quantity,title
FROM orders
WHERE username = ? and datetime = ?
Would return the quantity of items for a specific user on specific date. Instead of a date you could use an order id, which might be a bit safer. If you use order id, then username becomes irrelevant as well, since order ids should be unique.
The answer posted with the query will help you but you should also consider changing your table structure. Looks like you could have a table named orders and another one named orders_items. Then you could list all the itens from orders_itens matching a single order.
I think this query will return kind of data where you have the same unique_id string for records where username and datetime are the same.
SELECT MD5(a.unique_id), b.* FROM (
SELECT
GROUP_CONCAT(oid) unique_id, `datetime`, username
FROM `orders` GROUP BY username, `datetime`
) a
RIGHT JOIN `orders` b
ON a.`datetime` = b.`datetime` AND a.username = b.username
ORDER BY unique_id, oid;
I also have another answer for about 3 thousands characters long but I think this variant will help you more than my long tutorial how to split the table to two tables and how to migrate data into it + php code samples. So I decided not publicate it. )))
Edit: I think you even can run this one query which is easiest and works faster:
SELECT *, MD5( CONCAT( `username` , `datetime` ) ) unique_id
FROM `orders`
ORDER BY unique_id, oid;
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).
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.