I have a problem with my queries at my MySQL database. I have to represent some variables in a graph.
So far I have
JavaScript that reads what variables I have to represent and POST with Ajax
PHP code to handle the POST
My PHP code has a POST function that does a query with inner joins depending if my variables are in the same table or not. This query obtains a table with datetime and all the variables. This POST function works well, I tested it.
The problem is when I want to represent more than 4 variables. If I want to represent 5 variables, I can represent less than 97,000 rows. If I want to represent 6 variables, I can represent less than 86,000 rows (each time I add a variable I lose around 11,000 rows).
My javascript code
jQuery.extend({
llamada: function() {
var result=null;
$.ajax({
type:'POST',
async: false,
dataType: 'json',
url:"includes/mysql.php",
data: { tarea:'ejecutarQuery',
table: varNames,
columna: varLocations
},
success: function(respuesta){
alert(respuesta);
/*result=respuesta;*/
}
});
return result;
}
});
var myServerData = $.llamada();
The post function in mysql.php
if($_POST["tarea"]=="ejecutarQuery"){
$columnas = $_POST["columna"];
$tablas = $_POST["table"];
$tablacolumna = array();
$frasecolumnas="";
for($j=0;$j<count($columnas);$j++){
$tablacolumna[$j]=$tablas[$j].".".$columnas[$j];
if($j==0){
$frasecolumnas=$tablacolumna[0];
}
else{
$frasecolumnas=$frasecolumnas.",".$tablacolumna[$j];
}
}
$tablasdiferentes= array();
$tablasdiferentes[0]=$tablas[0];
$contador=0;
for($j=1;$j<count($tablas);$j++){
for($i=0;$i<count($tablasdiferentes);$i++){
if($tablas[$j]==$tablasdiferentes[$i]){
break 1;
}
if($i==$contador){
$tablasdiferentes[$i+1]=$tablas[$j];
$contador++;
}
}
}
$frasetablas="FROM ".$tablas[0]." ".$tablas[0]." ";
$fraseError =" where ".$tablas[0].".ErrorBit=0";
for($j=1;$j<count($tablasdiferentes);$j++){
$frasetablas=$frasetablas."inner join ".$tablasdiferentes[$j]." ".$tablasdiferentes[$j]." on ".$tablas[0].".datetime=".$tablasdiferentes[$j].".datetime ";
$fraseError =$fraseError." and ".$tablasdiferentes[$j].".ErrorBit = 0";
}
$sql="SELECT ".$tablas[0].".datetime,".$frasecolumnas." ".$frasetablas.$fraseError.";";
$rawdata=getArraySQL($sql);
echo json_encode($rawdata);
}
method getArraySQL
function getArraySQL($sql){
$conexion = conectarBD();
mysql_set_charset('utf8',$conexion);
if(!$result = mysqli_query($conexion, $sql)) die(mysql_error);
$rawdata = array();
$i=0;
while($row = mysqli_fetch_array($result,MYSQL_NUM))
{
$time = $row[0];
$date = new DateTime($time);
$row[0] = $date->getTimestamp()*1000;
$rawdata[$i] = $row;
$i++;
}
desconectarBD($conexion);
return $rawdata;
}
I think that the problem may be that the while loop does not finish depending on the number of variables. I suppose it is because of the array's memory size.
Can anybody help me?
Related
How do I add a new value to each row of my JSON. I'm currently pulling multiple rows of data and storing in a variable that I'll turn into JSON to be returned in my ajax call but I want to add one more value into each row.
This is my php code. I want to change json before I encode it to add another value called mark that stores an int to each row.
if($json = mysqli_fetch_all ($stmt, MYSQLI_ASSOC)){
} else{
$json['max'] = true;
}
echo json_encode($json);
This is my ajax call
$.ajax({
url: "infinite.php",
method: "POST",
data: {start: start, reachedMax: reachedMax},
dataType: "JSON",
success: function(data){
if(data.max || reachedMax){
reachedMax = true;
return;
}
}
Add a foreach loop right after you retrieve the database result. In this loop you add new values to all elements:
if ($json = mysqli_fetch_all($stmt, MYSQLI_ASSOC)) {
foreach (array_keys($json) as $key) {
$json[$key]['mark'] = 23;
}
} else {
$json['max'] = true;
}
echo json_encode($json);
I am using PHP to retrieve some records from a MySQL database, I would like to send these to my AJAX and loop through them, in order to prepend rows to an existing table.
However I can only see the last (most recent) record returned from my query. Could someone please point out where I am going wrong?
AJAX:
$.ajax({
type: "POST",
url: 'feed.php',
data: {lastSerial: true},
dataType: 'json',
success: function(data){
console.log(data); // logs `{Direction: "O", CardNo: "02730984", SerialNo: 20559303}`
$.each(data, function(key, value) {
// here I want to loop through the returned results - for example
$("#transactionTable").prepend('<tr><td>'+ SerialNo +'</td><td>'+ CardNo +'</td><td>'+ Direction +'</td></tr>');
});
}
});
feed.php
if(isset($_POST['lastSerial']) && $_POST['lastSerial'] == true) {
$query = "SELECT TimeStamp, Direction, CardNo, SerialNo FROM Transactions";
// this query returns approx. 20 results
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$data["Direction"] = $row['Direction'];
$data["CardNo"] = $row['CardNo'];
$data["SerialNo"] = $row['SerialNo'];
}
echo json_encode($data);
}
Also in my PHP, should I be using a while or if statement?
You're using a single $data object and resetting its contents each time. You want to build an array of objects:
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = array(
"Direction" => $row['Direction'],
"CardNo" => $row['CardNo'],
"SerialNo" => $row['SerialNo']
);
}
echo json_encode($data);
Followed by:
success: function(data) {
$.each(data, function(key, value) {
$("#transactionTable").prepend(
'<tr><td>' + value.SerialNo + '</td>' +
'<td>' + value.CardNo + '</td>' +
'<td>'+ value.Direction +'</td></tr>');
});
}
In your feed.php you loop through the results, but on each loop you overwrite the data. Thus, you are only returning the last result from the database to the AJAX request.
Many solutions exist, but you have to do something like
$data["Direction"][] = $row['Direction'];
$data["CardNo"][] = $row['CardNo'];
$data["SerialNo"][] = $row['SerialNo'];
or better:
$data[] = $row;
Since you dont change the key, you can use the last option. With jQuery you can loop over it, and access the data with value.Direction, value.CardNo, value.SerialNo
note: not tested
In this code I am getting posts from database in table, table displays posts in three columns, now I want to add some jQuery to limit the number of rows and add a button which on clicking appends few rows to table I am not a professional programmer may be something like slice should be used to limit number of rows.
$sql = "SELECT * FROM posts";
$query = $db->prepare($sql);
$query->execute();
<table>
<tr>
<?php do { //horizontal looper?>
<td>
<div>id</div>
<div>title</div>
<div>body</div>
<div>date</div>
</td>
<?php
$row = $query->fetch(PDO::FETCH_ASSOC);
if (!isset($nested_List)) {
$nested_List= 1;
}
if (isset($row) && is_array($row) && $nested_List++%3==0) {
echo "</tr><tr>";
}
} while ($row); //end horizontal looper
?>
</table>
HTML
Create your table (You can also create dynamically)
<table id='posts'>
<tbody></tbody>
</table>
<button id='load-more-entries'>Load</button>
JavaScript
Create a variable for keeping track of what result you are on. What the index of the last result you grabbed.
Grab the elements by id. attach listener to button so when you click you load more results. Take a look at AJAX documentation. It is very simple and short.
var index = 0;
var load, table;
load = document.getElementById('load_more_entries'),
table = document.getElementById('posts');
load.addEventListener('click', function(e){
processAjaxRequest({
type: 'get',
url: "posts.php?index="+index,
success: function(xmlhttp){
var results = JSON.parse(xmlhttp.response);
for(var i = 0; i < results.length; ++i){
var row = table.insertRow();
var cell = row.insertCell(cell_index);
//increment index according to how many results you
grab so next time you grab the next results
index++;
}
},
error: function(xmlhttp){
//Handle error
}
});
});
/*
this function here it is a a wrapped AJAX
it will call php file below and run it. It will fetch the results
form database and return them to you in form of a string. You need
to parse it JSON.parse() to turn it into an array
*/
function processAjaxRequest(object){
var xmlhttp = new XMLHttpRequest() ||
new ActiveXObject('Microsoft.XMLHTTP');
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4){
if(xmlhttp.status === 200){
object.success(xmlhttp);
}else{
object.error(xmlhttp);
}
}
}
xmlhttp.open(object.type, object.url, true);
xmlhttp.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
xmlhttp.send(object.args);
};
PHP
This file is called by processAjaxResquest
$posts = array();
while($post = mysqli_fetch_assoc($sql)){
$posts[] = $post;
}
echo json_encode($posts);
?>
*NOTE I have not tested the code there maybe a couple of thing I may have left of. However, this should be enough to get you started. I got the same kind of answer when I had this question. Also, note that there is also more things you need to be aware of; like checking the variables inside PHP file are set before you do anything.
Why does this code work fine in the unit test, but not in the page? I have Firebug and FirePHP in place and can see the variable pass just fine if I hard code it, the operation is passing an int just fine in the unit test, but I've tried parseInt, Math.floor, and many other wacky methods and the value for statementCount simply won't post.
The ajax:
//polling code
var statementCount = 0;
(function poll(){
setTimeout(function(){
$.ajax({ url: "RROO_update.php",
type: "POST",
data: {'meetID': 2176, 'statementCount': statementCount},
success: function(data){
if(data.length > 0){
var statements = JSON.parse(data);
//reset the statement count
statementCount = statementCount + statements.length;
$(this).actplug_RROO('formatReturns', statements, userID);
poll();
}
},
error: function(){
poll();
},
});
}, 5000);
})();
and the php:
<?php
include("../inc/variables.php");
error_reporting (E_ALL ^ E_NOTICE);
require_once('../FirePHPCore/FirePHP.class.php');
require_once('../FirePHPCore/fb.php');
$firephp = FirePHP::getInstance(true);
ob_start();
$MeetingID = $_POST['meetID'];
$StatementCount = (int)$_POST['statementCount'];
$firephp-> log($StatementCount, 'Statement count passed in' );
$Finished = FALSE;
while($Finished == FALSE){
$MeetingStats = mysql_query("SELECT RROO_UPDATE.*, MEMBER.UserName, MEMBER.UserImage FROM RROO_UPDATE JOIN MEMBER ON RROO_UPDATE.MemberID = MEMBER.MemberID WHERE MeetingID = $MeetingID ORDER BY TimeStamp DESC", $DB_Connection);
$MyNum = mysql_num_rows($MeetingStats);
$firephp->log($MyNum, 'Row Query');
if($MyNum > $StatementCount){
$Returns = array();
while($Return = mysql_fetch_array($MeetingStats)){
array_push($Returns, $Return);
}
$NewReturns = array();
$NewStats = $MyNum - $StatementCount;
$firephp->log($NewStats, 'heres the new stats count');
for($i = 0; $i < $NewStats; $i++){
array_push($NewReturns, $Returns[$i]);
}
$Here = count($NewReturns);
$firephp->log($Here, 'The length of the new returns array');
$Finished = TRUE;
echo json_encode($NewReturns);
}
else{
sleep(3);
}
}
?>
Like I said, it comes back fine on the unit test which is the same in all the aspects I can see (I actually copy pasted it into the page) the only difference being that the postback is routed differently on the page (to the plugin) but I've messed around with callback to no avail. Is there some reason the statementCount won't reset and Post in this code?
I don't think that statementCount is defined inside the callback, only in the function which executes the ajax call.
Here is a question and answer which should help you do what you want.
i am trying to get the data which is in array, from an SQL query to the ajax success data. Here is the code i tried,
function adminchecksub(value1){
//alert('hi');
var value1=$('#adminsid').val();
//alert(value1);
if(value1==''){
alert('Please enter a Sub id');
}
else{
//alert(value1);
$.ajax({
type: 'POST',
url: root_url + '/services/services.php?method=adminsubcheck',
data: {value1:value1},
async: true,
success: function (data) {
alert(data);
if (data == 1) {
alert('inside');
//window.location.assign(rdurl+"?sid="+sid);
return true;
} else {
//alert('does not exist!');
//alert('outside');
return false;
}
}
});
}
now in the php method which is requested from the above ajax call, i have to get the data return by this function which is returning an array
function adminsubcheck($sid){
$subid=$sid['value1'];
$row = array();
//echo $subid;
$query = "SELECT Sub_id,Status,Sub_type FROM Sub WHERE Sub_id=$subid";
//echo $query;
//echo $subid;
$queryresult = mysql_query($query);
$count = mysql_num_rows($queryresult);
//echo $count;
while ($r = mysql_fetch_assoc($queryresult)) {
$row[] = $r;
}
return $row;
}
here $row is returning an array as data to the ajax function, where i need to get all the items seperately. Some one help me out to get the values into the ajax call. Thanks in advance..
In your PHP file, you can return your array as a json object in the following way (notice how the PHP file echos the result to pass it back to javascript)
...
$json = json_encode($row);
echo $json
Now add the following to your javascrip ajax
$.ajax({
...
// Whatever code you currently have
...
}).done(function ( json ) {
var data = JSON.parse(json);
//Continue with javascript
});
You can handle the java script variable 'data' as an associative array like it was in PHP
also, look how you populate the php variable $row and adjust the following way:
$cnt = 0;
while ($r = mysql_fetch_assoc($queryresult)) {
$row[$cnt] = $r;
$cnt++;
}
$json = json_encode($row);
echo $json;
in javascript you can access your rows the following way in teh data variable:
var value = data[0]['field_name'];
in the above statement, 0 will correspond to the value of $cnt (i.e. mysql returned row number)
return $row;
replace like this
echo json_encode($row);
and add dataType='json' in ajax like this
dataType: 'json',
If you want get the value in ajax call i think it shoul be :
while ($r = mysql_fetch_assoc($queryresult)) {
$row[] = $r;
}
echo json_encode(array('data'=>$row));
exit;