0

I am working at a project with mySQL and Highcharts. First I have an ESP32 with several, whose measurements get wrote into a database called "MariaDB". This measurements which are in the database I represent in a Highsotck chart.

That works fine so far, but my real problem is that:

I have a data.php file and a main.php file. I'd like to change the string "$sensorid" between those two files. I can send the variable "$sensorid" from the main.php to the with the "SESSION" command. That also works, but I can't use this variable in in the data.php file (but with echo the value is correctly sent).

<?php


SESSION_START(); 

    echo "Die empfangene SensorID lautet" . 
          $_SESSION["sensorid"] ;                          //This output is correct :) 


date_default_timezone_set('Europe/Berlin');

$con = mysql_connect("IP of database","username","password");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}

mysql_select_db('MyHome', $con);

$result = mysql_query("SELECT * FROM `Messwerte` WHERE SensorID = '$sensorid' ");     /*In this part I need the value '$sensorid'!*/

while($row = mysql_fetch_array($result)) {
  $datum = $row['DateTime'];
  $value = round($row['Messwert'],1);

  $uts = strtotime ($datum);

if (date('I', time()))
{
   $uts = $uts + 7200;
   $x=1;
}
else
{
   $uts=$uts+3600;
if($x==1)
 {
        $uts=$uts-7200;
        $x=0;
 }
}

  $datum=date('l, F j y H:i:s',$uts);
  $uts *= 1000; // convert from Unix timestamp to JavaScript time
   $dataIN[] = array((float)$uts,(float) $value);

}
echo json_encode($dataIN);
mysql_close($con);

?>

I hope you understand what I mean(Im from Germany, so I am not really good in English) otherwise just ask.

DR.Alfred
  • 1
  • 1
  • 2
    $sensorid = $_SESSION["sensorid"] ; I think you want to get the data from sessions. You have to declare the variable or directly you can pass the $_SESSION["sensorid"] in mysql query. – Vikash Dhiman Sep 21 '18 at 11:47
  • 1
    [`mysql_*` functions are deprecated!](http://php.net/manual/de/function.mysql-fetch-array.php). Use [mysqli_*](http://php.net/manual/de/mysqli.construct.php) functions or [PDO mysql](http://php.net/manual/de/ref.pdo-mysql.php) instead. (links in german) – Philipp Maurer Sep 21 '18 at 11:49
  • Change $result = mysql_query("SELECT * FROM `Messwerte` WHERE SensorID = '$sensorid' "); /*In this part I need the value '$sensorid'!*/ to: $result = mysql_query("SELECT * FROM `Messwerte` WHERE SensorID = '".$_SESSION["sensorid"]."' "); /*In this part I need the value '$sensorid'!*/ – Sigma Sep 21 '18 at 11:49
  • 2
    You should read about **[variable scope](http://php.net/manual/en/language.variables.scope.php)**, mastering that will save you much time in the future. Meanwhile, try to declare a local (to the file) variable `$sensorId=$_SESSION['sensorId']; `, before using it. – YvesLeBorg Sep 21 '18 at 11:50
  • Do you load both files on one request, or do you call each one in a single request? – Philipp Maurer Sep 21 '18 at 11:55
  • What do you mean with "loading both files on one request"? – DR.Alfred Sep 27 '18 at 07:33

3 Answers3

0

@DR.Alfred welcome to SO. The first reccomandation is that you try to convert your query to mysqli or PDO statements because mysql is deprecated and have security problems.

Returning to your code, the value of $_SESSION["sensorid"] is correct but in your query:

mysql_query("SELECT * FROM `Messwerte` WHERE SensorID = '$sensorid' ");

you try to use an undeclared variable $sensorid

If you need to have the value of $_SESSION["sensorid"] you can use in your query directly the session variable whitch contains the value you need or better you must assign to the variable $sensorid (or you can call it as you want) the value of the session in this way:

$sensorid = $_SESSION["sensorid"];

and then in your query you can use the $sensorid to get the value, so your query becomes:

$result = mysql_query("SELECT * FROM `Messwerte` WHERE SensorID = ' ".$sensorid." ' ");

if you dont want to assign the value of the session to a new variable you can allways use it directly in your query:

$result = mysql_query("SELECT * FROM `Messwerte` WHERE SensorID = ' ".$_SESSION["sensorid"]." ' ");

Hope my explanation is clear and help you understand how to use variables in php. Of course i recommend to you read more about basic php and mysql and use mysqli or better PDO statements when have to work with queries and db.

Sigma
  • 387
  • 3
  • 17
0

@Sigma, thank you for your detailed answer. I tried to fix my problems with all your suggestion, but it didn't work. I'm looking for mysqli or PDO, but it seems, that the older "mysql" is not the problem. Something with the String from php-File to php-File seems not to work.

Here's the code with the suggestions, which you made.

<?php


SESSION_START();

$sensorID = $_SESSION["sensorID"]; 

    echo "Die empfangene SensorID lautet" . 
          $_SESSION["sensorID"] ;                          //This output is correct :) 

date_default_timezone_set('Europe/Berlin');

$con = mysql_connect("IP of database","username","password");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}

mysql_select_db('MyHome', $con);

$result = mysql_query("SELECT * FROM `Messwerte` WHERE SensorID = ' ".$sensorID." ' ");   /*In this part I need the value '$sensorID'!*/

while($row = mysql_fetch_array($result)) {
  $datum = $row['DateTime'];
  $value = round($row['Messwert'],1);

  $uts = strtotime ($datum);

if (date('I', time()))
{
   $uts = $uts + 7200;
   $x=1;
}
else
{
   $uts=$uts+3600;
if($x==1)
 {
        $uts=$uts-7200;
        $x=0;
 }
}

  $datum=date('l, F j y H:i:s',$uts);
  $uts *= 1000; // convert from Unix timestamp to JavaScript time
   $dataIN[] = array((float)$uts,(float) $value);

}
echo json_encode($dataIN);
mysql_close($con);

?>

second php-File

<?php 


$sensorID = "P_INNEN";

SESSION_START(); 


$_SESSION['$sensorID'];

?>

<a href="P_INNEN_data.php">Go to P_INNEN_data.php !</a>
DR.Alfred
  • 1
  • 1
0

DR.Alfred got it, he got it! I can't even realise it, because I was searching for that problem for about 2 months.

For these guys, who are interested in, what the problem was. I solved it like this:

<?php

$x = 'P_INNEN';

?>


<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>AZ Elektronik / Automatik, Emmen</title>

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script type="text/javascript">

$(function() {



    $.getJSON("P_INNEN_data.php?x=P_INNEN", function(data) { //here I had to also fill in "?x=P_INNEN?x=P_INNEN"!, not just "P_INNEN_data.php"


        // Create a timer
        var start = + new Date();

        // Create the chart
        $('#container').highcharts('StockChart', {
            chart: {
                events: {
                    load: function(chart) {
                        this.setTitle(null, {
                            text: 'Built chart at '+ (new Date() - start) +'ms'
                        });
                    }
                },
                zoomType: 'x'
            },

            rangeSelector: {
                buttons: [{
                    type: 'day',
                    count: 1,
                    text: '24h'
                }, {
                    type: 'week',
                    count: 1,
                    text: '1w'
                }, {
                    type: 'month',
                    count: 1,
                    text: '1m'
                }, {
                    type: 'month',
                    count: 6,
                    text: '6m'
                }, {
                    type: 'year',
                    count: 1,
                    text: '1y'
                }, {
                    type: 'all',
                    text: 'All'
                }],
                selected: 1
            },

            xAxis: {
               ordinal: false
            },

            yAxis: {
                title: {
                    text: 'Luftdruck Innen'
                }
            },

            title: {
                text: 'Luftdruck Innen'
            },

            subtitle: {
                text: 'Built chart at...' // dummy text to reserve space for dynamic subtitle
            },

            series: [{
                name: 'mB',
                type: 'line',
                data: data,
                tooltip: {
                    valueDecimals: 1,
                    valueSuffix: ' mB'
                },
                fillColor : {
                    linearGradient : {
                        x1: 0,
                        y1: 0,
                        x2: 0,
                        y2: 1
                    },
                    stops : [[0, Highcharts.getOptions().colors[0]], [1, 'rgba(0,0,0,0)']]
                },
            }]

        });
    });
});
        </script>
    </head>
    <body>
<script src="/Highstock/code/highstock.js"></script>
<script src="/Highstock/code/modules/exporting.js"></script>

<div id="container" style="height: 500px; min-width: 500px"></div>
    </body>
</html>




<?php

$x=$_GET["x"]; //I did it with $_GET[], but SESSION would also work


date_default_timezone_set('Europe/Berlin');

$con = mysql_connect("IP of databse","username","password");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}

mysql_select_db('MyHome', $con);

$result = mysql_query("SELECT * FROM `Messwerte` WHERE SensorID = '$x' "); //There was the main problem: I made two spaces between ' and $x before



while($row = mysql_fetch_array($result)) {
  $datum = $row['DateTime'];
  $value = round($row['Messwert'],2);


  $uts = strtotime ($datum);

if (date('I', time()))
{
    $uts = $uts + 7200;
    $x=1;
}
else
{
    $uts=$uts+3600;
if($x==1)
 {
        $uts=$uts-7200;
        $x=0;
 }
}

  $datum=date('l, F j y H:i:s',$uts);
  $uts *= 1000; // convert from Unix timestamp to JavaScript time
   $data[] = array((float)$uts,(float) $value);

}


echo json_encode($data);
mysql_close($con);

?>
DR.Alfred
  • 1
  • 1