Realtime with AJAX/MySQL multiple variables? - php

I have an dymamic PHP file that load Data from MySQL database about some relay card, every user have a different amount of relay card. All card have 8 relays (State 1/0), 8 inputs (State 1/0), and 2 analogue input (State from 0 to 1024) this is for every card, some user will have 1 and some other can have 8 and i would like to update this data as fast as possible. I have done a PHP script that trigger all relays information for a specific user, in this case this is the user 2.
I think the best way to do what i want as what i have read is to call it from jQuery, but i don't understand how-o update many variable.
Here is the code i have to get the latest state from MySQL.
Ok here is an update of the code, i have separated completely the data fetching and the GUI creation, so what i want to do, is show in realtime what the get_states_gui.php file fetch from mysql to the gui.php file. Can someone point me in the good direction since i am completely lost right now! THanx a lot here are those 2 files:
The gui.php:
<?php
require_once('config.php');
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$start = $time;
// We create connection to the MySQL database.
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$con) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database\n");
}
$req="SELECT * FROM cartes WHERE utilisateur=$user";
$result = mysql_query($req);
if(!$result) {
die('Query failed: ' . mysql_error());
}
$nb_iplab = mysql_num_rows($result);
$b = "1";
while ($ligne = mysql_fetch_assoc($result))
{
extract($ligne);
${'nom'.$b} = $nom;
${'mac'.$b} = $mac;
${'ip'.$b} = $ip;
for ($i=1; $i <= "8"; $i++ )
{
//We set Relays names for each IPLAB and get their states in the MySQL database.
${'nomR'.$i.$b} = ${'nomR'.$i};
$req = "SELECT * FROM states_log WHERE dev='R$i' AND mac='${'mac'.$b}' ORDER BY date_heure DESC LIMIT 1";
$result2 = mysql_query($req);
if(!$result2)
{
die('Query failed: ' . mysql_error());
}
$ligne = mysql_fetch_assoc($result2);
extract($ligne);
${'stateR'.$i.$b} = $state;
if ( ${'stateR'.$i.$b} == "1" )
{
${'img_linkR'.$i.$b} = "<a href=set_states.php?ip=${'ip'.$b}&cmd=CR$i target=empty> <img src=img/toggle_1.png height=28></a>";
}
else if ( ${'stateR'.$i.$b} == "0" )
{
${'img_linkR'.$i.$b} = "<a href=set_states.php?ip=${'ip'.$b}&cmd=SR$i target=empty> <img src=img/toggle_0.png height=28></a>";
}
else
{
${'img_linkR'.$i.$b} = "<a href=set_states.php?ip=${'ip'.$b}&cmd=CR$i target=empty> <img src=img/LED_yellow.png height=28></a>";
}
//We set Inputs names for each IPLAB and get their states in the MySQL database.
${'nomI'.$i.$b} = ${'nomI'.$i};
${'multI'.$i.$b} = ${'multI'.$i};
${'img_onI'.$i.$b} = ${'img_onI'.$i};
${'img_offI'.$i.$b} = ${'img_offI'.$i};
${'img_naI'.$i.$b} = ${'img_naI'.$i};
$req = "SELECT * FROM states_log WHERE dev='I$i' AND mac='${'mac'.$b}' ORDER BY date_heure DESC LIMIT 1";
$result2 = mysql_query($req);
if(!$result2)
{
die('Query failed: ' . mysql_error());
}
$ligne = mysql_fetch_assoc($result2);
extract($ligne);
${'stateI'.$i.$b} = $state;
if ( ${'stateI'.$i.$b} == "1" )
{
${'img_linkI'.$i.$b} = "<img src=img/${'img_onI'.$i.$b} height=28>";
}
else if ( ${'stateI'.$i.$b} == "0" )
{
${'img_linkI'.$i.$b} = "<img src=img/${'img_offI'.$i.$b} height=28>";
}
else
{
${'img_linkI'.$i.$b} = "<img src=img/${'img_naI'.$i.$b} height=28>";
}
// We check for how many times, the Inputs has changed state to 1, and we set them as a variable for counter.
$req = "SELECT count(*) FROM states_log WHERE dev='I$i' AND state='1' AND mac='${'mac'.$b}'";
$result2 = mysql_query($req);
if(!$result2)
{
die('Query failed: ' . mysql_error());
}
list (${'countI'.$i.$b}) = mysql_fetch_row ($result2);
if (isset(${'multI'.$i.$b}))
{
${'countI'.$i.$b} = ${'countI'.$i.$b} * ${'multI'.$i.$b};
}
}
//We set Analog names fir each IPLAB and get their states in the MySQL database.
for ($i=1; $i <= "3"; $i++ )
{
${'nomA'.$i.$b} = ${'nomA'.$i};
${'unitA'.$i.$b} = ${'unitA'.$i};
$req = "SELECT * FROM states_log WHERE dev='A$i' AND mac='${'mac'.$b}' ORDER BY date_heure DESC LIMIT 1";
$result2 = mysql_query($req);
if(!$result2)
{
die('Query failed: ' . mysql_error());
}
$ligne = mysql_fetch_assoc($result2);
extract($ligne);
${'stateA'.$i.$b} = $state;
}
if ( debug == "1" )
{
echo "${'nom'.$b}<br>";
echo "MAC = ${'mac'.$b}<br>";
for ( $i = 1; $i <= 8; $i++ )
{
echo "${'nomR'.$i.$b} = ${'stateR'.$i.$b}<br>";
echo "${'nomI'.$i.$b} = ${'stateI'.$i.$b}<br>";
}
for ( $i = 1; $i <= 3; $i++ )
{
echo "${'nomA'.$i.$b} = ${'stateA'.$i.$b}<br>";
}
echo "---------------------------------------<br>";
}
$b++;
}
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $start), 4);
if ( debug == "1" )
{
echo 'Page generated in '.$total_time.' seconds.'."\n";
}
mysql_close($con);
?>
And now the get_states_gui.php:
<?php
require_once('config.php');
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$start = $time;
// We create connection to the MySQL database.
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$con) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database\n");
}
$req="SELECT * FROM cartes WHERE utilisateur=$user";
$result = mysql_query($req);
if(!$result) {
die('Query failed: ' . mysql_error());
}
$nb_iplab = mysql_num_rows($result);
$b = "1";
while ($ligne = mysql_fetch_assoc($result))
{
extract($ligne);
${'nom'.$b} = $nom;
${'mac'.$b} = $mac;
${'ip'.$b} = $ip;
for ($i=1; $i <= "8"; $i++ )
{
//We set Relays names for each IPLAB and get their states in the MySQL database.
${'nomR'.$i.$b} = ${'nomR'.$i};
$req = "SELECT * FROM states_log WHERE dev='R$i' AND mac='${'mac'.$b}' ORDER BY date_heure DESC LIMIT 1";
$result2 = mysql_query($req);
if(!$result2)
{
die('Query failed: ' . mysql_error());
}
$ligne = mysql_fetch_assoc($result2);
extract($ligne);
${'stateR'.$i.$b} = $state;
if ( ${'stateR'.$i.$b} == "1" )
{
${'img_linkR'.$i.$b} = "<a href=set_states.php?ip=${'ip'.$b}&cmd=CR$i target=empty> <img src=img/toggle_1.png height=28></a>";
}
else if ( ${'stateR'.$i.$b} == "0" )
{
${'img_linkR'.$i.$b} = "<a href=set_states.php?ip=${'ip'.$b}&cmd=SR$i target=empty> <img src=img/toggle_0.png height=28></a>";
}
else
{
${'img_linkR'.$i.$b} = "<a href=set_states.php?ip=${'ip'.$b}&cmd=CR$i target=empty> <img src=img/LED_yellow.png height=28></a>";
}
//We set Inputs names for each IPLAB and get their states in the MySQL database.
${'nomI'.$i.$b} = ${'nomI'.$i};
${'multI'.$i.$b} = ${'multI'.$i};
${'img_onI'.$i.$b} = ${'img_onI'.$i};
${'img_offI'.$i.$b} = ${'img_offI'.$i};
${'img_naI'.$i.$b} = ${'img_naI'.$i};
$req = "SELECT * FROM states_log WHERE dev='I$i' AND mac='${'mac'.$b}' ORDER BY date_heure DESC LIMIT 1";
$result2 = mysql_query($req);
if(!$result2)
{
die('Query failed: ' . mysql_error());
}
$ligne = mysql_fetch_assoc($result2);
extract($ligne);
${'stateI'.$i.$b} = $state;
if ( ${'stateI'.$i.$b} == "1" )
{
${'img_linkI'.$i.$b} = "<img src=img/${'img_onI'.$i.$b} height=28>";
}
else if ( ${'stateI'.$i.$b} == "0" )
{
${'img_linkI'.$i.$b} = "<img src=img/${'img_offI'.$i.$b} height=28>";
}
else
{
${'img_linkI'.$i.$b} = "<img src=img/${'img_naI'.$i.$b} height=28>";
}
// We check for how many times, the Inputs has changed state to 1, and we set them as a variable for counter.
$req = "SELECT count(*) FROM states_log WHERE dev='I$i' AND state='1' AND mac='${'mac'.$b}'";
$result2 = mysql_query($req);
if(!$result2)
{
die('Query failed: ' . mysql_error());
}
list (${'countI'.$i.$b}) = mysql_fetch_row ($result2);
if (isset(${'multI'.$i.$b}))
{
${'countI'.$i.$b} = ${'countI'.$i.$b} * ${'multI'.$i.$b};
}
}
//We set Analog names fir each IPLAB and get their states in the MySQL database.
for ($i=1; $i <= "3"; $i++ )
{
${'nomA'.$i.$b} = ${'nomA'.$i};
${'unitA'.$i.$b} = ${'unitA'.$i};
$req = "SELECT * FROM states_log WHERE dev='A$i' AND mac='${'mac'.$b}' ORDER BY date_heure DESC LIMIT 1";
$result2 = mysql_query($req);
if(!$result2)
{
die('Query failed: ' . mysql_error());
}
$ligne = mysql_fetch_assoc($result2);
extract($ligne);
${'stateA'.$i.$b} = $state;
}
if ( debug == "1" )
{
echo "${'nom'.$b}<br>";
echo "MAC = ${'mac'.$b}<br>";
for ( $i = 1; $i <= 8; $i++ )
{
echo "${'nomR'.$i.$b} = ${'stateR'.$i.$b}<br>";
echo "${'nomI'.$i.$b} = ${'stateI'.$i.$b}<br>";
}
for ( $i = 1; $i <= 3; $i++ )
{
echo "${'nomA'.$i.$b} = ${'stateA'.$i.$b}<br>";
}
echo "---------------------------------------<br>";
}
$b++;
}
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $start), 4);
if ( debug == "1" )
{
echo 'Page generated in '.$total_time.' seconds.'."\n";
}
mysql_close($con);
?>
I can give access to the source, MySQL etc if someone can help, i am learning right now, And i really enjoy how it goes for now, but the AJAX Jquery thing, i completely miss it!!
Thanx a lot!

