I am currently creating a website through Joomla (creating a module) that is a members only site.
When members log in, I would want them to see their points (think about it like an airline flyer points site) which are unique. I have stored the points in a table in the database.
I have two tables:
#__users (the basic user table)
#__smiles_users (this stores the username, points etc etc)
Both tables have one similar column and this is "username".
I thought it would be wise to do it like this in an MYSQL query.
Connect to MYSQL
Find out the username that is logged in through #__users
Find the matching username in #__smiles_users table
Echo results that are in that specific row (that contains the correct username)
I have connected to MYSQL, echo the results, but I had to specify the WHERE function.
There are two main approaches to accomplish this:
You can perform two separate queries for every table and join them via a PHP associative array:
SELECT * FROM `__users` WHERE `username` = ?
And store the result to a var:
$user = $result->fetch();
Then do a second query for the remaining data of such user:
SELECT * FROM `__simles_users` WHERE `username` = ?
And join the data programatically like this:
$user_smiles_data = $result->fetch();
foreach($user_smiles_data as $key => $value) {
$user[$key] = $value;
}
Or something like this if you don't want to perform two different queries:
SELECT * FROM `__users`
INNER JOIN `__smiles_users`
ON `__users`.`username` = `__smiles_users`.`username`
This merges both tables by the username field at query time. The result will include all the fields of the two tables on a single row for the same username.
You are probably going to want to create a foreign key from one table to the other.
For example in SQL:
ALTER TABLE #__smiles_users
ADD FOREIGN KEY (username)
REFERENCES #__users(username)
This creates a link from one table to the other to ensure data integrity.
Related
I would like to link two SQL tables together, both the tables have data entered in them through HTML/PHP forms.
The first table is where the user enters all their details into a form (called system), and the second table is for where a user fills out another form for booking (called users). How do I link these tables together? To show the users booking(s).
I don't know how to get the booking table/form to echo out the user's username into the second table to link them together?
I understand that this does not make sense but would really appreciate some help!!!
Here is the first table's SQL for creating a user account:
And, here is the SQL for creating a booking?:
</form>
</body>
</html>
<br></br>
</div>
</div>
</div>
</body>
</html>
Here is the code that links what the user entered for the booking form (system table) to the SQL database.
Two tables can be "linked" together using JOIN. If you want to list the bookings (rows in the details table), with some user information, you can use LEFT OUTER JOIN or INNER JOIN. (The difference is that with LEFT OUTER JOIN you get all the bookings even if some of them don't have a user. With INNER JOIN you get only the bookings where there exists a corresponding row in users.)
If a column has the same name in two different tables, you can use users.user_uid and details.user_uid to refer to them.
SELECT details.*, user.email, user.first, user.last
FROM details LEFT OUTER JOIN user ON user.user_id = details.user_uid;
Then you maybe want to add a WHERE or ORDER BY and perhaps a LIMIT.
In the users table, there is a user_id (INT) and a user_uid (VARCHAR). The details table has a user_uid (INT). In the example, I was assuming that the user_uid in the details table corresponds to the user_id in the users table because these are both INT. You might want to change the name of some column to make it less confusing. Let's assume you want to rename users.user_uid to "username".
Also, you should add a unique index on the user_id and username, assuming that you want both of them to be unique. For the INT, I suggest you make this the primary key with automatically incrementing numbers and the username, just a unique key:
CREATE TABLE users (
user_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
... ,
username VARCHAR(20) NOT NULL UNIQUE,
...
);
In the details table you probably also want to make the ID a PRIMARY KEY with AUTO_INCREMENT.
A unique key guarantees that there are no duplicates and it also makes lookups on these columns efficient.
If you are just trying to query them together a join should do the trick.
SELECT users.user_first, users.user_last, users.user_email, system.* FROM system INNER users JOIN ON users.user_uid = system.user_uid
In order to store the user_uid value in the system table you need to add a hidden input in your form like this:
<input type="hidden" name="uid" value="<?php echo $_SESSION['u_id']; ?>">
then in your php add
$user_uid = $_POST['uid'];
and insert it when you run your insert query.
INSERT INTO system (date, time, table_layout, user_uid) VALUES ('$date', '$time', '$table_layout', '$user_uid');
Just make sure that your table actually has that column. Once that value is available you should be able to run the above join query.
Let's see. You have two tables, one with user data (users), and one with booking data (details). A "details" row contains an ID of the user linked to that particular row.
Once you know, at least, the ID of the booking, you can get the id of the user like this:
SELECT user_uid FROM details WHERE ID = #specificBookingID
Once you know the user id you can get the user data:
SELECT * FROM users where user_uid = #retrievedUserID
You can do it in one query like so:
SELECT * FROM users where user_uid IN (SELECT user_uid FROM details WHERE ID = #specificBookingID)
I want to use multiple database because I have 1 database which contain 40 tables and it doesnt seem good.Thats why I want to create another database but problem is I am not able to join this databases at one query for example
I have 'core' database and it contains users table which has user_id column
second database is post database and I need get user_id from users table which is in 'core' database like below
SELECT post_message from posts where 'core'.user_id=123
is that possible?or should I stick with one database?I have also foreign key problem which is related with database relation.
If it is SQL SERVER Product, You can call the Object residing on another DB like below
SELECT * FROM [DB_NAME].[Schema_Name].[Table_NAME]
For Example:
SELECT * FROM DB1.dbo.Employee
For MySQL : Please go through the below ans
Select columns across different databases
I have two database tables that I am using to create a Twitter-style following system.
sh_subscriptions
=> id
=> user_id
=> feed_id
sh_feeds
=> id
=> item
=> shop_name
=> feed_id
The problem with storing feed_id rather than shop_name in sh_subscriptions is that it requires a lot of table joining:
$id = $_POST['id'];
$user_id = $id['id'];
$shop_name = mysqli_escape_string($con, $_POST['shop_name']);
$query = "SELECT * FROM sh_subscriptions s INNER JOIN sh_feeds f ON s.feed_id = f.feed_id WHERE s.user_id = $user_id AND f.shop_name = '$shop_name'";
$result = mysqli_query($con, $query) or die(mysqli_error($con));
if (mysqli_num_rows($result) > 0)
{
$query2 = "DELETE FROM sh_subscriptions s INNER JOIN sh_feeds f ON s.feed_id = f.feed_id WHERE s.user_id = $user_id AND f.shop_name = '$shop_name'";
$result2 = mysqli_query($con, $query2) or die(mysqli_error($con));
}
else
{
// insert the row instead
}
(I know there's an error somewhere in the if statement, but I'll worry about that later.)
If I were to replace feed_id with shop_name, I would be able to replace line 5 with this:
$query = "SELECT * FROM sh_subscriptions WHERE user_id = $user_id AND shop_name = '$shop_name'";
My question is: is it always preferable to store MySQL values as integers where possible, or in a situation like this, would it be faster to have sh_subscriptions contain shop_name rather than feed_id?
Your sh_subscriptions table is actually a many-to-many join table that relates users to feeds. This is considered a fine way to design database schemas.
Your basic concept is this: you have a collection of users and a collection of feeds. Each user can subscribe to zero or more feeds, and each feed can have zero or more subscribers.
To enter a subscription you create a row in the sh_subscriptions table. To cancel it you delete the row.
You say there's "a lot of table joining." With respect, this is not a lot of table joining. MySQL is made for this kind of joining, and it will work well.
I have some suggestions about your sh_subscriptions table.
get rid of the id column. Instead make the user_id and feed_id columns into a composite primary key. That way you will automatically prevent duplicate subscriptions.
add an active column ... a short integer ... to the table. When it is set to a value of 1 your suscription is active. That way you can cancel a subscription by setting active to 0.
you might also add a subscribed_date column if you care about that.
create two compound non unique indexes (active,user_id,feed_id) and (active,feed_id,userId) on the table. These will greatly accelerate queries that join tables like this.
Query fragment:
FROM sh_feed f
JOIN sh_subscription s ON (f.feed_id = s.feed_id AND s.active = 1)
JOIN sh_users u ON (s.user_id = u.user_id)
WHERE f.shop_name = 'Joe the Plumber'
If you get to the point where you have hundreds of millions of users or feeds, you may need to consider denormalizing this table.. that is, for example, relocating the shop name text so it's in the sh_subscriptions table. But not now.
Edit I am proposing multiple compound covering indexes. If you're joining feeds to users, for example, MySQL starts satisfying your query by determining the row in sh_feeds that matches your selection.
It then determines the feed_id, and random-accesses your compound index on feed_id. Then, it needs to look up all the user_id values for that feed_id. It can do that by scanning the index from the point where it random-accessed it, without referring back to the table. This is very fast indeed. It's called a covering index.
The other covering index deals with queries that start with a known user and proceed to look up the feeds. The order of columns in indexes matters: random access can only start with the first (leftmost) column of the index.
The trick to understand is that these indexes are both randomly accessible and sequentially scannable.
one other note If you only have two columns in the join table, one of your covering indexes is also your primary key, and the other contains the columns in the reverse order from the primary key. You don't need any duplicate indexes.
I have three tables, the first is a table storing applications, the second is a table storing different online forms (different types of applications), the third is a table that stores actual form data:
TABLE applications=========
-applicationID (PK)
-formID (FK)
-formRecordID
====================
TABLE forms=========
-formID (PK)
-formName
-tableName (could be 'form_businessLicense','eventLicense',etc)
====================
TABLE form_businessLicense=====
-recordID (PK)
-dateSubmitted
-(a whole bunch of other data)
===============================
"formRecordID" points to "recordID" in "form_businessLicense" or "eventLicense". Since it could reference any table, it can't be a foreign key. So instead I grab the tableName from the "forms" table, then build a query to get all the application data from, say "form_businessLicense".
So I need to get data from, say, all applications plus a bit of data from the application form filled out (ex:form_businessLicense). I'm just going to paste my code (I'm actually querying all applications in a given set of IDs):
$applications = $this->selectAll(
"SELECT applicationID, formName, tableName, fieldIdentifier, formRecordID, dateSubmitted, DATE_FORMAT(dateSubmitted,'%c/%e/%Y') AS dateSubmittedFormat
FROM applications AS a
JOIN forms AS f
ON a.formID = f.formID
WHERE a.applicationID IN (".$applicationIDs.")
ORDER BY dateSubmitted ASC"
);
for($a=0;$a<count($applications);$a++){
$form = $this->select("SELECT ".$applications[$a]['fieldIdentifier']." AS identifierName
FROM ".$applications[$a]['tableName']."
WHERE recordID = ".$applications[$a]['formRecordID']
);
$applications[$a]['identifierName'] = $form['identifierName'];
}
Is there any way to merge these two queries into one so I don't have to loop over all results and run a separate query for each result? I feel like I could maybe do this with a JOIN but I'm not sure how to reference the "tableName" and "formRecordID" for use in the same SQL statement.
You need to apply join to three tables, and select count(PK) of third table while adding a group by clause for the PK of third table.
Note: PK used for Primary Key
I have a table for users. But when a user makes any changes to their profile, I store them in a temp table until I approve them. The data then is copied over to the live table and deleted from the temp table.
What I want to achieve is that when viewing the data in the admin panel, or in the page where the user can double check before submitting, I want to write a single query that will allow me to fetch the data from both tables where the id in both equals $userid. Then I want to display them a table form, where old value appears in the left column and the new value appears in the right column.
I've found some sql solutions, but I'm not sure how to use them in php to echo the results as the columns in both have the same name.
Adding AS to a column name will allow you to alias it to a different name.
SELECT table1.name AS name1, table2.name AS name2, ...
FROM table1
INNER JOIN table2
ON ...
If you use the AS SQL keyword, you can rename a column just for that query's result.
SELECT
`member.uid`,
`member.column` AS `oldvalue`,
`edit.column` AS `newvalue`
FROM member, edit
WHERE
`member.uid` = $userId AND
`edit.uid` = $userId;
Something along those lines should work for you. Although SQL is not my strong point, so I'm pretty sure that this query would not work as is, even on a table with the correct fields and values.
Here is your required query.
Let suppose you have for example name field in two tables. Table one login and table 2 information. Now
SELECT login.name as LoginName , information.name InofName
FROM login left join information on information.user_id = login.id
Now you can use LoginName and InofName anywhere you need.
Use MySQL JOIN. And you can get all data from 2 tables in one mysql query.
SELECT * FROM `table1`
JOIN `table2` ON `table1`.`userid` = `table2`.`userid`
WHERE `table1`.`userid` = 1