save table records in associative array in php - php

I have an associative array. After I select my records from my table (with two columns: objName,objCost), I want to save them in my array like this:
array(
'objName'=>$row['objName'],
'objCost'=>$row['objCost']
)
How should I do this?
This is my code:
$output = '';
$arr = array();
$sql = "SELECT * FROM obj WHERE objName LIKE '%" . $_POST["search"] . "%'";
$result = $db->query($sql) or die(mysql_error());
if ($result->rowCount() != 0) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
//here i should insert my rows into my array
}
$json_arr = json_encode($arr,JSON_UNESCAPED_UNICODE);
echo $json_arr;
} else {
echo 'Data Not Found';
}

According to your code,
$arr[] = ['objName'=>$row['objName'],'objCost'=>$row['objCost']];
Then you can encode the array and pick up the object on the other side with javascript or php. Which ever suits you
json_encode($arr);
In you Ajax success, get the objects and use the values as you deem fit
success: function (data) {data = JSON.parse(data);
for(var i = 0; i < data.length; i++){
alert(data[i].objName);
}
}
see jQuery loop over JSON result from AJAX Success? on how to loop through your results in jquery

Related

Returning an array from a PHP query

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.

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>");
}
}

how to fetch all rows from mysql using mysqli_fetch_assoc and convert to JSON

I have tried to get all the rows from mysql table for that am using mysqli_fetch_assoc. While using this am getting only one row. I need to convert the resulting array into JSON.
$query = "SELECT * FROM db_category WHERE publish='1'";
$result = mysqli_query($c, $query) or die(mysqli_error($c));
$length = mysqli_num_rows($result);
if($length > 0)
{
$var['status'] = 'success';
while($obj = mysqli_fetch_assoc($result))
{
$var = array_merge($var, $obj);
$var1 = json_encode($var);
}
echo '{"slider":['.$var1.']}';
}
else
{
$arr = array('status'=>"notfound");
echo '{"slider":['.json_encode($arr).']}';
}
Now the output for above code is,
{"slider":[{"status":"success","category_id":"12","category_name":"Books","publish":"1"}]}
Required output is,
{"slider":[{"status":"success","category_id":"1","category_name":"Apparel","publish":"1"},{"status":"success","category_id":"2","category_name":"Footwear","publish":"1"},{"status":"success","category_id":"3","category_name":"Furniture","publish":"1"},{"status":"success","category_id":"4","category_name":"Jewellery","publish":"1"}]}
How to solve this issue.
You can do it simply by json_encode() function. And you can also get all data into array, with mysqli_fetch_all() function :
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
$jsonData = json_encode(array('slider'=>$data, 'status' => 'success'));
If you want to put 'status'=>'success' for each row, do it like this (before json_encode)
foreach($data as $key => $dataRow) {
$data[$key]['status'] = 'success';
}

json_encode returning the next rows values - PHP PDO SQL HighCharts

When trying to use json_encode from arrays in foreach() the data moves in to the next values, for example:
I have this table which is coming from the same query + php:
when using json_encode to try and fit this tables data in to highcharts, my outcome is like this:
[{"name":"User1","data":[0,2,0,0]},{"name":"User2","data":[0,2,0,0,2,0,2,4]}]
So it's moving User1's data in to User2's
My desired outcome would be:
[{"name":"User1","data":[0,2,0,0]},{"name":"User2","data":[2,0,2,4]}]
This is my code:
$uniqueHours = array();
$series = array();
$data = array();
foreach ($pdo->query("SELECT DATEPART(HOUR, AL.EndDateTime) AS 'EndHour'
FROM ActivityLog AL
WHERE
".$where."
ORDER BY AL.EndDateTime, 'EndHour' DESC") as $row)
{
if ( in_array($row['EndHour'], $uniqueHours) ) {
continue;
}
$uniqueHours[] = $row['EndHour'];
}
$ODsql = "SELECT * FROM Users";
foreach ($pdo->query($ODsql) as $row)
{
echo '<tr>';
$SCardNumber = $row['CardNumber'];
$SEmployeeName = $row['Username'];
echo '<td>'.$SEmployeeName.'</td>';
$chartValues = "";
foreach($uniqueHours as $hour)
{
$countSQL= $pdo->prepare("SELECT DISTINCT(COUNT(AL.TerminalNumber)) AS TOTALS
FROM ActivityLog AL, WavePick WP
WHERE AL.TransactionType = 'SPK' AND WP.PickedQty > 0
AND DATEPART(HOUR, AL.EndDateTime) = ".$hour."
AND AL.StartDateTime >= '".$StartDate." 00:00:00.000' AND AL.EndDateTime <= '".$StartDate." 23:59:59.000'
AND AL.OrderNumber = WP.OrderNumber
AND AL.CardNumber = '".$SCardNumber."'
");
$countSQL->execute();
$result = $countSQL->fetch(PDO::FETCH_OBJ);
$row_count = $result->TOTALS;
$totals[] = $result->TOTALS;
echo '<td>'.$row_count.'</td>';
}
echo '</tr>';
$series['name'] = $SEmployeeName;
$series['data'] = $totals;
array_push($data,$series);
}
I haven't actually put this in to the chart yet because the data is invalid.
I am using this to return the outcome:
echo "<div class='well'>";
print json_encode($results, JSON_NUMERIC_CHECK);
echo "</div>";
How can I make this data show only for each user it is linked to?
Before this loop:
foreach($uniqueHours as $hour)
empty $total array with
$total=array();
foreach($uniqueHours as $hour)

how merge arrays receiving from mysql by json_encode function

I'm sitting on this for a long time and can't find a solution:
By using the function json_ encode in php file (script below) i receives data from mysql as group of arrays e.g. ["9,8","15,14","18,17","29,40,10,9"],in the main file by use $.parseJSON function(script below),
receives a array with indexed object as ["9,8","15,14","18,17","29,40,10,9"....]
instead [9,8,15,14,18,17,29,40,10,9],
How merge all this object together??
I tried to use $.merge function, but doesn't work.Help??;-)
/////receive.php file//////
$ask = mysql_query("SELECT numbers FROM bying");
if(!ask)
{
die('incorrect ask'.mysql_error());
}
else{
$tab = array();
while ($row = mysql_fetch_assoc($ask))
{
$data=$row['numbers'];
array_push($tab,$data);
}
echo json_encode($tab);
mysql_free_result($ask);
}
html file with $.parseJSON function
$.post('receive.php', function(data)
{
var table1=[];
table1 = $.parseJSON(data);
var numbers=$.merge([],table1);)
for(var i=0;i<numbers.length;i++)
{
alert(numbers[i]);
}
}
It looks as $data is a comma separated string of numbers, if so, you can slit it on commas and then merge the two arrays:
$ask = mysql_query("SELECT numbers FROM bying");
if(!ask)
{
die('incorrect ask'.mysql_error());
}
else {
$tab = array();
while ($row = mysql_fetch_assoc($ask)) {
$data = explode( ',', $row['numbers'] );
$tab = array_merge( $tab, $data );
}
echo json_encode($tab);
mysql_free_result($ask);
}
Why not do it the 'obvious' way and iterate through the array yourself splitting each string on ',' and appending each parsed number to an array you construct as you go?
e.g.
var newNums = [];
for (var i=0; i<table1.length; i++) {
newNums = newNums.concat(table1[i].split(','));
}

Categories