You could wright more of an abstract question ... no need for php code ...
If i understood you right , you need to send ajax reqests on a specific time interval to get your updated data ( js function setInterval() )
Here is a link about setInterval : http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
Here is link about ajax : http://www.w3schools.com/ajax/
If this answer has nothing to do with your question , please review it and state what you want to do with your data? Show it on each update? or what kind of update?

You could use javascript to trriger ajax script after 1 sec delay use setTimeout() in javascript for delay And in your php page retrieve the data and echo it.

Related

php problems with union select distinct

I submitted these two files:
sample_annotation.txt
sample_synteny.txt
I got on the next page the following error:
304501820180500000018.304501820180500000018<br><br>select distinct org1,org2 from '.304501820180500000018.'_synteny union select distinct org1,org2 from '.304501820180500000018.'_synteny<br><br>
Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''.304501820180500000018.'_synteny union select distinct org1,org2 from '.3045018' at line 1
Whole query: select distinct org1,org2 from '.304501820180500000018.'_synteny union select distinct org1,org2 from '.304501820180500000018.'_synteny[]
The mGSV/lib/data.php looks like below and caused the above error:
<?php
include('database.php');
## Get parameters
$org = $_GET['org'];
$data = $_GET['data'];
$session_id = $_GET['session_id'];
$array = array();
if($data == 'annotation') {
$query = "SELECT track_name FROM ".$session_id."_annotation WHERE org_id like '$org' GROUP BY track_name ";
$result = mysql_query($query);
if($result != ''){
while($row = mysql_fetch_assoc($result)){
array_push($array, $row['track_name']);
}
}
//array_push($syn_array, "10_50_20_70");
}
else if ($data == 'synteny') {
$query = "DESC ".$session_id."_synteny";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
if($row['Field'] == 'id'){ continue; }
if($row['Field'] == 'blocks'){ continue; }
if($row['Field'] == 'SYNcolor'){ continue; }
if(! preg_match("/^org[12]+[_]?[start|end]?/", $row['Field'])){
array_push($array, $row['Field']);
}
}
}
else if ($data == 'size'){
echo "$session_id.", $session_id, "<br>";
echo "$org", $org, "<br>";
$query = "select distinct org1,org2 from '.$session_id.'_synteny union select distinct org1,org2 from '.$session_id.'_synteny";
echo $query,"<br>";
$result = mysql_query($query);
echo $results,"<br>";
if ($results) {
while($row = mysql_fetch_assoc($result)){
echo $row['org1'], "<br>";
$q = "select max(output) as max from (select max(greatest(org1_start, org1_end)) as output from ".$session_id."_synteny where org1 like '" . $row['org1'] . "' union select max(greatest(org2_start, org2_end)) as output from ".$session_id."_synteny where org2 like '" . $row['org1'] . "') as t1";
echo $q, "<br>";
$res = mysql_query($q);
if (!$res) {
die('Could not query:' . mysql_error());
}
echo $row['org1'],"<br>";
echo $row['org2'],"<br>";
if (! isset($array[$row['org1']])){
//echo "add<br>";
$array[$row['org1']] = mysql_result($res,0);
}
$q = "select max(output) as max from (select max(greatest(org1_start, org1_end)) as output from ".$session_id."_synteny where org1 like '" . $row['org2'] . "' union select max(greatest(org2_start, org2_end)) as output from ".$session_id."_synteny where org2 like '" . $row['org2'] . "') as t1";
#echo $q, "<br>";
$res = mysql_query($q);
if (!$res) {
die('Could not query:' . mysql_error());
}
if (! isset($array[$row['org2']])){
//echo "add<br>";
$array[$row['org2']] = mysql_result($res,0);
}
}
}
else {
echo 'Invalid query: ' . mysql_error() . "\n";
echo 'Whole query: ' . $query;
}
}
else if ($data == 'order'){
$query = "select distinct org1 from ".$session_id."_synteny union select distinct org2 from ".$session_id."_synteny ";
//echo $query,"<br>";
$result = mysql_query($query);
$default = array();
while($row = mysql_fetch_assoc($result)){
array_push($default, $row['org1']);
}
$array = join('__ORDER__', $default);
}
else if ($data == 'sorder'){
$query = "select distinct org1,org2 from ".$session_id."_synteny union select distinct org1,org2 from ".$session_id."_synteny ";
//echo $query,"<br>";
$result = mysql_query($query);
$default = array();
$assarr = array();
while($row = mysql_fetch_assoc($result)){
if( ! in_array($row['org1'], $default)){
array_push($default, $row['org1']);
$assarr[sizeof($assarr)] = array();
}
if( ! in_array($row['org2'], $default)){
array_push($default, $row['org2']);
$assarr[sizeof($assarr)] = array();
}
$len_query = "select sum(org1_end) - sum(org1_start) + sum(org2_end) - sum(org1_start) as sum from ".$session_id."_synteny where (org1 like '".$row['org1']."' and org2 like '".$row['org2']."') OR (org1 like '".$row['org2']."' and org2 like '".$row['org1']."')";
$q_result = mysql_query($len_query);
$q_row = mysql_fetch_assoc($q_result);
#echo $len_query,"<br>";
#echo $q_row['sum'],"<br>";
$assarr[array_search($row['org1'], $default)][array_search($row['org2'], $default)] = $q_row['sum'];
#$assarr[array_search($row['org1'], $default)][array_search($row['org2'], $default)] = 1;
$assarr[array_search($row['org2'], $default)][array_search($row['org1'], $default)] = $q_row['sum'];
#$assarr[array_search($row['org2'], $default)][array_search($row['org1'], $default)] = 1;
#echo array_search($row['org1'], $default) . "][ ". array_search($row['org2'], $default) . '<br>';
$assarr[array_search($row['org1'], $default)][array_search($row['org1'], $default)] = 0;
#echo array_search($row['org1'], $default) . "][ ". array_search($row['org1'], $default) . '<br>';
$assarr[array_search($row['org2'], $default)][array_search($row['org2'], $default)] = 0;
#echo array_search($row['org2'], $default) . "][ ". array_search($row['org2'], $default) . '<br>';
}
$a = FindOrder($assarr);
$sugg = array();
//echo sizeof($a),'<br>';
foreach($a as $b){
//echo $default[$b],"<br>";
array_push($sugg, $default[$b]);
}
$array = join('__ORDER__', $sugg);
}
function FindOrder($graph){
$r = array();
$last = -1;
while(!isEmpty($graph)){
$start = leastEdges($graph);
$path = longestPath($graph, $start, 0);
$path = completeCycle($graph, $path);
if($path[0] != $last){
array_push($r, $path[0]);
}
for($x = 1; $x < sizeof($path); $x++){
array_push($r, $path[$x]);
}
$last = $path[sizeof($path)-1];
$graph = removePath($graph, $path);
}
return $r;
}
function longestPath($graph, $cur, $len){
$path = array();
array_push($path, $cur);
$longestSubpath = array();
for($x = 0; $x < sizeof($graph); $x++){
if($graph[$cur][$x] != 0){
$subpath = longestPath(removeVertex($graph, $cur), $x, $len + $graph[$cur][$x]);
if(sizeof($subpath) > sizeof($longestSubpath)){
$longestSubpath = $subpath;
}
}
}
foreach($longestSubpath as $x){
array_push($path, $x);
}
return $path;
}
function completeCycle($graph, $path){
$graph = removePath($graph, $path);
$last = $path[sizeof($path)-1];
for($x = 0; $x < sizeof($graph); $x++){
if($graph[$last][$x] != 0){
array_push($path, $x);
return $path;
}
}
return $path;
}
function removePath($graph, $path){
for($x = 0; $x < sizeof($path) - 1; $x++){
$arr = $path[$x]; //***forgot the $ in front of path***
$b = $path[$x+1]; //***forgot the $ in front of path***
$graph[$arr][$b] = 0;
$graph[$b][$arr] = 0;
}
return $graph;
}
function removeVertex($graph, $vtx){
if($vtx < 0 || $vtx >= sizeof($graph)){
return copy($graph);
}
for($x = 0; $x < sizeof($graph); $x++){
$graph[$x][$vtx] = 0;
$graph[$vtx][$x] = 0;
}
return $graph;
}
function numEdges($vtx){
$r = 0;
foreach($vtx as $x){
if($x != 0){
$r++;
}
}
return $r;
}
function leastEdges($graph){
$r = -1;
$min = 2147483647;
for($x = 0; $x < sizeof($graph); $x++){
$e = numEdges($graph[$x]);
if($e != 0 && $e < $min){
$r = $x;
$min = $e;
}
}
return $r;
}
function isEmpty($arr){
$r = true;
foreach($arr as $x){
$r = $r && numEdges($x) == 0;
}
return $r;
}
## Return the JSON object
echo json_encode($array);
?>
I created a docker-compose.yml and the can be run in the following way:
git clone https://github.com/mictadlo/mGSV-docker.git
docker-compose up --build
The service can be accessed via localhost and PhpMyAdmin can be accessed via localhost:8183
What did I miss?
Thank you in advance
Try to run independently both query in your Mysql phpmyadmin
select distinct org1,org2 from '.304342020180200000016.'_synteny
select distinct org1,org2 from '.304342020180200000016.'_synteny
As i see your query seems to be correct since union requires the same numbers of columns and same data type.
And why is your table name in the union query is both the same.

