I need to check if a form input is set and run different queries based on that. All the queries are to the same DB and most of them are to the same table. Here is an example: (Note this is a simplified code for an example)
//First query
if (isset ($_POST['abccheckbox']))
{
$abccheckbox = implode("','", $_POST['abccheckbox']);
$connect = mysqli_connect("localhost", "root", "");
if (!$connect) {
die('Connection Failed: ' . mysqli_error());
}
//Connect to Database
mysqli_select_db($connect, "trialDB") or die( "Unable to select database");
$query= "SELECT * FROM xyz_table WHERE xyz IN ('$abccheckbox')";
$result=mysqli_query($connect, $query);
if (!$result)
{
die('Error fetching results: ' . mysqli_error());
exit();
}
while ($row = mysqli_fetch_array($result))
{
$description[] = $row['description'];
}
//Closing DB Connection
mysqli_close($connect);
}
else {
$description = 0;
}
//SECOND QUERY
if (isset ($_POST['defcheckbox']))
{
$defcheckbox = implode("','", $_POST['defcheckbox']);
$connect = mysqli_connect("localhost", "root", "");
if (!$connect) {
die('Connection Failed: ' . mysqli_error());
}
//Connect to Database
mysqli_select_db($connect, "trialDB") or die( "Unable to select database");
$query= "SELECT * FROM xyz_table WHERE xyz IN ('$defcheckbox')";
$result=mysqli_query($connect, $query);
if (!$result)
{
die('Error fetching results: ' . mysqli_error());
exit();
}
while ($row = mysqli_fetch_array($result))
{
$headings[] = $row['headings'];
}
//Closing DB Connection
mysqli_close($connect);
}
else {
$headings = 0;
}
//Third Query
if (isset ($_POST['ghicheckbox']))
{
$ghicheckbox = implode("','", $_POST['ghicheckbox']);
$connect = mysqli_connect("localhost", "root", "");
if (!$connect) {
die('Connection Failed: ' . mysqli_error());
}
//Connect to Database
mysqli_select_db($connect, "trialDB") or die( "Unable to select database");
$query= "SELECT * FROM xyz_table WHERE xyz IN ('$ghicheckbox')";
$result=mysqli_query($connect, $query);
if (!$result)
{
die('Error fetching results: ' . mysqli_error());
exit();
}
while ($row = mysqli_fetch_array($result))
{
$type[] = $row['type'];
}
//Closing DB Connection
mysqli_close($connect);
}
else {
$headings = 0;
}
......
I am bascially trying to query the same table but doing different queries and storing different values in array after checking if that particular set of checkboxes are selected. I feel that the code is really windy and very redundant.
My questions are:
1) Is it fine to have multiple SELECT queries to SQL in 1 file itself or having too many separate queries in 1 file can overload the server?
2) In the above code, I open sql connection and close it for each queries. Does that affect the performance if I connect to sql so many times and run separate queries in the same file?
3) Can someone give an example on how I can maybe simply that code for efficiency so I can understand the right way of doing it please?