0
<script type="text/javascript">
function on_callPhp1()
{
    var result = "<?php php_func();?>";
    document.getElementById('phptext').innerHTML = result;
}
</script>


<form action="" method="POST">
    <input type="button" value="Get Numbers" onclick="on_callPhp1()"/>
</form>
<div id="phptext"></div> 
<?php
include_once ('/var/www/db/connection.php');

function php_func() {    
    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); 
    }
}
?>

Whenever I run the above code, I do not see the form button. However, when I comment out the last line $result = $mysqli -> query($queryInsertNum); they appear and the page runs normally.

What could be wrong?


Update 1:

My connection.php is as follows

<?php
global $mysqli;
$mysqli = new mysqli("127.0.0.1", "user1", "somepassword", "myDB");
if ($mysqli -> connect_errno)
{
    echo "Failed to connect to MySQL: (" . $mysqli -> connect_errno . ") " . $mysqli -> connect_error;
}
?>
tony9099
  • 4,567
  • 9
  • 44
  • 73
  • Do you have acces to your erro log AND you could use http://php.net/manual/en/mysqli.error.php to see what mysql is complaining about – Louis Loudog Trottier Mar 27 '17 at 11:21
  • Maybe you just have to change the previous line for `$queryInsertNum = "INSERT INTO myDb.myTable(number) VALUES ('".$num."');";`.It can be possible that you were inserting the text `$num`in the database instead of the number – JCalcines Mar 27 '17 at 11:30
  • @JCalcines No. that line works fine. Its the mySQLi that is causing the problem – tony9099 Mar 27 '17 at 11:33

2 Answers2

1

I guess it 's because $mysqli is an unknow object inside your function, try to add global $mysqli inside your function.

<?php
include_once ('/var/www/db/connection.php');

function php_func() {
    global $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); 
    }
}
?>
Manoj Sharma
  • 1,467
  • 2
  • 13
  • 20
devseo
  • 1,182
  • 1
  • 13
  • 26
1

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);
}
?>
Community
  • 1
  • 1
hassan
  • 7,812
  • 2
  • 25
  • 36
  • Awesome ! `url: 'phpfunc.php?get=data',` why is this file under the AJAX, given my php function is in the same file and not an external php – tony9099 Mar 27 '17 at 12:35
  • i didn't wanted to make it complicated , it's up to you -**and more recommended**- to separate your code into related pieces as you said , you may separate you ajax code , or even your html form to another file to keep your script organized. – hassan Mar 27 '17 at 12:41
  • hasan, for the simplicity of my trivial task, I will keep the code on the same page, can you adjust the answer accordingly? I'd appreciate it. – tony9099 Mar 28 '17 at 06:44
  • the given answer is what you want, just change `phpfunc.php` to your current file name , and don't forget to embed on of the jquery sources listed here https://code.jquery.com/ – hassan Mar 28 '17 at 07:30
  • Hassan, shouldn't the `
    ` be `GET`?
    – tony9099 Mar 30 '17 at 07:10
  • you don't need form tags as long as you handle your request using ajax – hassan Mar 30 '17 at 07:13