Pagination not showing results on next page

Looking for some help please. I am using the following code to filter and show results which works fine. My problem is the results aren't passing on to the second page so the page becomes blank no errors. very new to this so all help is welcome.
$num_rec_per_page=2;
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("searchresults") or die("ERROR");
if (!isset($_POST['submit'])) exit();
$vars = array('companyname','location');
$verified = TRUE;
foreach ($vars as $v) {
if (!isset($_POST[$v]) || empty($_POST[$v])) {
$verified = FALSE;
}
}
if (!$verified) {
echo "Sorry no results found, please enter your search";
exit();
}
// isset function is also used in checking for the existence of data in $_POST
if (isset($_POST["companyname"]) && $_POST["companyname"] != '') {
$companyname = mysql_real_escape_string($_POST["companyname"]);
$companyname = " AND (companyname LIKE '%$companyname%')";
}
if (isset($_POST["location"]) && $_POST["location"] != '') {
$location = mysql_real_escape_string($_POST["location"]);
$location = " AND (location LIKE '%$location%')";
}
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $num_rec_per_page;
$sql = "SELECT * FROM reviewsandtips WHERE member_id > 0". $companyname . $location . "LIMIT $start_from, $num_rec_per_page";
$sql_result = mysql_query($sql) or die (mysql_error());
// now echo the code for the table heading
if (mysql_num_rows($sql_result)>0) {
while ($row = mysql_fetch_assoc($sql_result)) {
}
$sql = "SELECT * FROM reviewsandtips WHERE member_id > 0". $companyname . $location;
$sql_result = mysql_query($sql); //run the query
$total_records = mysql_num_rows($sql_result); //count number of records
$total_pages = ceil($total_records / $num_rec_per_page);
echo "<a href='codetest.php?page=1'>".'|<'."</a> "; // Goto 1st page
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='codetest.php?page=".$i."'>".$i."</a> ";
}
echo "<a href='codetest.php?page=$total_pages'>".'>|'."</a> "; // Goto last page
} else {
echo '<tr><td colspan="5">No results found.</td></tr>';
}

