Multiple values for one column PHP and SQL - php

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.

Related

Selecting data for each user from multiple tables

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.

inserting form data into mysql

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.

MySQL Remove/Combine Similar Rows

I've got a problem that I just can't seem to find the answer to. I've developed a very small CRM-like application in PHP that's driven by MySQL. Users of this application can import new data to the database via an uploaded CSV file. One of the issues we're working to solve right now is duplicate, or more importantly, near duplicate records. For example, if I have the following:
Record A: [1, Bob, Jones, Atlanta, GA, 30327, (404) 555-1234]
and
Record B: [2, Bobby, Jones, Atlanta, GA, 30327, Bob's Shoe Store, (404) 555-1234]
I need a way to see that these are both similar, take the record with more information (in this case record B) and remove record A.
But here's where it gets even more complicated. This must be done upon importing new data, and a function I can execute to remove duplicates from the database at any time. I have been able to put something together in PHP that gets all duplicate rows from the MySQL table and matches them up by phone number, or by using implode() on all columns in the row and then using strlen() to decide the longest record.
There has got to be a better way of doing this, and one that is more accurate.
Do any of you have any brilliant suggestions that I may be able to implement or build on? It's obvious that when importing new data I'll need to open their CSV file into an array or temporary MySQL table, do the duplicate/similar search, then recompile the CSV file or add everything from the temporary table to the main table. I think. :)
I'm hoping that some of you can point out something that I may be missing that can scale somewhat decently and that's somewhat accurate. I'd rather present a list of duplicates we're 'unsure' about to a user that's 5 records long, not 5,000.
Thanks in advance!
Alex
If I were you I'd give a UNIQUE key to name, surname and phone number since in theory if all these three are equal then it means that it is a duplicate. I am thinking so because a phone number can have only one owner. Anyways, you should find a combination of 2-3 or maybe 4 columns and assign them a unique key. Once you have such a structure, run something like this:
// assuming that you have defined something like the following in your CREATE TABLE:
UNIQUE(phone, name, surname)
// then you should perform something like:
INSERT INTO your_table (phone, name, surname) VALUES ($val1, $val2, $val3)
ON DUPLICATE KEY UPDATE phone = IFNULL($val1, phone),
name = IFNULL($val2, name),
surname = IFNULL($val3, surname);
So basically, if the inserted value is a duplicate, this code will update the row, rather than inserting a new one. The IFNULL function performs a check to see whether the first expression is null or not. If it is null, then it picks the second expression, which in this case is the column value that already exists in your table. Hence, it will update your row with as much as information possible.
I don't think there're brilliant solutions. You need to determine priority of your data fields you can rely on for detecting similarity, for example phone, some kind of IDs, of some uniform address or official name.
You can save some cleaned up values (reduced to the same format like only digits in phones, concatenated full address) along with row which you would be able to use for similarity search when adding records.
Then you need to decide on data completeness in any case to update existing rows with more complete fields, or delete old and add new row.
Don't know any ready solutions for such a variable task and doubt they exist.

Keeping track of dynamically generated form elements and passing them as POST variables

I have a page that retrieves records from 1 table in a database when a certain condition is met.
What I want to achieve is to provide the use to with an opportunity to update each record displayed using text boxes.
I am having trouble interpreting what logic to proceed with after the user hits the 'submit' button.
Normally, if I'm updating one record (or a static number of records), I will use the apporpriate amount of SQL statements.
Since the amount of records are dynamically generated, what is the best way to update all at once? How would I know which records were retrieved in the first place to update?
FOR EXAMPLE:
OK, We have a table with student ids (ID), names (SNAME), subjects (SUBJ), grade for each subject (GRADE) and general remarks (COMMENTS).
I want to retrieve information about all students that got an 'A', and write UNIQUE congratulatory remarks for each student (such as 'good job', or 'congratulations', or etc.)
I'd retrieve the records and lay them out on the page, with a text box next to each student record for the comments to be entered. Because I don't know how many text boxes to make, I give the text boxes dynamically generated names using the student ID. The user now enters unique comments for each student, and clicks on submit.
Now, how am I supposed to update these records with the values entered in each text box?
I wouldn't know which students were retrieved in the first place - how would I know what names to use? I'm trying to avoid having to execute the query again after submitting - but is there any other way?
Hope this question was not too confusing.
thanks
Further expanding earlier answers:
You need a loop (e.g. foreach) to display and save the textareas. If the names of the textareas include the students ID, you don't need to know the name, because the text is inserted to the database by the primary key (the students ID). You may name your form-elements as array, to iterate over them, for example (where the numbers are the IDs):
<textarea name="comment[2345234]"></textarea>
<textarea name="comment[8957485]"></textarea>
Read it out as described by #evan:
foreach((array)$_POST['comment'] as $studentId => $studentComment)
{
var_dump($studentId, $studentComment);
}
And if you implement this whole thing as self-requesting form (Affenformular in german), you may also use just one single loop to save and output the textareas.
"I don't think you're understanding what I'm trying to ask." Maybe you don't understand the answers, even you stated it. You don't need a students name to save a database record. But if you really want to submit it, you may also use hidden inputs.
Use foreach() to find the values you care about, put them in an array, and process the array.
Expanding on #Ignacio's answer to make it more easily understandable:
foreach($_POST as $name_of_input => $value_of_input)
{
// do stuff - here is something so you can see the results after the submit
echo "$name_of_input :: $value_of_input <br>";
}

