Returning an array from a PHP query - php

I query my database with a PHP script that looks like this:
$query = "SELECT * FROM JKFactory WHERE ronde = '$ronde' AND moment = '$moment' AND klas = '$klas'";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['afzetAG'];
echo ",";
}
This gives a result something like this:
10000,20000,30000,
I need this data to build a piegraph with chart.js.
chart.js works with arrays for the data. So the numbers should be returned as an array which I can put into an JavaScript variable which I can use with chart.js.
Another problem is the last comma. I have no idea how I can get rid of this comma.
Maybe these question are straightforward but I am relatively new in this field I really get stuck on this part.

You have the array and you'd put the comma after the results yourself. so try to declare an array like $arr before while and use array_push($arr,$row['afzetAG']) inside the while

To print your result like 1000,2000,3000... You can save the content into an Array and print it using implode:
$data = array();
while($row = mysql_fetch_array($result))
{
array_push($data, $row['afzetAG']);
}
echo implode(",",$data);
But if you want to use an Array from PHP to JavaScript you can do this:
<script type="text/javascript">
<?php
$data = array();
while($row = mysql_fetch_array($result))
{
array_push($data, $row['afzetAG']);
}
?>
var obj = <?php echo json_encode($data); ?>;
</script>
So now obj contains the Array ready to use in your JavaScript code.

$types = array();
while(($row = mysql_fetch_assoc($result))) { $types[] = $row['type']; }

ok i made it. To echo the result i used this:
$a = array();
while($row = mysql_fetch_array($result))
{
$b = $row['afzetAG'];
array_push($a,$b);
}
echo implode(",",$a);
This gives not an array i can use in javascript. In javascript i put the result in a variable myResult and than i used:
myResult = myResult.split(',');
this i could use in chart.js to build a pie chart.
Thanks guys. Now i can sleep.

Related

Encoding MySQL array result in JSON array notation

$markers =array();
$getmap = $mysqli->query("SELECT `desc`,`lat`,`long` FROM map");
$i=0;
$markers = $getmap->fetch_all(MYSQLI_ASSOC);
echo $markers[1]["desc"];
echo $markers;
$markers = json_encode($markers);
How is it possible such that these will flow properly and it will be read by the JS?
var position = (markers[i][lat], markers[i][long]);
Please try this way:
Hopefully it will help:
foreach($markers as $i=>$arrMarkes)
{
$finalArray[$i] = $arrMarkes;
}
echo json_encode($finalArray);

How to add rows to jquery table from mysql query with ajax?

I need insert rows into a jQuery DataTable from AJAX. In AJAX I call a PHP file when I make a query to my mySql database, but I get show only a character in rows. It is because the format returned is incorrect, but I can't to parse the correct format.
$query = "..myquery..";
if ($row = mysql_fetch_array($sql)) {
do {
$arr []= $row['name'];
} while ($row = mysql_fetch_array($sql));
echo json_encode($arr); // Here I tried return array without json_encode and a lot of things...
}
I know that the format to add the rows with .DataTable().row.add() is the below, but I do not get the desired format.
[["Element software"], ["Software dist"],["Global envir"], ["Software"], ["Software list"]]
How can I get this format in the echo to returned this??
Thanks!
It is array of arrays, so you need to push an array to $arr, not a string:
$query = "..myquery..";
$arr = []; // init an empty array
// no need to do if() and do{}while() inside. You can just while(){} it
while($row = mysql_fetch_array($sql)){
$arr[]= [$row['name']]; // <== these square brackets do the trick
}
echo json_encode($arr); // still need to json_encode
do{
$arr[]= array($row['name']);
} while ($row = mysql_fetch_array($sql));
echo json_encode($arr);
Note the
$arr[]= array($row['name']);
instead of
$arr []= $row['name'];
One:two run mysql_fetch_array($sql) because php return null;
Two:code ajax for insert table .
$.ajax({
dataType:"json",
url:"recive.php",
type:"POST",
data:{id:id},
success: function(res){
for(var j=0;j<res.length;j++)
{
$("#tabel").append("<table ><tr><td style='width:100%;' > "+res[j].id+"</td></tr></table>");
}
}

PHP array into Javascript Array

Afternoon all. The code below works perfectly, however, I need to pull each row of the php sql array out and into the script var. Any ideas on how to write a while loop that could do this? Thanks for any help
var enableDays = ["<?php echo mysql_result($result, 0, 'date'); ?>"];
enableDays.push("<?php echo mysql_result($result, 1, 'date'); ?>");
Additional Code::
$rows = array();
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
var enableDays = [<?php echo json_encode($rows); ?>];
console.log(enableDays[1]);
You can get the rows using mysqli_fetch_assoc and then encode it to JSON:
<?php
$rows = array();
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
?>
var enableDays = <?php echo json_encode($rows); ?>;
Pull your data out into a PHP array, then transfer that to JavaScript with
var enableDays = <?php echo json_encode($enableDays); ?>;
As an aside, the obligatory recommendation that you should stop using the PHP mysql extension immediately because it is not very safe and has been deprecated; switch to something better (mysqli and PDO are both good choices).
This can't work. Once the page is loaded, all the PHP has run already. But if you're really just adding the next mysql_result for each push, you could have PHP create the entire enableDays array for you:
<?php
echo 'var enableDays = ["' . mysql_result(...) . '", "' . mysql_result(...) . '"];'
?>
Hope this would help
<?php
$res = mysql_fetch_assoc($result)
foreach($res as $key => $val){ ?>
enableDays.push('<?php echo $val; ?>');
<?php }
?>

How to index the result of a mySql query as an array of array?

If I need to select and use information of every element of a table in a database the procedure would be this:
$query = "...mySql query...";
$query_result = mysql_query($query) or die (mysql_error());
Then if I wished to access the fields of the result I would use the function mysql_fetch_array() and access them like this:
$query_result_array = mysql_fetch_array($query_result);
echo $query_result_array['field_1'];
....
echo $query_result_array['field_i'];
....
But since more elements could be returned by the query I would like to access every single of them with an array indexed from 0 to mysql_num_rows($query_result).
As an example:
echo $query_result_array['field_i'][0];
....
echo $query_result_array['field_i'][mysql_num_rows($query_result)];
should print for every selected element of the table the value of field i.
Is there a function that will do the job for me?
If not, any suggestions on how to do it?
Thanks in advance for help.
This may be an alternative
$res = mysql_query("..SQL...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$arr[] = $row;
}
var_dump($arr);
Or
$res = mysql_query("..SQL...");
for
(
$arr = array();
$row = mysql_fetch_assoc($res);
$arr[] = $row
);
var_dump($arr);
I don't think there is such a method; you have to do it yourself.
try with something like:
$res = mysql_query("..mySql query...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$query_result_array[] = $row;
}
then you access your data like:
echo $query_result_array[0]['field_i'];
based on 2 previous answers, those authors assuming that usual SO author is familiar with such a thing as creating a function
function sqlArr($sql) { return an array consists of
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
if ($res) {
while ($row = mysql_fetch_assoc($res)) {
$ret[] = $row;
}
}
return $ret;
}
$array = sqlArr("SELECT * FROM table");
foreach ($array as $row) {
echo $row['name'],$row['sex'];
}
this resulting array have different structure from what you asked, but it is way more convenient too.
if you still need yours unusual one, you have to tell how you gonna use it

format mysql data in array

I am pulling data from my database and trying to encode into JSON data using json_encode. But to make it easier to read in my android app. I was hopping to format it differently then I am currently doing. Please see bottom encode string example. Any help would be great. Thanks in Advance.
$result = $db->query($query);
while($info = mysql_fetch_array($result))
{
$content[] = $info;
}
$count = count($content);
$result=array();
for($i=0;$i<$count;$i++)
{
$result[id][] = $content[$i]['imageID'];
$result[name][] = $content[$i]['Name'];
$result[thumb][] = $content[$i]['Thumb'];
$result[path][] = $content[$i]['Path'];
}
echo json_encode($result);
{"id":["1","2","3"],"name":["Dragon","fly","bug"],"thumb":["thm_polaroid.jpg","thm_default.jpg","thm_enhanced-buzz-9667-1270841394-4.jpg"],"path":["polaroid.jpg","default.jpg","enhanced-buzz-9667-1270841394-4.jpg"]}
But I am trying to format my array like so when it is encoded by json_encode.
[{"id":"1","name":"Dragon","thumb":"thm_polaroid.jpg","path":"polaroid.jpg"},{"id":"2","name":"Fly","thumb":"thm_default.jpg","path":"default.jpg"},{"id":"3","name":"Bug","thumb":"thm_enhanced-buzz-9667-1270841394-4.jpg","path":"enhanced-buzz-9667-1270841394-4.jpg"}]
Well, there is a problem. This is not valid JSON:
{"image":["1","Dragon","thm_polaroid.jpg","polaroid.jpg"],
"image":["2","fly","thm_default.jpg","default.jpg"]}
A JSON object can only have one value per unique key. This means that your latter image key would clobber the value of the former.
If you are content with this, however:
[["1","Dragon","thm_polaroid.jpg","polaroid.jpg"],
["2","fly","thm_default.jpg","default.jpg"]]
Then you can simply use mysql_fetch_row:
$result = $db->query($query);
while($info = mysql_fetch_row($result))
{
$content[] = $info;
}
echo json_encode($content);
Side Note:
Generally, in PHP, it is best to use foreach( $arr as $val ) (or $arr as $key => $val). for loops should be limited to when they are strictly necessary.
You need to add the iterator $i to the setting array
for($i=0;$i<$count;$i++)
{
$result[$i][id] = $content[$i]['imageID'];
$result[$i][name] = $content[$i]['Name'];
$result[$i][thumb] = $content[$i]['Thumb'];
$result[$i][path] = $content[$i]['Path'];
}
<?
$result = $db->query($query);
while($info = mysql_fetch_array($result))
$content[] = $info;
$result=array();
$count = count($content);
for ($x=0;$x<$count;++$x)
{
$result[$x][] = $content[$x]['imageID'];
$result[$x][] = $content[$x]['Name'];
$result[$x][] = $content[$x]['Thumb'];
$result[$x][] = $content[$x]['Path'];
}
echo json_encode($result);
?>

Categories