SQL Connection creates excessive concurrent HTTP connections to the host

I kept commenting parts of my PHP script till this is what I ended up with. This thing creates about 200 to 300 concurrent connections in under a minute to the SQL ip (checked from the gateway) and I don't understand why.
Shouldn't closing the SQL connection end the communication between the servers?
The php script is being called once a second via JavaScript, I'm the only user on the website.
PHP implementation of the sock (taken from the net, fclose() added as that's how I read socks are closed)
<?php
$cookie="tD2h6";
$data = $_COOKIE[$cookie];
parse_str($data, $output);
$name = $output['name'];
$pass = $output['pass'];
$con=mysqli_connect("89.33.242.99","global","changeme","global");
$sql = 'SELECT * FROM `users` WHERE `username`=?';
# Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
# Execute statement
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if($row['password']===$pass && !empty($pass))
{
$hisusername = $name;
$hiscredits = $row['credits'];
$hiseuro = $row['euro'];
}
else
{
$hisusername = "Guest";
$hiscredits = "0";
$hiseuro = "0";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM `users`");
$num_rows = mysqli_num_rows($result);
$result = mysqli_query($con,"SELECT * FROM `users` WHERE admlevel>0");
$num_admrows = mysqli_num_rows($result);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM jbchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$jbchat = $jbchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM frchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$frchat = $frchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM drchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$drchat = $drchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM cschat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$cschat = $cschat . $data[$i] . "<br>";
}
$today = getdate();
$date = $today['mday'] . "/" . $today['mon'] . "/" . $today['year'];
if($today['minutes']>9)
$time = $today['hours'] . ":" . $today['minutes'];
else
$time = $today['hours'] . ":0" . $today['minutes'];
$sqlx = 'SELECT * FROM notifications WHERE username=? ORDER BY id DESC LIMIT 5';
# Prepare statement
$stmt = $con->prepare($sqlx);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sqlx . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
$stmt->execute();
$res = $stmt->get_result();
while($row = $res->fetch_assoc())
{
if($row['read']==0)
$nnumber = $nnumber+1;
$notifications = $notifications . "
<li>
<a href=\"#\" onclick=\"invisphp2('http://r4ge.ro/php/readnotif.php?notifid=" . $row['id'] . "')\">
<i class=\"fa fa-warning danger\"></i>" . $row['text'] . "
<br>" . $row['date'] . "
</a>
</li>";
}
$result = mysqli_query($con,"SELECT * FROM chat ORDER BY id DESC LIMIT 30");
$data = array();
$i=1;
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['name'] . ": " . $row['msg'];
$i=$i+1;
}
for($i=30;$i>0;--$i)
{
$lchat = $lchat . $data[$i] . "<br>";
}
echo json_encode(array(
"registered" => $num_rows,
"admins" => $num_admrows,
"time" => $time,
"date" => $date,
"nnumber" => $nnumber,
"notifications" => $notifications,
"lchat" => $lchat,
"hisusername" => $hisusername,
"hiscredits" => $hiscredits,
"hiseuro" => $hiseuro
));
mysqli_close($con);
?>
Edit: after listening to a comment that's now deleted, I removed every single query except the first one, so this code is now being ran, the connections still rocketed to 150 in 20-30 seconds.
<?php
$cookie="tD2h6";
$data = $_COOKIE[$cookie];
parse_str($data, $output);
$name = $output['name'];
$pass = $output['pass'];
$con=mysqli_connect("89.33.242.99","global","changeme","global");
$sql = 'SELECT * FROM `users` WHERE `username`=?';
# Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
# Execute statement
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if($row['password']===$pass && !empty($pass))
{
$hisusername = $name;
$hiscredits = $row['credits'];
$hiseuro = $row['euro'];
}
else
{
$hisusername = "Guest";
$hiscredits = "0";
$hiseuro = "0";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo json_encode(array(
"registered" => $num_rows,
"admins" => $num_admrows,
"time" => $time,
"date" => $date,
"nnumber" => $nnumber,
"notifications" => $notifications,
"lchat" => $lchat,
"hisusername" => $hisusername,
"hiscredits" => $hiscredits,
"hiseuro" => $hiseuro
));
mysqli_close($con);
?>
I know this will make me look very bad.
Unfortunately there is nothing bad in this particular code.
The problem was at a much deeper level in the site's framework, and the above code being the homepage, lead me to think it was the source of the problem.
To #developerwjk , the answer is no, combining procedural and object oriented implementations has no effect whatsoever on the functionality of mysqli, it works great.
The culprit: lack of mysqli_close() at the end of every single PHP that creates a connection
Don't trust the documentation when it says the connection is closed on script end, put it there just to be safe.

array pulling out no results

public function GetRoomTotalForDay($room, $date = null) {
if(!isset($date)) {
$date = date("Y-m-d");
}
// This function is going to return the number of shoes processed that day
// First of all work out which scanner number is required for the room
$scanner = $this->GetScannerNumber($room);
// Next generate the SQL
$sql = "SELECT `scanners.KordNo`, `scanners.BundleNumber`
FROM `scanners`
WHERE `scanners.Date` = '" . $date . "'
AND `scanners.Scanner` IN (";
foreach($scanner as $x) {
$sql .= $x . ",";
}
$sql .= "0);";
// And query the database
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$return[] = $row;
}
// It is more complicated for Kettering, Closing & Rushden, we need to filter the list
if(in_array($room, array(3,4,5))) {
foreach($return as $x) {
$sql = "SELECT `scanners.Scanner`
FROM `scanners`
WHERE `scanners.KordNo` = " . $x['scanners.KordNo'] . "
AND `scanners.BundleNumber` = " . $x['scanner.BundleNumber'] . "
ORDER BY `scanners.Date` DESC
LIMIT 1,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
// If scanner 7, it's been through bottom stock so need to find previous
if($row[0] == 7) {
$sql = "SELECT `scanners.Scanner`
FROM `scanners`
WHERE `scanners.KordNo` = " . $x['scanners.KordNo'] . "
AND `scanners.BundleNumber` = " . $x['scanners.BundleNumber'] . "
ORDER BY `scanners.Date` DESC
LIMIT 2,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
}
if($row[0] == 10 && $room == 3) {
$finalReturn[] = $x;
} elseif($row[0] == 11 && $room == 4) {
$finalReturn[] = $x;
} elseif($row[0] == 15 && $room == 5) {
$finalReturn[] = $x;
}
}
$return = $finalReturn;
}
// Now we have a list of tickets, we need to query how many pairs are in each ticket
$total = 0;
foreach($return as $x) {
$sql = "SELECT `QtyIssued`
FROM `ArchiveBundle`
WHERE `ArchiveBundle.KordNo` = '" . $x['scanners.KordNo'] . "'
AND `ArchiveBundle.BundleNumber` = '" . $x['scanners.BundleNumber'] . "';";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$total += $row[0];
}
return $total;
}
I have edited the class above which pulls no results. However the original class below pulls results out. Please can someone help.
public function GetRoomTotalForDay($room, $date = null) {
if(!isset($date)) {
$date = date("Y-m-d");
}
// This function is going to return the number of shoes processed that day
// First of all work out which scanner number is required for the room
$scanner = $this->GetScannerNumber($room);
// Next generate the SQL
$sql = "SELECT `KordNo`, `BundleNumber`
FROM `scanners`
WHERE `Date` = '" . $date . "'
AND `Scanner` IN (";
foreach($scanner as $x) {
$sql .= $x . ",";
}
$sql .= "0);";
// And query the database
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$return[] = $row;
}
// It is more complicated for Kettering, Closing & Rushden, we need to filter the list
if(in_array($room, array(3,4,5))) {
foreach($return as $x) {
$sql = "SELECT `Scanner`
FROM `scanners`
WHERE `KordNo` = " . $x['KordNo'] . "
AND `BundleNumber` = " . $x['BundleNumber'] . "
ORDER BY `Date` DESC
LIMIT 1,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
// If scanner 7, it's been through bottom stock so need to find previous
if($row[0] == 7) {
$sql = "SELECT `Scanner`
FROM `scanners`
WHERE `KordNo` = " . $x['KordNo'] . "
AND `BundleNumber` = " . $x['BundleNumber'] . "
ORDER BY `Date` DESC
LIMIT 2,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
}
if($row[0] == 10 && $room == 3) {
$finalReturn[] = $x;
} elseif($row[0] == 11 && $room == 4) {
$finalReturn[] = $x;
} elseif($row[0] == 15 && $room == 5) {
$finalReturn[] = $x;
}
}
$return = $finalReturn;
}
// Now we have a list of tickets, we need to query how many pairs are in each ticket
$total = 0;
foreach($return as $x) {
$sql = "SELECT `QtyIssued`
FROM `ArchiveBundle`
WHERE `KordNo` = '" . $x['KordNo'] . "'
AND `BundleNumber` = '" . $x['BundleNumber'] . "';";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$total += $row[0];
}
return $total;
}
The class above counts the amount of shoes produced. I have had to edit this class so it can exclude certain types of shoes but it does not seem to pull any results for some reason.
UPDATE.
This is the class scanners. This is what its currently at the moment. I'm fairly new to php and this code was writted by my predecessor.
<?php
class CHScanners {
var $conn;
// Constructor, connect to the database
public function __construct() {
require_once "/var/www/reporting/settings.php";
define("DAY", 86400);
if(!$this->conn = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD)) die(mysql_error());
if(!mysql_select_db(DB_DATABASE_NAME, $this->conn)) die(mysql_error());
}
public function ListRoomBundles($room, $date, $dateTo = null) {
// If dateTo hasn't been set, make it now
if(!isset($dateTo) or $dateTo == "") {
$dateTo = $date;
}
// Return an array with each bundle number and the quantity for each day
$scanner = $this->GetScannerNumber($room);
$sql = "SELECT * FROM `scanners` WHERE `Scanner` IN (";
foreach($scanner as $x) {
$sql .= $x . ",";
}
$sql .= "0)
AND `Date` BETWEEN '" . $date . "' AND '" . $dateTo . "'
GROUP BY `KordNo`, `BundleNumber`;";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$sql = "SELECT `BundleReference`, `QtyIssued`, `WorksOrder`
FROM `ArchiveBundle`
WHERE `KordNo` = '" . $row['KordNo'] . "'
AND `BundleNumber` = '" . $row['BundleNumber'] . "';";
$result2 = mysql_query($sql);
while($row = mysql_fetch_array($result2)) {
if($row[0] != "") {
$final[] = $row;
} else {
$final[] = array("Can't find bundle number", "N/A");
}
}
}
return $final;
}
public function GetRoomTotalForDay($room, $date = null) {
if(!isset($date)) {
$date = date("Y-m-d");
}
// This function is going to return the number of shoes processed that day
// First of all work out which scanner number is required for the room
$scanner = $this->GetScannerNumber($room);
// Next generate the SQL
$sql = "SELECT `scanners.KordNo`, `scanners.BundleNumber`
FROM `scanners,TWOrder,Stock`
INNER JOIN TWORDER ON `scanners.KordNo` = `TWOrder.KOrdNo`
AND `scanners.Date` = '" . $date . "'
INNER JOIN Stock ON `TWOrder.Product` = `Stock.ProductCode`
AND `Stock.ProductGroup` NOT BETWEEN 400 AND 650
AND `scanners.Scanner` IN (
ORDER BY `scanners.KordNo' ASC";
foreach($scanner as $x) {
$sql .= $x . ",";
}
$sql .= "0);";
// And query the database
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$return[] = $row;
}
// It is more complicated for Kettering, Closing & Rushden, we need to filter the list
if(in_array($room, array(3,4,5))) {
foreach($return as $x) {
$sql = "SELECT `scanners.Scanner`
FROM `scanners`
WHERE `scanners.KordNo` = " . $x['scanners.KordNo'] . "
AND `scanners.BundleNumber` = " . $x['scanners.BundleNumber'] . "
ORDER BY `scanners.Date` DESC
LIMIT 1,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
// If scanner 7, it's been through bottom stock so need to find previous
if($row[0] == 7) {
$sql = "SELECT `scanners.Scanner`
FROM `scanners`
WHERE `scanners.KordNo` = " . $x['scanners.KordNo'] . "
AND `scanners.BundleNumber` = " . $x['scanners.BundleNumber'] . "
ORDER BY `Date` DESC
LIMIT 2,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
}
if($row[0] == 10 && $room == 3) {
$finalReturn[] = $x;
} elseif($row[0] == 11 && $room == 4) {
$finalReturn[] = $x;
} elseif($row[0] == 15 && $room == 5) {
$finalReturn[] = $x;
}
}
$return = $finalReturn;
}
// Now we have a list of tickets, we need to query how many pairs are in each ticket
$total = 0;
foreach($return as $x) {
$sql = "SELECT `QtyIssued`
FROM `ArchiveBundle`
WHERE `KordNo` = '" . $x['scanners.KordNo'] . "'
AND `BundleNumber` = '" . $x['scanners.BundleNumber'] . "';";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$total += $row[0];
}
return $total;
}
// We need a function to select the previous Monday from a given date
public function GetPreviousMonday($timestamp) {
if(date("N", $timestamp) == 1) {
return $timestamp;
} elseif(in_array(date("N", $timestamp), array(2, 3, 4, 5))) {
return $timestamp - (date("N", $timestamp)-1)*DAY;
} elseif(in_array(date("N", $timestamp), array(6, 7))) {
return $timestamp + (date("N", $timestamp)*(-1)+8)*DAY;
} else {
return false;
}
}
public function GetRoomName($room) {
// Return the room name from the room number
switch($room) {
case 1:
return "Skin Room";
case 2:
return "Clicking Room";
case 3:
return "Kettering";
case 4:
return "Closing Room";
case 5:
return "Rushden";
case 6:
return "Assembly Room";
case 7:
return "Lasting Room";
case 8:
return "Making Room";
case 9:
return "Finishing Room";
case 10:
return "Shoe Room";
}
}
public function GetDueDateForWorksOrder($worksOrderNumber) {
$sql = "SELECT `DueDate`
FROM `TWOrder`
WHERE `WorksOrderNumber` = '" . $worksOrderNumber . "';";
mysql_select_db(DB_DATABASE_NAME, $this->conn);
$result = mysql_query($sql, $this->conn);
$row = mysql_fetch_row($result);
return $row[0];
}
private function GetScannerNumber($room) {
// Get the room number from the scanner number
switch($room) {
case 1:
$scanner = array(3);
break;
case 2:
$scanner = array(10,11,15);
break;
case 3:
$scanner = array(5);
break;
case 4:
$scanner = array(5);
break;
case 5:
$scanner = array(5);
break;
case 6:
$scanner = array(6);
break;
case 7:
$scanner = array(9);
break;
case 8:
$scanner = array(8);
break;
case 9:
$scanner = array(12);
break;
case 10:
$scanner = array(14);
break;
default:
$scanner = array(0);
break;
}
return $scanner;
}
}
?>
You have a typo - a letter is missing in the last line of this block of code:
if(in_array($room, array(3,4,5))) {
foreach($return as $x) {
$sql = "SELECT `scanners.Scanner`
FROM `scanners`
WHERE `scanners.KordNo` = " . $x['scanners.KordNo'] . "
AND `scanners.BundleNumber` = " . $x['scanner.BundleNumber'] .
Here the array item should be $x['scanners.BundleNumber'].

Session variables working when testing with Chrome and IE but not Firefox

I'm writing a quiz program using PHP and a bit of Javascript. The questions can be answered correctly when IE or Chrome is used but Firefox refreshes the page and increments the session variable.
Here's a code snippet:
if(isset($_GET['answer1']))
{
if($_GET['answer'] == $_GET['answer1'])
{
include 'config.php';
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db, $con);
$userId = $_SESSION['userId'];
$wordNow = $_SESSION['word'];
$sql3 = "SELECT * FROM userAccomplishments Where UserId = '$userId' AND
word = '$wordNow'";
$result3 = mysql_query($sql3);
if (mysql_num_rows($result3) == 0) {
$sql4 = "SELECT wordId from allwords WHERE word = '$wordNow'";
$result = mysql_query($sql4);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting from random number";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
$wordId = $row["wordId"];
// echo $row["word"] . " " ."<BR>" ;
}
list($usec, $sec) = explode(' ', microtime());
$script_end = (float) $sec + (float) $usec;
$elapsed_time = (float)($script_end - $script_start);
$elapsed_time = $_GET['formvar'];
$sql2 = "INSERT INTO userAccomplishments (UserId, word, TimeTaken, wordId)
VALUES ('$userId', '$wordNow', '$elapsed_time', '$wordId')";
echo 'You got '. $wordNow . ' in ' .$elapsed_time . ' seconds. <BR><BR>';
$result = mysql_query($sql2);
}
$_SESSION['views'] = $_SESSION['views'] + 1;
}
else
{
$_SESSION['views'] = $_SESSION['views'] + 1;
echo 'Keep studying <BR>';
}
}
else
{
$_SESSION['views'] = 1;
}
Doesn't look like you're calling session_start(). Make sure you call it to get your session in gear! Woo! Yeah!

Categories