Skip to content
Advertisement

PHP: looking up values in DB and converting before inserting data

This might be easier to do with javascript but but I happen to be restricted solely to MySQL, PHP, and Apache (as well as HTML and CSS obviously) for this project, and I’m not good at PHP

I’ve basically finished the whole thing but came a cross a small problem.

The user creates a sport event and to do so the user chooses two opposing teams with the help of two html dropdowns (both dropdowns display the same array of teams that are fetched from my ‘teams’ table located in my database). The names of the teams are displayed and selected on the page, and therefore stored as string variables in PHP once the user submits the form.

Here’s the catch, the two teams the user selects are then to be saved in a table which is meant to contain the IDs of the two teams, rather than their names (makes it easier to enforce integrity constraints). But I would have to query the db again to obtain the IDs from the ‘teams’ table and then store this in the table I’m interested in.

What makes this a tad more complicated is the fact that along with the two team-dropdowns, in the aforementioned html form, the user inputs a lot of other data regarding the event which is stored together with the two teams; this data is supposed to be inserted into the same database table as is, everything but the two teams is supposed to be inserted as is.

My initial thoughts were to add a subquery next to the two value placeholders I would use to insert the teams-data:

JavaScript

this returns an error however:

JavaScript

which makes no sense. if I try to insert the same tuple into the database manually (using these two subqueries in mysql) everything is fine:

JavaScript

if I try to query the database using either one of the two subqueries, the result is always one row as the team_name is always unique (below is the query):

JavaScript

EDIT: here’s the code

How the teams are fetched and displayed in two html dropdowns:

JavaScript

the five pieces of data inserted by the user into the form are then checked for null-values (example of one below)

JavaScript

and then this is as far as the data gets

JavaScript

P.S. using MySQL 10.4.14 connected to the XAMPP 3.2.4 using Apache 2.4 and PHP 7.2.34

Advertisement

Answer

You can set a value for an <option>, and then it’s the value which is submitted to the server with the form.

So if you put the ID of your team into each option when you are rendering the HTML, then you’ll get the selected ID back again when the form is submitted.

e.g.

JavaScript

More info: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option

The current SQL used to select the teams isn’t shown, but I would guess the SQL query to do this needs to be something like:

JavaScript

and then the PHP to read it:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement