1

I am having some difficulties and I am unsure of where I am going wrong, I have a mySQL database which supplies data to a webpage. The following works correctly:

<?php include "includes/db.php"; ?>

I include my connection php file above html tags on my index.php page which contains the following;

<?php

// Create an assosciative array holding connection data
$db['db_host'] = "localhost"; 
$db['db_user'] = "XXXXXXXX";
$db['db_pass'] = "XXXXXXXX";
$db['db_name'] = "XXXXXXXX";


// Convert array values into constants, this is much more secure.
foreach($db as $key => $value)
{
    // Create constant and convert to upper case
    define(strtoupper($key), $value);
    define(strtoupper($key), $value);
}


// Initiate database connection and assign to a variable to test whether it was successful or not.
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

// If Database connection is incorrect - display an error. 
if(!$connection)
{
    echo "Error: Database Connection Failed";
} ?> 

This supplies my connection string. Following this I build the webpage as normal and request data as follows:

<div id="latest-temperature" class="col-xs-6 col-sm-3 col-lg-offset-1 infoSections" style="background: #45d4ff;">

        <?php include "includes/get-latest-temperature.php"; ?>

</div>

The included file looks like this:

<?php
echo "<h4>Latest Temperature</h4>";

$query =  "SELECT * FROM `XXXXX`.`temperature_values` ";
$query .= "WHERE time_added IN (select max(time_added) from temperature_values GROUP BY entry_id)";
$query .= "ORDER BY time_added DESC LIMIT 1;";

$select_latest_temperature = mysqli_query($connection, $query);

if(!$select_latest_temperature)
{
    echo "DB Connection Error";
    die();
}

while($row = mysqli_fetch_assoc($select_latest_temperature))
{
    // Assign data to variables
    $temperature = $row['temperature'];
    $time = $row['time_added'];
} 


echo "<p>" . $temperature . " degrees </p>";
echo "<span class='text-muted'>Recorded at: " . date("G:i a", strtotime($time)) .  " on " . date("j F Y", strtotime($time)) . "</span>"; ?>

The above works correctly until I try to reload data via jQuery as follows (in Head):

<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>

<script type="text/javascript">

    function reloadRealTimeInfo() 
    {
        $('#latest-temperature').load('includes/get-latest-temperature.php');
        $('#fan-status').load('includes/get-fan-status.php');
        $('#temperature-entries').load('includes/get-temperature-entries.php');
    }

    $(document).ready(function()
    {
        reloadRealTimeInfo();
    });

    $(function()
    {
        setInterval(reloadRealTimeInfo, 2000);
    });

</script>

Upon the divs reloading the data disappears, and it appears it completely loses the connection string. I have tried to instead include the db.php file in each .php file that requires it which also does not work. The one solution I found was copying the contents of db.php into each PHP script - this works correctly.

Why is this? I have tried making the string global, I have tried removing constants. Whilst I have a "solution" I dislike the idea of copying the database connection details into each file as on a larger website it would be a pain to change details.

Thanks for your time - If I have missed anything please let me know.

EDIT: I am almost certain the issue is down to scope but I am fairly new to PHP so I can not be sure. Would loading the PHP file after the file has been read line by line effectively eliminate the $connection string declared at the top of the file? I did try to make it global and also add it to the global array.

EDIT2: I have moved the files onto a local XAMPP installation which has allowed me to view PHP errors easily. The problems are as follows:

Notice: Constant DB_USER already defined in D:\xampp\htdocs\project\includes\db.php on line 15
Notice: Constant DB_PASS already defined in D:\xampp\htdocs\project\includes\db.php on line 15
Notice: Constant DB_NAME already defined in D:\xampp\htdocs\project\includes\db.php on line 15

This is followed by another error in each div element that is being updated by jQuery:

Notice: Undefined variable: connection in D:\xampp\htdocs\project\includes\get-latest-temperature.php on line 9
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in D:\xampp\htdocs\project\includes\get-latest-temperature.php on line 9

Line 9 refers to:

$select_latest_temperature = mysqli_query($connection, $query);

These errors appear to confirm my original suspicions that the problems are with the constants and scoping, hopefully somebody can help!

12
  • 1
    Firstly, your query read as GROUP BY idORDER with GROUP BY entry_id)"; $query .= "ORDER... and that should be throwing you an error. You need to add a space here $query .= " ORDER or GROUP BY entry_id) "; Commented Feb 2, 2016 at 18:08
  • @Fred-ii- Thanks for your response, I am not sure what the problem is with the query, the query works correctly as the problems only arises when I use jQuery to reload the page. I have added the space as mentioned and it hasn't made any difference - I have also tested the query in mySQL workbench and it returns the result that was added most recently - which is correct. Commented Feb 2, 2016 at 18:15
  • Are there any errors in your browser's console? Commented Feb 2, 2016 at 18:36
  • You're welcome. Try putting your 2nd script where you have the function reloadRealTimeInfo() with the includes inside <body> also or outside of <head>. See if error reporting catches anything also. php.net/manual/en/function.error-reporting.php Commented Feb 2, 2016 at 18:37
  • 1
    Put all of your code inside the $(document),ready handler. Commented Feb 2, 2016 at 18:40

2 Answers 2

1

You're likely running into a couple of things, a scope issue and the DOM not being ready to perform the actions you're asking. To remedy that put all of the JavaScript / jQuery code into one document ready handler (you had two, your second one was a shortcut which is OK to use but just not necessary in this case):

<script type="text/javascript">

$(document).ready(function()
{
    function reloadRealTimeInfo() 
    {
        $('#latest-temperature').load('includes/get-latest-temperature.php');
        $('#fan-status').load('includes/get-fan-status.php');
        $('#temperature-entries').load('includes/get-temperature-entries.php');
    }
    reloadRealTimeInfo(); // will perform when the page loads
    setInterval(reloadRealTimeInfo, 2000); // then the timer is set
});

</script>

Doing it this will will insure that all of the elements have loaded into the DOM and have become available for use.


To get the skinny on possible jQuery AJAX errors have a look at this post. Clicking the F12 key while in your browser will reveal to you a whole world of information about your AJAX.


Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your response, I have made the changes and understand why but unfortunately it has not solved the problem. I think the problem has something to do with scope as it works correctly when I paste the connection details into each additional php file but I could be wrong.
Please open your browser's console and see if you have any information about errors there.
Hi, I have moved the files to a local installation and updated my question with more information. Thanks again
0

As is often the case, I was simply looking too hard and missing the problem all together. I appreciate everybody that has tried to solve this problem, the problem appears to be as follows:

On the index page I include the following:

<?php include "includes/db.php"; ?>

Which works fine as the index page is one folder below that, so the path is correct, this also means the initial calls to the scripts work. The problem has always been when jQuery loads the page into the div, well what happens is the include is then at the same directory level as the scripts being called making the path

include "db.php";

After adding this include into each file that requires it and removing it from the index all together everything works as expected. Perhaps there is another solution but this solves my problem and meets my requirements to have connection details editable in only one place.

Thanks again!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.