I have a 'db' database and table 'c1' and another table 'c2'.
I have a Form through which the data 'name' and 'last name' is entered into table 'c2', but I have to select a 'value' from the 'dropdown list' from table 'c1'.
info_comapny rows are copied from table 'c1' to table 'c2' and this is done by the 'value' selected from the dropdown list (From)
How can I do this in PHP?
Here is a picture for more clarification:
CodePudding user response:
I think you may have misunderstood how this works a little bit, and could also perhaps benefit from studying some more introductory tutorials about PHP, HTML forms and databases. You don't need to "copy" any data from c1
to c2
.
In a HTML dropdown list, you can specify options with values. For example:
<select name="info">
<option value="1">Company</option>
<option value="2">Personal</option>
<select>
When you submit your form, the selected value from the dropdown list is submitted to the server. So if the user selects the "Company" option, then the value 1
will be submitted to the server and be available to you in $_POST["info"]
.
All you need to do then is include that selected value in the INSERT
SQL statement which your PHP code will create in order to write a record into c2
. For example:
$sql = "INSERT INTO `c2` (`name`, `last_name`, `infoID`) VALUES (?, ?, ?);"
and then use $_POST["info"]
in your parameters list:
$stmt = $db->prepare($sql);
$stmt->execute([$_POST["name"], $_POST["lastname"], $_POST["info"]]);
This will result in the selected ID being written to infoID
column in the c2
database, which is all you need in order to link it back to the related info record in c1
.
N.B. The From
and info_Company
columns in table c2
in your screenshot are redundant - you can remove them. All that's required in c2
is an infoID
column, which should have a foreign key relationship defined with the id
column in c1
, to ensure referential integrity.
You should study the topics of relational database design and normalisation before attempting to do any further design of your database, so that you understand the key concepts here, and avoid doing anything else which would denormalise the schema or cause unnecessary duplication of the data.