PHP, MySQL: mysql substitute for php in_array function

Say if I have an array and I want to check if an element is a part of that array, I can go ahead and use in_array( needle, haystack ) to determine the results. I am trying to see the PHP equivalent of this for my purpose. Now you might have an instant answer for me and you might be tempted to say "Use IN". Yes, I can use IN, but that's not fetching the desired results. Let me explain with an example:
I have a column called "pets" in DB table. For a record, it has a value: Cat, dog, Camel
(Yes, the column data is a comma separated value). Consider that this row has an id of 1.
Now I have a form where I can enter the value in the form input and use that value check against the value in the DB. So say I enter the following comma separated value in the form input: CAT, camel
(yes, CAT is uppercase & intentional as some users tend to enter it that way).
Now when I enter the above info in the form input and submit, I can collect the POST'ed info and use the following query:
$search = $_POST['pets'];
$sql = "SELECT id FROM table WHERE pets IN ('$search') ";
The above query is not fetching me the row that already exists in the DB (remember the record which has Cat, dog, Camel as the value for the pets column?). I am trying to get the records to act as a superset and the values from the form input as subsets. So in this case I am expecting the id value to show up as the values exist in the column, but this is not happending.
Now say if I enter just CAT as the form input and perform the search, it should show me the ID 1 row.
Now say if I enter just camel, cAT as the form input and perform the search, it should show me the ID 1 row.
How can I achieve the above?
Thank you.
The function you're looking for is find_in_set:
select * from ... where find_in_set($word, pets)
for multi-word queries you'll need to test each word and AND (or OR) the tests:
where find_in_set($word1, pets) AND find_in_set($word2, pets) etc
IN() Check whether a value is within a set of values
mysql> SELECT 2 IN (0,3,5,7);
-> 0
mysql> SELECT 'wefwf' IN ('wee','wefwf','weg');
-> 1
SELECT val1 FROM tbl1 WHERE val1 IN (1,2,'a');
View: IN MySql
I've got several things for you in terms of feedback & in direct response to your questions:
First, I suggest you sanitize the input. Everybody is going to tell you that. For that, see What’s the best method for sanitizing user input with PHP?.
Second, normalize the input with UPPER() or LOWER() if you want to use MySQL and need to store user-formatted input, or use strtoupper() and strtolower() if you wanted to process the input before storing it.
You're still left with the order in the user query. E.g. "cat, dog" ought to yield the same result as "dog, cat". If you were to code that with a LIKE statement, performance issues are going to eat you alive. Not only would you have to create the query dynamically, you'd also end up with huge and unnecessarily complex queries. In short, forget it. You have to change the way you store your data.
One way to accomplish this is by creating a relationship table that references a table of unique user input and your record. This table would look similar to
user_id | pet_id
Every user could have more than one pet_id associated with them. I've set up a database a long time ago the same way you did and ran into the same issues. Performance-wise it never paid off and it's anything but good style. I ended up changing my structure because of that to the above-mentioned method.
This mysql function search an INT value into a json array of INT:
-- EXAMPLES :
-- select is_into_json_array(18, '[25, 10, 15]'); -> -100
-- select is_into_json_array(25, '[25, 10, 15]'); -> 0
-- select is_into_json_array(15, '[25, 10, 15]'); -> 2
https://github.com/PietroLaGrotta/Json-in-mysql-text-type/blob/master/is_into_json_in_array.sql
Yes, the column data is a comma
separated value
Here is your fault.
No, it shouldn't be comma separated value
And your database structure should be normalized.

Categories