I have SQL query which goes to result table:
$php_variable_answer = "SELECT
answer_id
FROM result
WHERE question_id = $php_variable_question";
than query goes to answer table and get answer:
$php_variable_answer = "SELECT answer
FROM answer_table
WHERE answer_id = $php_variable_answer";
I have 20 php files on my website. I am using these three query each time to get answer in at least 5 or 8 files.
My questions:
- How can i reuse this code in all files by calling them in one place? And if it is even possible?
- Secondly is it good to reuse this code using one place holder for it? Does it makes any difference?
The short answer is that re-using code is a great idea, and the more you can effectively reuse stuff the better. (Easier to make updates, keep things consistent, etc.) If you’re reusing the same queries or the same PHP, move the reusable parts to an appropriately-named file, like
database.php. Then, add this line to the top of any file that needs your query functions:require_once('database.php');This will make your existing functions and queries available, so you don’t have to re-write them in each new PHP file.
If your PHP files start growing, you might want to start researching the benefits of using a framework to keep things organized and efficient. A framework is a code base you can use that’ll encourage you to keep organized and give you some existing code to build from. A PHP framework I like using is CodeIgniter, and there are many others available.