I am trying to restrict users records display. Basically i am developing a CRM where a user logs in and enters (orders, quotes...) his data and submits to database. So when a user logs in i want to display only those records which he has entered not others data. For this I take user's session id and stores it infront of his records,
While displaying i am doing like this
"SELECT * FROM orders WHERE user_id='".$_SESIION['userID']."';
But i have to do this 'WHERE' for all display function . Instead of that is there any other way i can do this i mean without repetitive WHEREstatement?
Please suggest
Your question: is there any other way i can do this i mean without repetitive WHEREstatement?
My answer is: There is no!
Help for prepare: https://www.w3schools.com/php/php_mysql_prepared_statements.asp
The database could be like this, for example:
table users
id_user email password etc.
Table articles
id_article title_article body_article id_user etc
When you query
select * from article where id_users = ?
Use prepere
insert into articles (............, id_user, ....) values (?, ?, ? etc)
All tables, like this one article, can have field id_user, it goes in table with query input ...., by session and prepere protection against SQL injections. And when user select anything, he will have only what he has injected.
Related
I'm trying to add a function to a script that orders a list of users and then allows that same order SQL to be used to create an export file. I'm writing it for a piece of software that hosts basic user data in one table, and the question value I'm trying to get in another. Here's the details:
Table1 is base_user and from it I need the values of columns id, username, and email. However, I want to add the option to order/export by users with all that same data, but by their sex.
Table2 is base_question_data and from it I want to get the question 'sex' value.
Users can pick between Male or Female (Values: 1 or 2), and that info is stored in a column named intValue. I've already tried using INNER JOINS and such selecting multiple info from both tables, but where I'm getting confused is how to say "Get id, username, email, and sex for every user that is X sex" where "X sex" is the gender the user set to order/export by. I'm having a hard time figuring out how to get the specifics for the sex value for each user, but also use it to only show all those users of that value. All ideas are appreciated.
EDIT:
Forgot to mention that in the 'base_question_data' table, column 'userId' is equal to column 'id' in 'base_user' table.
This is Table1 or base_user
This is Table2 or base_question_data
To clarify what I'm trying to do:
In the 'base_user' table, I want to select ID, Username, and Email. I have this working normally, as it's a simple query. I want to, however, let users order by each user's gender. So
1)They can order the preview list by Male (questionName = sex intValue = 1) or Female (questionName = sex intValue = 2). This way, it will show all user's ID, Username, and Email who are gender 1 or 2. Using this same query, I'm trying to let them export that data as well, so they can export only users of gender 1 or 2.
My problem is the process of combining all of this data. I need to combine base_user's "id" to base_question_data's "userId" and I need to also get the value of each user by targeting base_question_data's questionName='sex' and get the intValue based on if they're ordering by Male (value=1) or Female (value=2).
I've done LEFT JOINS when combining one value to another for two tables, and while this is still two tables, I've never done it where I need to combine two different keys from two tables while also ordering them all by two different column values in one of those tables.
I agree with #rowmoin but if you use LEFT JOIN it will give null value if no entry in your base_question_data table and if you use INNER JOIN it will ignore those records from both tables which does not match so you can not get users from base_user if you do not have related entries in base_question_data table.
The query was easier than I anticipated. I will explain it in detail here.
To achieve something like this, (in which I needed one table's two values to decide what I'm getting in my other table results), I simply changed the value of 'intValue' in my query, but you can also do this by assigning a php value to let it be dynamically changed if you want. Since I'm doing a change between 1 or 2, I just have to different queries with the respective variable.
Here's my query:
SELECT * FROM ow_base_user
INNER JOIN ow_base_question_data ON ow_base_user.id = ow_base_question_data.userId
WHERE questionName='sex' AND intValue='$value';
I finally realized this morning I needed to go backwards, rather, and select my conditionals from base_question, rather than from the base_user table. Using this query, (where $value=1 for male or $value=2 for Female) I have successfully gotten to return a list of user's who match the set $value with their IDs, Username, and Email.
Suppose I have a MySQL table called "User".
ID, Name, Email, Age, Gender, Country, Hometown, City, Address, Relationship_Status, Employment_Status, IP, Registered_Time
Now, which query is more efficient to fetch all info of a user?
A)
SELECT * FROM User WHERE id=1
B)
SELECT ID FROM User WHERE id=1
SELECT Name FROM User WHERE id=1
SELECT Email FROM User WHERE id=1
SELECT Age FROM User WHERE id=1
SELECT Gender FROM User WHERE id=1
SELECT Country FROM User WHERE id=1
SELECT Hometown FROM User WHERE id=1
SELECT City FROM User WHERE id=1
SELECT Address FROM User WHERE id=1
SELECT Relationship_Status FROM User WHERE id=1
SELECT Employment_Status FROM User WHERE id=1
SELECT IP FROM User WHERE id=1
SELECT Registered_Time FROM User WHERE id=1
Thing is, depending on situation, I may or may not need all of the data. So, should I just fetch each data one by one when I need them or should I fetch all the data at once and then use as I need?
Thanks for helping!
A single query fetching multiple columns is almost always more efficient than multiple queries. Why? The query must be serialized by php, sent to the mySQL server, deserialized. Then the mySQL server has to do the WHERE operation to find the appropriate row or rows. Finally it has to serialize the results and send them back to php. The less you do all this, the less work the system has to do.
Pro tip: Don't use SELECT * . Instead enumerate the columns you want, like so.
SELECT ID, Name, Email, Employment_Status, Registered_Time
FROM Users
WHERE ID = 1
There are a lot of advantages to that approach, especially in queries that return many rows (which yours does not).
Each query to database costs something. PHP has to send the query to SQL server, the query analyzer has to parse your query, optimize it, translate it into some internal code, lookup the table, seek in the index file on the disk, seek in the data file on the disk.
The cost of selecting all columns at once using SELECT * is almost the same as cost of selecting a single column individually in one sql query.
When the data is read from the file on disk, it won't read just the 10 bytes you need, data from disk is always read in much bigger chunks by the operating system (like 4KB, it may depend).
Selecting one column like "SELECT Age ..." will read from disk the entire row anyway in vast majority of cases.
So to answer your question, SELECT * in your example will be more efficient since you'll go through the overhead of parsing a query just once.
I'm currently trying to retrieve values from a database.
New Users are given a UNIQUE ID once they register on my website:
Keys are stored into my database with a link such as:
website.com/file.php?id=4&key=123abcd123
What I was planning on having was the website pulling the keys ONLY related to the ID of the user.
Lets say User 4 inputs a key into the database, I want to have a universal .php file that will retrieve HIS codes (codes with the ID of 4) ONLY.
I'm sorry if this doesn't really make sense, English isn't my first language.
For finding particular record in mysql query pass the id value in the place of 4 below.
SELECT * FROM tablename WHERE UserID = '4'
if you want to get particular value then use like this
$query = "SELECT * FROM tablename WHERE UserID = '".$_SESSION['ID']."'";
Refference
If you use SQL, it is easy to search for all keys for a user:
select cdkey
from YourTable
where UserID = 1
Note that anyone can edit a URL. So unless you take additional measures, any user could ask for the cdkeys of any other user, just by modifying the id parameter in the URL.
So this is my sorta first time doing an Online RPG (MMORPG), It's a browser based-Pokemon game.
In the Database, l've created 2 tables;
1.Pokemons (Columns; ID#, PokemonName, PokemonType, Level, Exp, HPoints, ATT, DEF)
2.Users (Columns; ID, Full Name, E-Mail, Username, Password)
In the Register field, they put in their info (User, Pass, Email), then chooses a Starter Pokemon to fight with. My question is how would i interpret that into a SQL/PHP command that joins the starter pokemon to that User or vise versa?
Far as l know it's
SELECT * FROM table_name;
But let's say l wanted to choose THAT user who just registered. Would the * just automatically choose that player or will it select everything from the Users list (Currently 3 rows of users in the Table).
Im reading w3schools for the moment, but needed some real-time advice on how l should go about with this. Thanks again!
thepokemonrpg.x10.mx If you guys wanna see what l mean.
This would indeed select everything from the Users table:
SELECT * FROM Users
The * doesn't mean all records, it just means all columns for any matching record. However, since there's no filter, all records happen to be matching records. If you want to only select a single record from that table, you would add a WHERE clause:
SELECT * FROM Users WHERE Username='someusername'
There are a few different ways that you can construct the SQL query to include a value like that (since someusername would likely come from a variable and not be explicitly written like that). Just be aware of SQL injection vulnerabilities when building those queries. You wouldn't want to accidentally publish a website where users can write their own database code and execute it on your server.
As for joining the tables, I currently don't see a way that you could do that. These two tables define two distinct entities, but have no way to relate to one another. There are a couple of ways you could do that, depending on how these entities are actually related. To that end:
Does a Pokemon always have exactly 0 or 1 owner? or;
Does a Person always have exactly 0 or 1 Pokemon? or;
Can a Pokemon have many owners and a Person have many Pokemons?
If the first statement is true, then you can add a UserId column to your Pokemons table and make it a foreign key to the Users table. That way every Pokemon record would indicate which User owns it.
If the second statement is true, then you can add a PokemonId column to your Users table and make it a foreign key to the Pokemons table. That way every User record would indicate which Pokemon is currently owns.
If the third statement is true, then you'd need to add a joining table to maintain this many-to-many relationship. Something like this:
PokemonUsers
------------
Id
PokemonId
UserId
Every record in this table would essentially be a link between a record in the Users table and a record in the Pokemons table.
I'm currently working on my private messaging system for my website and so far some of what I have to do is making sense.
I've figured I have to use the power of mysql join but have a few questions..
In my model I have started coding for my message inbox and have the following query:
"SELECT * FROM messages WHERE from_id = '$id'";
$id is basically the auto-incremented id from my users table and from_id is the same thing but in my messages table.
What I want to know is how is the message table suppose to get the from_id? I know that the from_id from the messages table and the auto-incremented id from the users table are what I will use to link both tables.. but I'm slightly stuck how to go about this.
I would rather use id's to identify the sender and receiver of a message than their username but I'm quite confused how to go about setting this up. I'm quite certain I can do it once I have an understanding of it.
depending on what auth library you are using, you will need something like this in CI:
view_messages()
{
//this check could be done in the constructor
if($this->auth->logged_in()==TRUE)
{
$userID=$this->auth->user_data('userID');
}
else
{
redirect('not_logged_in');
}
$this->load->model('message');
$messages = $this->message->get_messages($userID);
// do what you want with messages.
//print_r($messages);
}
your messages model:
function get_messages($userID=null)
{
$this->db->where('userID', $userID);
$data = $this->db->get('tblMessages');
return $data->result();
}
I'm not quite sure if I fully understand you.
You are loading the messages, within the messages table you have a column for the user id but you want to load the users name aswell with a single query?
If so than something like this would do it
SELECT {whatever you want to have} FROM users
u, messages m WHERE u.id=m.from_id
than in your SELECT claus you can retrieve the users details with u.username assuming you have a username column in your users table.
Can't you use session to save the user id when the user login?
That way you can have the user id when needed.
// ...
$fromID = $_SESSION['uid'];
INSERT INTO `message` (`from_id`, `to_id`, `time`, `message`) VALUES('$fromID', '$toID', '$time', '$message')
Of course, we haven't talk about security here, so the code's obviously not secure. But we'll leave that for another discussion. Have I kicked you in the right direction? :p
There is more to it than just knowning a little about MySQL joins. There are lots of systems you can download to get a good idea, try phpBB or some other forum software.
With Private Message systems its very easy to make something rubbish, but good ones are tough.
Remember, if your message only has one entry like the example proivided by another user:
INSERT INTO `message` (`from_id`, `to_id`, `time`, `message`) VALUES('$fromID', '$toID', '$time', '$message')
That will need to show in the Inbox of the to user, and the sent box for the from user. If the to_user deletes it, the from_user suddenly has no record of the message.
You need to create a join table to list all the attachments of users (to or from) joined to the message id. Then you can have multiple to users as well!
Messages should always exist, users just "trash" (set is_trach to 1 on their connection). When users delete from trash they delete only their connection to the message, and when the last user has deleted their connection THEN you can delete it (or get a cron job to delete orphaned messages).