I have an html form (each form has different page, according to date), with five text inputs, called date, inp1, inp2, inp3 and inp4.
For example, I have database table, with structure like this: id | parent | name | value.
In this case, I want to store my data, and adding it to date by parent, like this:
id | parent | name | value
1 | 0 | date | 20.07.2011
2 | 1 | inp1 | value-from-inp1
3 | 1 | inp2 | value-from-inp2
4 | 0 | date | 21.07.2011
5 | 4 | inp2 | value-from-inp2
6 | 1 | inp3 | value-from-inp3
7 | 4 | inp1 | value-from-inp1
and so on…
But problem starts here. I want to create option, that you can update those values for previously added.
But the QUESTIONS are, how to check, if
- Do I have anything assigned to that date already?
- If is assigned, how to determine, and use MySQL Update for that
- If is not assigned, how to determine, and use MySQL Insert Into for that
My stupid and 50% more inefficient of loading page solution for this problem sounds like this (Don’t worry about security, its just mock-up):
if($_POST['submit']){
$inp1_data = $db->get_row("SELECT name FROM table WHERE parent = ".$parent_id." and name='inp1'");
if($inp1_data){$db->update($query)}else{$db->insert($query)}
// ... and so on, four copies of same code, just replacing "inp1" to "inp2", "inp3"...
}
Yes, I know, this is useless script, in case, if I have added one more, or hundreds of inpNUMBER, it would be crush test site, 100% guaranteed timeout, not working script.
It sounds to me like you’re trying to use a singe table where you really need two. To answer your question, because the date is stored separately from the value, there is no way to find out if you have a value assigned to a particular question using a single
SELECT. You may be able to do this with a nested select, but I won’t try to go through the contortions to make it happen.Consider this alternative design, which assumes that a given field can’t be repeated for a given submission:
Submission table
answers table
Note that Randolf Rincón-Fadul’s suggestion of keeping the data types separated by field is a good one, but I haven’t done it here to keep things simple. Now you can find out if you have an answer for a particular date by joining the tables.