如何从不同用户的mysql检索记录

问题描述:

我正在使用php和mysql数据库制作预订系统.该系统有多个用户可以登录并进行预订,因此我想知道一种基于用户会话选择记录的方法.目前,它仅选择所有预订记录,这意味着用户可以访问所有预订.

I am making a booking system using php and mysql database. The system has multiple users who can log in and make bookings so i want to know a way of selecting records based on users sessions. At the moment its only selecting all booking records which means users have access to all bookings.

我有一个包含预订记录的预订表和一个带有用户凭证的用户表.还有一种从这两个表中选择记录的方法

I have a booking table which has booking records and a users table with users credentials.Is there also a way for selecting records from both tables

在用户表上,您应该具有唯一的ID.

On your users table, you should have a unique id.

在您的预订表上,您有一个现场用户ID.添加预订时,会将用户ID保存在该字段中.

On your bookings table, you have a field user id. When you add a booking, you save the user id in to that field.

然后,当您要检索预订时,选择与特定用户ID匹配的记录.

Then, when you want to retrieve bookings, you select records matching the specific user id.

在预订表上具有用户ID的字段称为外键.它是您使用sql进行大量操作的基础.以这种方式进行设置可以使您执行称为 join 的操作.在这里,您可以从两个或多个表中获取所有数据,并根据行的键值组合行.因此,在您的情况下,您可以执行以下操作:

Having a field for user id on the bookings table is called a foreign key. It's the basis for a lot of what you do with sql. Setting it up this way allows you to do what's called a join. This is where you get all the data from two or more tables, with the rows combined based on their key values. So in your case you could do something like this:

SELECT * FROM users,bookings WHERE bookings.id=users.id;

这将为您提供包含所有预订数据以及进行该预订的用户的所有用户数据的记录.您也可以这样做:

This will give you back records that have all the booking data, and all the user data for the user who made that booking. You could also do:

SELECT * FROM bookings where users.id=3;

哪个可以为您提供ID为3的用户的所有预订数据.

Which would give you all the booking data for the user with id 3.

您还可以在其他字段上进行匹配,但是保留该外键作为联接,以确保您始终在预订和用户之间获得正确的链接.

You can also match on other fields, but keep that foreign key as the join to guarantee that you always get the correct link between bookings and users eg.

SELECT * FROM users,bookings WHERE users.surname="Doe" AND bookings.id=users.id;

您也可以反向使用它-例如,如果要获取给定日期所有预订的用户的详细信息,则可以执行以下操作:

You can use it in reverse too - for example, if you want to get the user details for everyone who has a booking on a given date, you could do something like this:

SELECT * FROM users WHERE bookings.date='03/03/2015' AND users.id=bookings.id;

如您所见,将用户ID添加到Bookings表中将带来很多可能性,因为它将数据链接在一起,即使您将数据拆分为多个表,也可以将其作为一条记录获得.

As you can see, adding that user id to the bookings table opens up a lot of possibilities because it links your data together, allowing you to get data as a single record even if it's split over multiple tables.