Some of the problem with our attempt at understanding what you are trying to do, is due to the organization of the code on the page and the extra code trying to SELECT data to determine if it already exists before inserting/updating it.
Your code for any page should be laid out in this general order -
- initialization - define, require, create, … things your page needs, such as the session_start() statement, a database connection, configuration values, …
- post method form processing code - a post method form should be used for things that create/update data on the server or perform an action such as sending an email.
- get method business logic - get/create data needed to display the dynamic content on the web page.
- html document/template - using simple php code or an actual template system, produce the actual html document, using the data produced from the above sections of code.
At the end of the post method form processing code, item #2 on this list, is where you would perform a header() redirect to the exact same URL of the current page to cause a get request. This will clear any post data and cause the page to display the result of any inserted/updated information. If you want to display a one-time success message, store it in a session variable, then test/display/clear that session variable at the appropriate location in the html document.
Next, don’t SELECT data in order to decide if it already exists. By defining an appropriate unique index in your database table, you can just attempt to INSERT or UPDATE the data, then detect if a duplicate key error occurred to let you know if the data already exists.
In case it has not already been stated, you need to use a prepared query when supplying enteral, unknown, dynamic data values when a query is executed. While a prepared query adds one php statement per query, provided you use the much simpler PDO extension, this actually will simplify the sql query syntax.