I have this code:
function Perubahan($a = '`Ubah`') {
$con = mysqli_connect("localhost", "root", "", "nofriani"); //koneksi ke database
$syntax = 'SELECT' . $a . ' FROM `table 1` WHERE `No`= 6';
$naik = mysqli_query($con, $syntax);
while ($row = mysqli_fetch_array($naik)) {
echo round($row[0], 3);
}
}
function Jenis($b = 1) {
$con = mysqli_connect("localhost", "root", "", "nofriani"); //koneksi ke database
$syntax = 'SELECT `Jenis` FROM `table 1` WHERE `No`= ' . $b;
$naik = mysqli_query($con, $syntax);
while ($row = mysqli_fetch_array($naik)) {
echo $row[0];
}
}
function Andil($b = 1) {
$con = mysqli_connect("localhost", "root", "", "nofriani"); //koneksi ke database
$syntax = 'SELECT `Andil` FROM `table 1` WHERE `No`= ' . $b;
$naik = mysqli_query($con, $syntax);
while ($row = mysqli_fetch_array($naik)) {
echo round($row[0], 3);
}
}
function Kelompok($b = 1) {
$con = mysqli_connect("localhost", "root", "", "nofriani"); //koneksi ke database
$syntax = 'SELECT `Andil` FROM `table 1` WHERE `No`= ' . $b;
$naik = mysqli_query($con, $syntax);
while ($row = mysqli_fetch_array($naik)) {
echo round($row[0], 3);
}
}
So I call each function (still in the same PHP file). But when I start running it, it took too long to show the result (but it worked). I'm guessing the problem is because I repeat the database connection in each function. How do I make avoid connecting to the same database?
I tried to create the database connection to different file and call the file in each function, but it didn't work. I also tried to pass the $con variable into the function (doing global $con
in each function), but it also didn't make it run faster.
So am I missing something here?