You have a variable scope
issue , every php function has it's own scope, you cannot deal with a variable from outside the function within it unless you pass this variable to your function .
the $mysqli
variable which we are talking about here .
and to solve this , you need either use global variables , which is considered as a bad practice, checkout this wiki for more details OR by passing your variable as a parameters as follows :
// hey `php_func` ,please pass $mysqli value to be able to use it within you
// or whatever the variable name is
function php_func($mysqli) {
for ($i = 0; $i <= 25000; $i++) {
$num = (rand(1,1000));
echo "Number #" .$i . "\t ------ " . $num;
echo "<br>";
$queryInsertNum = "INSERT INTO myDb.myTable(number) VALUES ('$num');";
$result = $mysqli -> query($queryInsertNum);
}
}
but take care, you will need every time you call your function to pass that variable to it as following :
php_func($mysqli);
this , will take us to the other issue , that you are mixing and misunderstanding the difference between client-side and server-side programming? ,
you are calling the php function like this :
var result = "<?php php_func();?>";
which is wrong , if you hit CTRL+U
from your firefox you will figure out that the function already executed even before call your HTML event onclick
it's recommended in such a case -which you are need to open a contacting channel so to speak between the client side and server side- to use ajax
so , your script may be like this : here i will assume that your file name is phpfunc.php
the ajax part :
<script type="text/javascript">
function on_callPhp1()
{
$.ajax({
url: 'phpfunc.php?get=data', // change this to whatever your file is
type: 'GET',
success: function (data) {
document.getElementById('phptext').innerHTML = data;
}
});
}
</script>
<form action="" method="POST">
<input type="button" value="Get Numbers" onclick="on_callPhp1()"/>
</form>
<div id="phptext"></div>
<?php
function php_func($mysqli) {
for ($i = 0; $i <= 25000; $i++) {
$num = (rand(1,1000));
echo "Number #" .$i . "\t ------ " . $num;
echo "<br>";
$queryInsertNum = "INSERT INTO myDb.myTable(number) VALUES ('$num');";
$result = $mysqli -> query($queryInsertNum);
}
}
if (isset($_GET['get']) && $_GET['get'] == 'data') {
include_once ('/var/www/db/connection.php');
php_func($mysqli);
}
?>