I have a checkbox asking the user to put his/her favorite courses. I want to store all the selected courses in one column separated by delimiters in MySQL database
This is the way I insert it into mysql database. How should I be doing this?
$sql="INSERT INTO Students(FirstName, LastName,gender,Major,Favorite_courses,GPA,Date_of_reg)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[sex]','$_POST[major]','$_POST[favorite]','$_POST[GPA]',SYSDATE())";
$_POST[favorite] is the field in question.
$sql="INSERT INTO Students(FirstName, LastName,gender,Major,Favorite_courses,GPA,Date_of_reg) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[sex]','$_POST[major]','implode(\',\',$_POST[\'favorite\'])','$_POST[GPA]',SYSDATE())";
If you REALLY want to put all favorite courses into a single field, you can make this field a string, and store the PHP array in it by serializing it. You can use the serialize() function, or JSON, json_encode(), or any other similar method. To retrieve the data, just use unserialize(), or json_decode(), and you will have your array back in PHP.
But keep in mind that using a SELECT statement to filter who likes course foo or course bar, will be quite dificult. The best approach is to follow jeroen's suggestion, normalizing your data.
Well, for security and normalization reasons you shouldn't do that.
However, you can do it, if you really want to by using the function serialize() of php.
$myFavorites = serialize($_POST[favorite]);
$sql="INSERT INTO Students (FirstName, LastName, gender, Major, Favorite_courses, GPA, Date_of_reg) VALUES
('$_POST[firstname]' ,'$_POST[lastname]' ,'$_POST[sex]' ,'$_POST[major]', '$myFavorites', '$_POST[GPA]', SYSDATE())";
You'll be able to unserialize it after you got it from your database with
$serializedCourses = myFunctionToGetItFromMyDatabase();
$unserializedCourses = unserialize($serializedCourses);
What I would do would be to create another table in your database for the Courses, and link it to the user via the user's id.
For example you could create as much columns as there is type of courses, and that will make you able to get easily the list of people who like Maths (for example) or even Maths and Geometry.
You won't be able to do that with your solution easily.
Related
I have created a website (you don't want to see that). Now i want to input students details there. I created a tiny table for testing, only 3 rows - firstname, lastname, age.
I created a simple HTML form and a PHP script, now I can input data and save there easily.
Now the problem is I don't seem to find an easy way to update data.
I have some knowledge in Oracle database, forms and reports. I was thinking to populate HTML forms from MySQL data (similar to Oracle Forms) and update and save. I did not find a way to do that. I searched Google and got some complicated long code, did not understand properly.
If possible, please give me the simplest way (no validation, no security check, etc) to do that.
Since you provide no code of your website, I can only assume that you are using a query to insert data into the database? Should be something like:
$query = "INSERT INTO table_name VALUES (value1,value2,...)";
To update, you can use the same type of form, except the query would be:
$query = "UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE some_column = some_value";
You can find more information here: http://www.w3schools.com/sql/sql_update.asp
If you want more help, show us more code and tell us what the column names are in the database. I can the provide exact variables to put in the query.
I'm new to SQL and PHP. Maybe I don't understand what you will answer, so please explain it fully that I can understand so here's my question
I have 5 columns: Id, Name, UserName, Password, valuie
You can understand 4 columns, the fifth is valuie means what the user want to give in wish list. Now when user select a thing and add into wish list, that's good but when he/she adds 2 things in his wish list, how to put that in valuie? how can I display 1st and 2nd value? I mean if I want to display 1st one and if 2nd and if both, what I can do about it?
My PHP is good but MySQL is not good....
Code
Insert into user(Name, UserName, Password, Valuie)
Values("bla bla", "blabla", "blabla", "here's 1st value", "here's second");
This seems like something that should be handled by a one-to-many relationship. A user can have many items in his wishlist. This means that you will need to split your current table up into two. Example: A user table and a wish list table:
user: id, name, etc.
wishlist: id, item_name, user_id
Whenever the user adds a new wish list item, it should be added to the wishlist table, keyed by his/her user_id.
Seeing as you are new to MySQL, you should make sure that you read up on the concept of database normalization.
you can use explode function for it, here is a example below, which will make you easier to understand..
suppose you have a field in your db as value=(value1,value2)
now you can fetch both of the these values one by one as following..
$data=explode(',',value);
//An Explode function gives you an array,
//by which you can get any desired value just by passing it's index.
$data1=$data[0];
$data2=$data[1];
Hopefully this would help you.
Thanks.... :)
For that you can use simple technique. Create two columns Value1 and Value2. If user select first value then store it in Value1 and when user select second the store this value in Value2. Before performing this check if the Value1 field is Null in Database. If not then put that value to Value2.
You can also display both values on different location, if you want.
Please advise how to do this php mysql form and data insert.Already searched on this site and couldn't find any question regarding this.
I have a form that collects student information - student_info(fields: id, name, sex, dob). I can insert this to a table. Now I would like to create two other tables like this
male_students (id, student_info_id, male_names)
female_students (id, student_info_id, female_names).
My idea for these two separate tables is because I can show the list of male and female easily by a SELECT query.
To do this, I thought I can do this but I am not sure how and if this is even a right approach.
for example I have a script called form_submit.php - this has the form
filling and submitting the form would insert data into student_info tables.
when doing the step 2, I would like to check if ($sex == male) or (if $sec==female), do a insert into male_students and female_students respectively.
but I am stuck
should i just write three individual queries inside the
form_submit.php ?
how to get the student_info_id for these two
tables. I thought of LAST_INSERT_ID but I am confused what will
happen if two users fill out the form at same time. So how to
approach this?
If this is not even a right way to approach, how to populate the data for those two tables?
Please advise.
regards
There is absolutely no reason to split "males" and "females" into their own tables in this scenario. (And I'm at a loss to imagine any scenario where it would make sense.)
The entity you're storing is, for lack of a better term, a Person. (User, Individual, etc. could be used in this context as well. Stick with whatever language is appropriate for the domain.) So a Person is a record in a table. Gender is an attribute of a Person, so it's a data element on that table. A highly simplified structure to convey this might be:
Person
----------
ID (integer)
GivenName (string)
FamilyName (string)
Gender (enumeration)
The Gender value would simply be a selected value from whichever possible options are available. Such options might include:
Male
Female
Unknown
Undisclosed
There are medical cases where there may be even more options, and psychological cases may indeed further add to the set. But for most domains that might be covered by "Unknown" or "Undisclosed" (or perhaps "Other" as an option, though that might look strange on the form to the vast majority of users).
To select this information, you'd simply add a WHERE clause to your query. Something like this:
SELECT * FROM Person WHERE Gender=1
If 1 maps to, for example, Male then this would select all Persons who have a Gender attribute of Male.
I'm trying to figure out how and which is best for storing and getting multiple entries into and from a database. Either using explode, split, or preg_split. What I need to achieve is a user using a text field in a form to either send multiple messages to different users or sharing data with multiple users by enter their IDs like "101,102,103" and the PHP code to be smart enough to grab each ID by picking them each after the ",". I know this is asking a lot, but I need help from people more skilled in this area. I need to know how to make the PHP code grab IDs and be able to use functions with them. Like grabbing "101,102,103" from a database cell and grabbing different stored information in the database using the IDs grabbed from that one string.
How can I achieve this? Example will be very helpful.
Thanks
If I understand your question correctly, if you're dealing with comma delimited strings of ID numbers, it would probably be simplest to keep them in this format. The reason is because you could use it in your SQL statement when querying the database.
I'm assuming that you want to run a SELECT query to grab the users whose IDs have been entered, correct? You'd want to use a SELECT ... WHERE IN ... type of statement, like this:
// Get the ids the user submitted
$ids = $_POST['ids'];
// perform some sanitizing of $ids here to make sure
// you're not vulnerable to an SQL injection
$sql = "SELECT * FROM users WHERE ID IN ($ids)";
// execute your SQL statement
Alternatively, you could use explode to create an array of each individual ID, and then loop through so you could do some checking on each value to make sure it's correct, before using implode to concatenate them back together into a string that you can use in your SELECT ... WHERE IN ... statement.
Edit: Sorry, forgot to add: in terms of storing the list of user ids in the database, you could consider either storing the comma delimited list as a string against a message id, but that has drawbacks (difficult to do JOINS on other tables if you needed to). Alternatively, the better option would be to create a lookup type table, which basically consists of two columns: messageid, userid. You could then store each individual userid against the messageid e.g.
messageid | userid
1 | 1
1 | 3
1 | 5
The benefit of this approach is that you can then use this table to join other tables (maybe you have a separate message table that stores details of the message itself).
Under this method, you'd create a new entry in the message table, get the id back, then explode the userids string into its separate parts, and finally create your INSERT statement to insert the data using the individual ids and the message id. You'd need to work out other mechanisms to handle any editing of the list of userids for a message, and deletion as well.
Hope that made sense!
Well, considering the three functions you suggested :
explode() will work fine if you have a simple pattern that's always the same.
For instance, always ', ', but never ','
split() uses POSIX regex -- which are deprecated -- and should not be used anymore.
preg_split() uses a regex as pattern ; and, so, will accept more situations than explode().
Then : do not store several values in a single database column : it'll be impossible to do any kind of useful work with that !
Create a different table to store those data, with a single value per row -- having several rows corresponding to one line in the first table.
I think your problem is more with SQL than with PHP.
Technically you could store ids into a single MySQL field, in a 'set' field and query against it by using IN or FIND_IN_SET in your conditions. The lookups are actually super fast, but this is not considered best practice and creates a de-normalized database.
What is nest practice, and normalized, is to create separate relationship tables. So, using your example of messages, you would probably have a 'users' table, a 'messages' table, and a 'users_messages' table for relating messages between users. The 'messages' table would contain the message information and maybe a 'user_id' field for the original sender (since there can only be one), and the 'users_messages' table would simply contain a 'user_id' and 'message_id' field, containing rows linking messages to the various users they belong to. Then you just need to use JOIN queries to retrieve the data, so if you were retrieving a user's inbox, a query would look something like this:
SELECT
messages.*
FROM
messages
LEFT JOIN users_messages ON users_messages.message_id = messages.message_id
WHERE
users_messages.user_id = '(some user id)'
I have a database that has a users first and last name. Some cases i display the users full name, but in other cases i just show the first name. i have a function that gathers user information.
within the function, i use an sql query to gather the first and last name, but i also concat the first and last name and label it full_name.
Example..
$q = "SELECT first_name, last_name, CONCAT_WS(' '. first_name, last_name) AS full_name
/* A lot of other information */
FROM users WHERE user_id=$user_id";
My question is, is this too much, is it unnecessary to get the same data in different forms straight out of the database, or would it be better to just take the first and last name from the database and then concat afterward in php like so...
echo $user['first_name'].' '.$user['last_name'];
I would just use the database for information storage and retrieval as much as possible, and leave things like the "full name" (which is really probably used only for display purposes) to the application, i.e. php logic.
It doesn't really matter. Setting one variable takes a small fraction of a second either way. If you're expecting lots of requests, then setting it in MySQL will be faster, as when you do it in PHP, it has to search for the array key in the returned array and set that value to a variable. If you set it in MySQL, you just use the value straight out of the array without the in-between steps.
Unless you're getting a HUGE volume of people requesting that data however, you won't notice a difference.