0

I have two php files. one called index, which includes (include ' ') the second, which is called phpload. in phpload I have a function - addKid (I call it from index.php after including phpload inside of it) that inserts data to the database upon page load. I'd like phpload to include all my database functions. It works fine like that:

<?php

    function addKid() {
        include '../pass.php';
        $conn = new mysqli($servername, $username, $password, $dbname);
        mysqli_query($conn, "SET NAMES 'utf8'");
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
    $sql = "INSERT INTO kids (kid_fn, kid_ln, fk_gan_id)
    VALUES ('chk', 'chk', '1')";

    if ($conn->query($sql) === TRUE) {
        echo "<br>";
        echo "That Worked!";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();
    }
    //$myfoo = $_POST['sendfoo'];
    //$myfoo();
    ?>

But if I leave the database connection lines outside of the addKid function (in order to use them also on different db operations (select / create etc.) it does not work. index.php loads its visual content but I get an Error 500 from phpload.php. This is what I mean by leaving the database connections methods outside the function:

<?php 
include '../pass.php';
$conn = new mysqli($servername, $username, $password, $dbname);
mysqli_query($conn, "SET NAMES 'utf8'");
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
function addKid() {
    $sql = "INSERT INTO kids (kid_fn, kid_ln, fk_gan_id)
    VALUES ('chk', 'chk', '1')";

    if ($conn->query($sql) === TRUE) {
        echo "<br>";
        echo "That Worked!";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();
}

?>

What am I doing wrong? Thanks in advance!

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • 4
    `$conn` is out of scope. Pass your connection to the function and it will work. – IsThisJavascript Apr 17 '18 at 14:53
  • You probably don't need the `===` type check in your `if ($conn->query($sql) === TRUE) {` aswell. You're ok for now but if you try to `SELECT * FROM...` that if statement will actually fail. `if ($conn->query($sql) )` is sufficient. Just FYI an all – IsThisJavascript Apr 17 '18 at 14:57
  • @IsThisJavascript Thanks but at that case it gives me an sql error that includes "using password: NO". It works only if I also include the 'pass.php' file - which has my db password. – Dave Batiko Apr 17 '18 at 14:59
  • Post your updated code please so I can see (put it in your original post) – IsThisJavascript Apr 17 '18 at 15:05

0 Answers0