how to retrieve selected data from database based on selected checkbox in proper JSON format for highcharts - json

sorry for disturbing...I got json format to build column highcharts that will accept data from user multiple selected via checkbox and retrieve the data result from database based on what they check at checkbox and display by highcharts in form of column chart..
The problem is,I think my json format for column highcharts is not correct can anyone see my code and tell me what wrong with this....below this is the json output and the code..:- Thank u very much for your time..
Let say if I checked 2 checkbox from the checkboxes list (BAT123 & BIO22), this json will displayed like this:
[{"name":"Subject","data":["BAT123"]},{"name":"Result","data":[3.03]}]
[{"name":"Subject","data":["BAT123","BIO222"]},{"name":"Result","data":[3.03,1.05]}]
I know that json format is wrong, I tried to fixed it but still failed..I am a newbie..hope u can try to fix my code below.
Here is the json code:
<?php
if(isset($_GET['iddoc'])) //iddoc is the value from selected checkbox
{
$category = array();
$category['name'] = 'Subject';
$series1 = array();
$series1['name'] = 'Result';
foreach ($_GET['iddoc'] as $iddoc)
{
$query="select * from compareresult where iddocument=$iddoc";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while($r = mysql_fetch_assoc($sql_query))
{
$category['data'][] = $r['subject'];
$series1['data'][] = $r['result'];
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
$jsonTable = json_encode($result, JSON_NUMERIC_CHECK);
echo $jsonTable;
}
}
?>

Related

How to solve sql error " product portfolio has diversified to encompass a highly successful multi-brand' at line 1"

I am kind of new one for mysql and php. a week ago this code worked perfectly and when now I am trying it shows this error message
Error : You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 's product portfolio has diversified to encompass a highly
successful multi-brand' at line 1
I search how to solve that after spending a whole day, but couldn't figure it out.
I have tried similar questions here in stackoverflow, Yet I am stucked here.
A help would be really admired
Given below is my code
<?php
if(isset($_POST['upload']))
{ $company_name =$_POST['company_name'];
$service =$_POST['service'];
$email =$_POST['email'];
$password =$_POST['password'];
$details =$_POST['details'];
$fileName = $_FILES['Filename']['name'];
$fileName1 = $_FILES['Filename1']['name'];
$fileName2 = $_FILES['Filename2']['name'];
$fileName3 = $_FILES['Filename3']['name'];
$fileName4 = $_FILES['Filename4']['name'];
$target = "company_images/";
$fileTarget = $target.$fileName;
$fileTarget1 = $target.$fileName1;
$fileTarget2 = $target.$fileName2;
$fileTarget3 = $target.$fileName3;
$fileTarget4 = $target.$fileName4;
$tempFileName = $_FILES["Filename"]["tmp_name"];
$tempFileName1 = $_FILES["Filename1"]["tmp_name"];
$tempFileName2 = $_FILES["Filename2"]["tmp_name"];
$tempFileName3 = $_FILES["Filename3"]["tmp_name"];
$tempFileName4 = $_FILES["Filename4"]["tmp_name"];
$result = move_uploaded_file($tempFileName,$fileTarget);
$result1 = move_uploaded_file($tempFileName1,$fileTarget1);
$result2 = move_uploaded_file($tempFileName2,$fileTarget2);
$result3 = move_uploaded_file($tempFileName3,$fileTarget3);
$result4 = move_uploaded_file($tempFileName4,$fileTarget4);
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="pdf_uploads/";
// new file size in KB
$new_size = $file_size/1024;
// new file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);//anthima
if(move_uploaded_file($file_loc,$folder.$final_file))
{
$query = "INSERT INTO company_details( company_name,service, email, password, details,image_path,file_name,image_path1,file_name1,image_path2,file_name2,image_path3,file_name3,file,type,size,image_path4,file_name4) VALUES ('$company_name','$service','$email','$password','$details','$fileTarget','$fileName','$fileTarget1','$fileName1','$fileTarget2','$fileName2','$fileTarget3','$fileName3','$final_file','$file_type','$new_size','$fileTarget4','$fileName4')";
$con->query($query) or die("Error : ".mysqli_error($con));
mysqli_close($con);
}
}
?>
<?php
Given below is the test data error
VALUES ('singer','Hardware','singer#gmail.com','singer','Singer has been in Sr' at line 1
Because you never sanitize anything and put the data straight into your query,
$company_name =$_POST['company_name'];
$service =$_POST['service'];
$email =$_POST['email'];
$password =$_POST['password'];
$details =$_POST['details'];
...
$query = "INSERT INTO
company_details( company_name,service, email, password, details,image_path,file_name,image_path1,file_name1,image_path2,file_name2,image_path3,file_name3,file,type,size,image_path4,file_name4)
VALUES (
'$company_name','$service','$email','$password','$details','$fileTarget','$fileName','$fileTarget1','$fileName1','$fileTarget2','$fileName2','$fileTarget3','$fileName3','$final_file','$file_type','$new_size','$fileTarget4','$fileName4'
)";
your problem is most likely in the data
's product portfolio has diversified to encompass a highly successful multi-brand
Maybe you have unscaped apostrophes in your data, so you're kinda SQL-injecting yourself. The query ends before the string shown in the error.
The solution is to escape special chars before inserting like in this question: How do I escape only single quotes?
In your case, start with the details
$details = addcslashes($_POST['details'], "'");
or
$details = addslashes($_POST['details']);
But keep adding test scenarios for your code. E.g. what happens if company name gets something like Mc'Donaldson? What is the set of chars you want to accept for each field? Then you will know how to validate those fields and create your functions (or reuse something)

echo a variable from a multidimentional array outside a function

The code below works for a string value but not when I try to access the variable directly.
The data being accessed is a table at http://webrates.truefx.com/rates/connect.html?f=html
My code strips it of tags and put it in an array $row0
And puts it in a function. But I can't get it out. The function is simplified for this question. I intend to concatenate some of the variables inside the function once I find out what I'm doing wrong.
$row0 = array();
include "scrape/simple_html_dom.php";
$url = "http://webrates.truefx.com/rates/connect.html?f=html";
$html = new simple_html_dom();
$html->load_file($url);
foreach ($html->find('tr') as $i => $row) {
foreach ($row->find('td') as $j => $col) {
$row0[$i][$j]= strip_tags($col);
}
}
myArray($row0); //table stripped of tags
function myArray($arr) {
$a = 'hello'; //$arr[0][0]; HELLO will come out but not the variable
$b = $arr[1][0];
$r[0] = $a;
$r[1] = $b;
//echo $r[1]; If the //'s are removed one can see the proper value here but not outside the function.
return $r;
}
$arrayToEcho = myArray($arr);
echo $arrayToEcho[0]; // will echo "first"
I have tried all the suggestions from here:
http://stackoverflow.com/questions/3451906/multiple-returns-from-function
http://stackoverflow.com/questions/5692568/php-function-return-array
Suggestion appreciated please and more info available if required. Thank you very much for viewing.
You need to get the innertext of $col in your loop. Like this:
$row0[$i][$j]= $col->innertext;
The next thing is:
myArray($row0);
This call will correctly return the parsed array; try echoing it and you'll see. But when you do this:
$arrayToEcho = myArray($arr);
...you're referencing to $arr which is a local variable (a parameter, actually) inside your function myArr. So what you probably meant was this:
$arrayToEcho = myArray($row0);
Hope this helps!
UPDATE
Look, I show you what happens when you call a function:

how use mysql_data_seek with PDO?

I want use mysql_data_seek with PDO from google search I found that it should looks like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
however it's not work, what I do wrong?
this is my code:
$query = "SELECT name,age FROM users";
$q = $db->prepare($query);
$q->execute();
$q->setFetchMode(PDO::FETCH_ASSOC);
$arrayData = $q->fetchAll();
foreach ($arrayData as $row){
echo $row['name'] ." ";
echo $row['age'] ."<br>";
}
$result = $q->fetch(PDO::FETCH_OBJ,PDO::FETCH_ORI_ABS,4);
var_dump($result);
I just want get the 5th row in object form from the last run query. I don't want run this query again (as some guys told me) I just want the results from sql buffer.
the var_dump result is: bool(false)
any ideas?
EDIT:
thanks for your answers and sorry but maybe I don't explain myself as well. I like the trick with JSON but the point is that the 5th row is example. I just want use the result of the query from the buffer with PDO exactly as I did it with mysql_data_seek in regular mysql (change the cursor). is it possible? I like all the tricks but that not what I look for.
the PDO 'cursor' default is PDO::CURSOR_FWDONLY that means that cursor can't back to zero like it happens with mysql_data_seek to allow cursor back to zero it necessary define use 'scrollable cursor'
example:
$db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
before use it like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
$result = $arrayData[4];
is all you need.
If you want the 5th row result you can do like this:
$result = json_decode(json_encode($arrayData[4]), FALSE);
var_dump($result);
or something like this:
$object = new stdClass();
foreach ($array as $key => $value)
{
$object->$key = $value;
}
Just curious! why do you need the object form?
EDIT (this will give the object form of the 5th row):
$index = 0;
$fifthRow = new stdClass();
while($row = $q->fetch())
{
if($index++==4)
$fifthRow = json_decode(json_encode($row), FALSE);
}
You could do it like this:
$c = 1;
$saved=null;
while($row = $q->fetch()){
if($c==4){
$saved = clone $row;
};
$c++;
somethingelse;
}
$saved will then contain the 4th element as an object with almost no extra overhead calculations.

Multidimensional Array insert into Mysql rows

I have an Array (twodimensional) and i insert it into my database.
My Code:
$yourArr = $_POST;
$action = $yourArr['action'];
$mysql = $yourArr['mysql'];
$total = $yourArr['total'];
unset( $yourArr['action'] , $yourArr['mysql'] , $yourArr['total'] );
foreach ($yourArr as $k => $v) {
list($type,$num) = explode('_item_',$k);
$items[$num][$type] = $v;
$pnr= $items[$num][pnr];
$pkt= $items[$num][pkt];
$desc= $items[$num][desc];
$qty= $items[$num][qty];
$price= $items[$num][price];
$eintragen = mysql_query("INSERT INTO rechnungspositionen (artikelnummer, menge, artikel, beschreibung,preis) VALUES ('$pnr', '$qty', '$pkt', '$desc', '$price')");
}
I get 5 inserts in the Database but only the 5th have the informations i want. The firsts are incomplete.
Can someone help me?
Sorry for my english.
check if You have sent vars from browser in array (like
input name="some_name[]" ...
also You can check, what You get at any time by putting var_dump($your_var) in any place in script.
good luck:)
You probably want to have your query and the 5 assignments above that outside of the foreach. Instead in a new loop which only executes once for every item instead of 5 times. Your indentation even suggests the same however your brackets do not.
Currently it is only assigning one value each time and executing a new query. After 5 times all the variables are assigned and the last inserted row finally has everything proper.
error_reporting(E_ALL);
$items = array();
foreach($yourArr as $k => $v) {
// check here if the variable is one you need
list($type, $num) = explode('_item_', $k);
$items[$num][$type] = $v;
}
foreach($items as $item) {
$pnr = mysql_real_escape_string($item['pnr']);
$pkt = mysql_real_escape_string($item['pkt']);
$desc = mysql_real_escape_string($item['desc']);
$qty = mysql_real_escape_string($item['qty']);
$price = mysql_real_escape_string($item['price']);
$eintragen = mysql_query("INSERT INTO rechnungspositionen (artikelnummer, menge, artikel, beschreibung,preis) VALUES ('$pnr', '$qty', '$pkt', '$desc', '$price')");
}
Switching on your error level to E_ALL would have hinted in such a direction, among else:
unquoted array-keys: if a constant of
the same name exists your script will
be unpredictable.
unescaped variables: malformed values
or even just containing a quote which
needs to be there will fail your
query or worse.
naïve exploding: not each $_POST-key
variable will contain the string
item and your list will fail, including subsequent use of $num

jQuery datepicker, disable dates from MYSQL

I have a list of dates stored in a MYSQL table, the idea is if the following field has valued 'completed' the row's date is unselectable in the jQueryUI datepicker. The dates are stored in the format YYYY-MM-DD.. how would I go about loading these 'completed' dates into a PHP array in a format for the datepicker to understand and disable them? JSON would be the obvious answer, I've spent the last couple of weeks getting to grips with it. Any example code of the jquery / php code would be greatly appreciated.
Many thanks in advance.
[ I have done research around the subject but it is not particularly well documented.. I've already got the datepicker showing valid days in a week. The jqueryUI datepicker seems to be able to do everything except make me a cup of tea. ]
EDIT: So I've managed to feed the array of dates with 'final' status through with JSON, I thought i'd provide the code if it helps anyone:
<?php
//connect to local db
include('functions.php');
connectLocal($localcon);
//locate rows with status set to final
$result = mysql_query("SELECT sendDate FROM my_table WHERE status='final'");
// return corresponding dates as json array
$i=0;
while($row = mysql_fetch_array($result))
{
$confirmedSends[$i] = array ( "sendDate" => $row['sendDate']);
$i++;
}
header('Content-type: application/json');
$jsonConfirmedSends = json_encode($confirmedSends);
echo $jsonConfirmedSends;
?>
This can retrieved with json in the form of a list of dates. The alert box pops up once for each date. About to get to work on presenting these to my datepicker array.
$.getJSON("get-disabled-dates.php",
function(data){
$.each(data, function(index, completed) {
alert(completed.sendDate);
});
});
Try following code to match your situation which disables set of dates. You can get dates by using json from your mysql table using $.getJSON of jquery
$(function() {
$( "#pickdate" ).datepicker({
dateFormat: 'dd MM yy',
beforeShowDay: checkAvailability
});
})
var $myBadDates = new Array("10 October 2010","21 October 2010","12 November 2010");
function checkAvailability(mydate){
var $return=true;
var $returnclass ="available";
$checkdate = $.datepicker.formatDate('dd MM yy', mydate);
for(var i = 0; i < $myBadDates.length; i++)
{
if($myBadDates[i] == $checkdate)
{
$return = false;
$returnclass= "unavailable";
}
}
return [$return,$returnclass];
}
source : http://codingforums.com/showthread.php?t=206879