I'm asking this question because all the answers I could find for similar problems were using MySQL whereas I'm not, just a JSON API to get the data, which I then put into arrays that I want to display as a Google graph. All I know is that I have to somehow format the arrays properly in order to get them to display but I have no idea how to do it in my case. I would just like to have a simple pie chart, based on the arrays below. So far I'm getting a blank space on the site. I tried something with Json_encode before but it didn't work so I decided to leave it as it is and come here instead. Here are the arrays after I do print_r:
Array 'name'-
Array ( [0] => Facebook Inc [1] => Alphabet Class A [2] => Apple Inc [3] => Ford Motor Company [4] => Adv Micro Devices [5] => Morgan Stanley [6] => Berkshire Hath Hld B [7] => JP Morgan Chase & Co )
Array 'sumOf'-
Array ( [0] => 5811.63 [1] => 116135.97 [2] => 1564.1 [3] => 1053 [4] => 113.1 [5] => 521.4 [6] => 1960.2 [7] => 1100.4 )
Code:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable($name, $sumOf);
var options = {
title: 'Portfolio Allocation'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
How arrays are made:
$name = [];
$lastprice = [];
$y = 0;
$z = '';
$key = "";
// Retreiving information from database
$memberid = $_SESSION['memberID'];
$sql = "SELECT * FROM portfolio WHERE memberID = $memberid";
$result = mysqli_query($conn, $sql);
// Check if databse is empty
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$sym[$y] = $row["stocks_symbol"];
$pri[$y] = $row["price"];
$vol[$y] = $row["quantity"];
$id[$y] = $row["memberid"];
$y += 1;
}
}
// If database empty
else
{
echo "Portfolio Empty";
die();
}
mysqli_close($conn);
// Adding all stock names in one variable to enable API call
for($a=0;$a<$y;$a++)
{
$z = $z.$sym[$a].',';
}
$z = rtrim($z,",");
// API call
$contents = file_get_contents("http://marketdata.websol.barchart.com/getQuote.json?key=$key&symbols=$z&mode=R");
$contents = json_decode($contents, true);
// Check successfull API call
if($contents["status"]["code"] == 200)
{
foreach($contents['results'] as $result)
{
array_push($name,$result['name']);
array_push($lastprice,$result['lastPrice']);
}
}
// If API call unsuccessful
else
{
echo "Error retreiving data. Please try again later.";
die();
}
?>
<!-- Generating Output in tabular format -->
<table id= test class='table table-responsive'>
<tr class='head warning'>
<th>Name</th>
<th>Last Price</th>
<th>Price Bought</th>
<th>Quantity</th>
<th>Change Per Stock</th>
<th>Profit/Loss</th>
<th>Market Value</th>
<th>Amount Invested</th>
</tr>
<?php
$profitOrLossSum = 0;
$dividendRateSum = 0;
$startEqSum = 0;
$sumOf = array();
for($x=0;$x<$y;$x++)
{?>
<tr>
<td class="input"><?php echo $name[$x]; ?></td>
<td class="input"><?php echo $lastprice[$x]; ?></td>
<td class="input"><?php echo $pri[$x]; ?></td>
<td class="input"><?php echo $vol[$x]; ?></td>
<td class="input"><?php
if($pri[$x] > $lastprice[$x])
{
echo $lastprice[$x]-$pri[$x];
}
else if($pri[$x] < $lastprice[$x])
{
echo $lastprice[$x]-$pri[$x];
}
else
echo '0';
?></td>
<td class="input"><?php
$profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
$profitOrLossSum += $profitOrLoss;
echo $profitOrLoss;
?></td>
<td><?php
$firstno1 = floatval($vol[$x]);
$secondno1 = floatval($lastprice[$x]);
$sumOf[] = $firstno1 * $secondno1;
$sum1 = $firstno1 * $secondno1;
print ($sum1);
?></td>
<td class="input">
<?php
$starteq = $pri[$x] * $vol[$x];
$startEqSum += $starteq;
echo $starteq;
?>
</td>
</tr>
<?php
}
$arr = array('profitOrLossSum' => $profitOrLossSum, 'dividendRateSum' => $dividendRateSum);
$arr1 = array('startEqSum' => $startEqSum);
print_r ($name);
print_r ($sumOf);
echo json_encode($name);
echo json_encode($sumOf);
?>
Here is the working Example of your code you were very close though. Actually, you have to pass only one single parameter as a multidimensional array to arrayToDataTable(); you have to json_encode and JSON_parse your array as well
check https://developers.google.com/chart/interactive/docs/gallery/piechart
No worries its working copy and paste it and you are good to go.
<?php
$name = ['Facebook Inc', 'Alphabet Class A', 'Apple Inc', 'Ford Motor Company', 'Adv Micro Devices', 'Morgan Stanley', 'Berkshire Hath Hld B', 'P Morgan Chase & Co'];
$sumOf = [5811.63, 116135.97, 1564.1, 1053, 113.1, 521.4, 1960.2, 1100.4];
?>
<html>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
var name = <?= json_encode($name) ?>;
var sumOf = <?= json_encode($sumOf) ?>;
var array = name.split(",");
newArr = [['Name', 'Amount']];
array.forEach(function (v, i) {
newArr.push([v, sumOf[i]]);
});
function drawChart() {
var data = google.visualization.arrayToDataTable(newArr);
var options = {
title: 'Portfolio Allocation'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
array_combine was needed to join the two arrays together and then inside of
'function drawChart' a simple foreach loop was required, like this:
<?php
foreach ($array as $name => $allocation):
echo "['$name', $allocation]";
echo ($allocation != end($array)) ? ',' : '';
endforeach;
?>
Related
I'm a JavaScript Programmer and has a project with PHP.
I'm having trouble with working JSON with PHP.
This is my JSON
{
"orders":[
{
"name":"#1002"
},
{
"name":"#1001"
}
]
}
I need to get each name and echo them, I tried the following code $myarray = json_decode($order, true) but it returns me this error.
Warning: json_decode() expects parameter 1 to be string, array given in
How can i convert the json from array to string? or am i doing it wrong.
config.php
<?php
$con = mysql_connect('localhost','root','');
mysql_select_db('db_school',$con);
$sql = "SELECT * FROM userlogin";
$result = mysql_query($sql,$con);
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] =array(
'id'=>$row['id'],
'username'=>$row['username'],
'userpass'=>$row['userpass'],
);
}
echo json_encode(array('data'=>$data));
?>
view.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table id="tbl" border="1">
<thead><tr>
<th>Id</th>
<th>Username</th>
<th>Password</th>
</tr></thead>
<tbody></tbody>
</table>
<script type="text/javascript">
$.ajax({
url: 'config.php',
}).done(function(res) {
var res_data = JSON.parse(res),table='';
$.each(res_data.data,function(index, el) {
console.log(el.id,' ', el.username,' ',el.userpass);
table+='<tr>';
table+='<td>'+el.id+'</td>';
table+='<td>'+el.username+'</td>';
table+='<td>'+el.userpass+'</td>';
table+='</tr>';
});
$('#tbl').html(table);
});
</script>
Demo:
Simply save the json response on a variable. And then do json_decode
$orders = '{
"orders":[
{
"name":"#1002"
},
{
"name":"#1001"
}
]
}';
$myarray = json_decode($orders, true);
Now performing print_r will yield result like
echo '<pre>';
print_r($myarray);
Result
Array
(
[orders] => Array
(
[0] => Array
(
[name] => #1002
)
[1] => Array
(
[name] => #1001
)
)
)
EDIT :
In order to get only name values simply run a foreach
$result = [];
foreach($myarray['orders'] as $value) {
$result[] = $value['name'];
}
Now printing $result you will get
Array
(
[0] => #1002
[1] => #1001
)
First of all I have the following MySQL table name as store_items :
id ref store item qty sell
1 2 m1 001 1 12.00
2 2 m1 002 3 12.00
3 3 m3 004 4 5.00
4 3 m3 003 8 10.00
And starting with a simple PHP code to convert the above rows to an array
<?php
$query = "SELECT * FROM store_items ORDER by store Asc";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
//This is for moving PHP array to JS array ? Not sure if it is correct
$js_arr = json_encode($data);
?>
Now I have been looking for a way rather than displaying it as a table , so I want to place those results inside an Excel look alike, so I found this plugin called : Javascript Handsontable
Moving on , after placing the style sheets and the scripts :
<script src="http://localhost/handsontable-master/dist/handsontable.full.js"></script>
<link rel="stylesheet" media="screen" href="http://localhost/handsontable-master/dist/handsontable.full.css">
<link rel="stylesheet" media="screen" href="http://localhost/handsontable-master/demo/css/samples.css">
<link rel="stylesheet" media="screen" href="http://localhost/handsontable-master/demo/css/samples.css">
<link rel="stylesheet" media="screen" href="http://localhost/handsontable-master/demo/css/samples.css">
<style type="text/css">
body {background: white; margin: auto;}
h2 {margin: 20px 0;}
</style>
<div id="example" class="handsontable htColumnHeaders"></div>
So the Problem arises over here :
<script>
var array_code = '<?php echo $js_arr; ?>';
//Alerting result to make sure its correct
alert(array_code);
$(document).ready(function () {
//Not sure how to display the results here ???
var
data =
[
array_code
],
container = document.getElementById('example'),
hot;
hot = new Handsontable(container, {
data: data,
minSpareRows: 1,
colHeaders: true,
contextMenu: true
});
function bindDumpButton() {
Handsontable.Dom.addEvent(document.body, 'click', function (e) {
var element = e.target || e.srcElement;
if (element.nodeName == "BUTTON" && element.name == 'dump') {
var name = element.getAttribute('data-dump');
var instance = element.getAttribute('data-instance');
var hot = window[instance];
console.log('data of ' + name, hot.getData());
}
});
}
bindDumpButton();
});
But I can't achieve the correct display; what I'm aiming for is something like this:
But the above picture is shown correct when var data array values are like this
var
data = [
['1', '2', 'm1', '001', '1', '12.00'],
['2', '2', 'm1', '002', '3', '12.00'],
['3', '3', 'm3', '004', '4', '5.00'],
],
How can I place the PHP array values inside JS array correctly?
Any suggestions will be appreciated.
Maybe I'm missing something (in which case comment and i'll edit my answer), but I think you just need to replace:
while ($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
with:
while ($row = mysql_fetch_row($result)){
$data[] = $row;
}
and your "data" should be exactly array_code
You don't need to use $js_arr = json_encode($data); for displaying the data in the HTML table since it would produce JSON formatted data and if you're not going to manipulate the table using JavaScript, you can avoid doing this way. Just add the following HTML code and style it however you want:
<table>
<thead>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
<th>F</th>
</thead>
<tbody>
<?php if(!empty($data)): ?>
<?php foreach($data as $row): ?>
<tr>
<td><?= $row['id'] ?></td>
<td><?= $row['ref'] ?></td>
<td><?= $row['store'] ?></td>
<td><?= $row['item'] ?></td>
<td><?= $row['qty'] ?></td>
<td><?= $row['sell'] ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
i did some coding to group the product attributes on frontend and show their groups names above theme like this:
attgroup 1
attribute 1
attribute 2
...
attgroup 2
attribute 3
attribute 4
...
I added /app/code/local/Mage/Catalog/Block/Product/View/Attributesgroups.php with the following code:
<?php
class Mage_Catalog_Block_Product_View_Attributesgroups extends Mage_Core_Block_Template
{
protected $_product = null;
function getProduct()
{
if (!$this->_product) {
$this->_product = Mage::registry('product');
}
return $this->_product;
}
public function getAdditionalData(array $excludeAttr = array())
{
$data = array();
$product = $this->getProduct();
$attributes = $product->getAttributes();
foreach ($attributes as $attribute) {
if ($attribute->getIsVisibleOnFront() && !in_array($attribute->getAttributeCode(), $excludeAttr)) {
$value = $attribute->getFrontend()->getValue($product);
// TODO this is temporary skipping eco taxes
if (is_string($value)) {
if (strlen($value) && $product->hasData($attribute->getAttributeCode())) {
if ($attribute->getFrontendInput() == 'price') {
$value = Mage::app()->getStore()->convertPrice($value,true);
} elseif (!$attribute->getIsHtmlAllowedOnFront()) {
$value = $this->htmlEscape($value);
}
$group = 0;
if( $tmp = $attribute->getData('attribute_group_id') ) {
$group = $tmp;
}
$data[$group]['items'][ $attribute->getAttributeCode()] = array(
'label' => $attribute->getFrontend()->getLabel(),
'value' => $value,
'code' => $attribute->getAttributeCode()
);
$data[$group]['attrid'] = $attribute->getId();
}
}
}
}
// Noch Titel lesen
foreach( $data AS $groupId => &$group ) {
$groupModel = Mage::getModel('eav/entity_attribute_group')->load( $groupId );
$group['title'] = $groupModel->getAttributeGroupName();
}
return $data;
}
}
Then, I created the /app/design/frontend/MY_TEMPLATE/default/template/catalog/product/view/attributesgroups.phtml file with the following content:
<?php
$_helper = $this->helper('catalog/output');
$_product = $this->getProduct()
?>
<?php if($_additionalgroup = $this->getAdditionalData()): ?>
<div class="box-collateral box-additional">
<h2><?php echo $this->__('Additional Information') ?></h2>
<?php $i=0; foreach ($_additionalgroup as $_additional): $i++; ?>
<h3><?php echo $this->__( $_additional['title'] )?></h3>
<table class="data-table" id="product-attribute-specs-table-<?php echo $i?>">
<col width="25%" />
<col />
<tbody>
<?php foreach ($_additional['items'] as $_data): ?>
<tr>
<th class="label"><?php echo $this->htmlEscape($this->__($_data['label'])) ?></th>
<td class="data"><?php echo $_helper->productAttribute($_product, $_data['value'], $_data['code']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<script type="text/javascript">decorateTable('product-attribute-specs-table-<?php echo $i?>')</script>
<?php endforeach; ?>
</div>
<?php endif;?>
Last step was to modify /app/design/frontend/default/YOUR_TEMPLATE/layout/catalog.xml in line 223, and replaced
<block type="catalog/product_view_attributes" name="product.attributes" as="additional" template="catalog/product/view/attributes.phtml">
with
<block type="catalog/product_view_attributesgroups" name="product.attributes" as="additional" template="catalog/product/view/attributesgroups.phtml">
i did this but nothing is changed on product attribute tap on frontend product page.
im using magento 1.9.1 ce and custom template
First try to simple way
foreach($product->getAttributes() as $att){
$group_id = $att->getData('attribute_group_id');
$group = Mage::getModel('eav/entity_attribute_group')->load($group_id); var_dump($group);
}
or please try to below code....
Get attribute set ID programmatically..
$sDefaultAttributeSetId = Mage::getSingleton('eav/config')
->getEntityType(Mage_Catalog_Model_Product::ENTITY)
->getDefaultAttributeSetId();
Get group name programmatically..
$attributeSetId = 10;
$groups = Mage::getModel('eav/entity_attribute_group')
->getResourceCollection()
->setAttributeSetFilter($attributeSetId)
->setSortOrder()
->load();
$attributeCodes = array();
foreach ($groups as $group) {
echo $groupName = $group->getAttributeGroupName();
$groupId = $group->getAttributeGroupId();
}
I am trying to get member photos from my sql and show as a slide. i am trying this with DHTML slideshow script- © Dynamic Drive DHTML code library (www.dynamicdrive.com) check the basic code here basic code
now i change the code to get the image url from mysql using php
my code :
Here is the html and script code.
<html>
<head>
<script type="text/javascript">
/***********************************************
* DHTML slideshow script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice must stay intact for legal use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
var photos = new Array()
<?php
$mid=$_POST['mid'];
//echo $mid;
$mid=$_POST['mid'];
require_once("datacon.php");
$result = $data->query("SELECT * FROM tempregist where id= $mid ");
$row = mysqli_fetch_array($result) or die(mysqli_error());
$folde= "uploads/thumb/";
$folder=utf8_encode($folde);
//echo $folder;
$mid1 =$row['mid'];
require_once("datacon.php");
$result = $data->query("SELECT image_name FROM tbl_images where mid= '$mid1' ");
$phparray = array();
$count = mysqli_num_rows($result);
if($count>=1)
{
while($crow = mysqli_fetch_array($result))
{
$i=0;
$phparray[$i] = $folder. $crow['image_name'];
$i++;
?>
photos<?php echo"[".$i."]" ;?> = <?php echo '"'. implode( $phparray) . '"'."\n" ;
} }
?>
var photoslink = new array
var x
x =<?php echo json_encode($count) ?>;
var which=0
/
//Specify whether images should be linked or not (1=linked)
var linkornot=0
Set corresponding URLs for above images. Define ONLY if variable linkornot equals "1"
photoslink[0]=""
photoslink[1]=""
photoslink[2]=""
//do NOT edit pass this line
var preloadedimages=new Array()
for (i=0;i<photos.length;i++){
preloadedimages[i]=new Image()
preloadedimages[i].src=photos[i]
}
function applyeffect(){
if (document.all && photoslider.filters){
photoslider.filters.revealTrans.Transition=Math.floor(Math.random()*23)
photoslider.filters.revealTrans.stop()
photoslider.filters.revealTrans.apply()
}
}
function playeffect(){
if (document.all && photoslider.filters)
photoslider.filters.revealTrans.play()
}
function keeptrack(){
window.status="Image "+(which+1)+" of "+photos.length
}
function backward(){
if (which>0){
which--
applyeffect()
document.images.photoslider.src=photos[which]
playeffect()
keeptrack()
}
}
function forward(){
if (which<photos.length-1){
which++
applyeffect()
document.images.photoslider.src=photos[which]
playeffect()
keeptrack()
}
}
function transport(){
window.location=photoslink[which]
}
</script>
</head>
<body>
<div align="center">
<img src="images/logo.jpg" border = "2" align="center" alt="no logo">
</div>
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="100%" colspan="2" height="22"><center>
<script>
if (linkornot==1)
document.write('<a href="javascript:transport()">')
document.write('<img src="'+photos[0]+'" name="photoslider" style="filter:revealTrans(duration=2,transition=23)" border=0>')
if (linkornot==1)
document.write('</a>')
</script>
</center></td>
</tr>
<tr>
<td width="50%" height="21"><p align="left">Previous Slide</td>
<td width="50%" height="21"><p align="right">Next Slide</td>
</tr>
</table>
<p align="center"><font face="Arial" size="-2">Free DHTML scripts provided by<br>
Dynamic Drive</font></p>
</body>
</html>
Now i am getting out put as follows
var photos = new Array()
photos[0] = "uploads/thumb/220816_1412135472.jpeg"
photos[0] = "uploads/thumb/312840_1412135511.jpeg"
photos[0] = "uploads/thumb/589453_1412135511.jpeg"
photos[0] = "uploads/thumb/467341_1412135630.jpeg"
photos[0] = "uploads/thumb/800658_1412135790.jpeg"
photos[0] = "uploads/thumb/366793_1412135826.jpeg"
But i need the out put like this
photos[0] = "uploads/thumb/220816_1412135472.jpeg"
photos[1] = "uploads/thumb/312840_1412135511.jpeg"
photos[2] = "uploads/thumb/589453_1412135511.jpeg"
photos[3] = "uploads/thumb/467341_1412135630.jpeg"
photos[4] = "uploads/thumb/800658_1412135790.jpeg"
photos[5] = "uploads/thumb/366793_1412135826.jpeg"
i tried so much. please any one help.
while($crow = mysqli_fetch_array($result))
{
$i=0;
You're resetting $i in your loop
$result = $data->query("SELECT image_name FROM tbl_images where mid= '$mid1' ");
{
$count = mysqli_num_rows($result);
if($count>=1)
{
$i=0;
while($crow = mysqli_fetch_array($result))
{
$phparray[$i] = $folder. $crow['image_name'];
echo $i. "\n";
$i++;
}
}
use $i=0 initialization outside while
finally i found it with help of Hammerstein and Dhanush Bala. i mingled two persons suggestion i got it here is the answer
$phparray = array();
$count = mysqli_num_rows($result);
if($count>=1)
{
$b=0;
while($crow = mysqli_fetch_array($result))
{
$i=0;
$phparray[$i] = $folder. $crow['image_name'];
$i++;
$b++;
?>
photos<?php echo"[".$b."]" ;?> = <?php echo '"'. implode( $phparray) . '"'."\n" ;
} }
now the out put is:
photos[1] = "uploads/thumb/220816_1412135472.jpeg"
photos[2] = "uploads/thumb/312840_1412135511.jpeg"
photos[3] = "uploads/thumb/589453_1412135511.jpeg"
photos[4] = "uploads/thumb/467341_1412135630.jpeg"
photos[5] = "uploads/thumb/800658_1412135790.jpeg"
photos[6] = "uploads/thumb/366793_1412135826.jpeg"
thanks Hammerstein and Dhanush Bala
Here is the situation... Two results are created in the php page.. The results are echoed as json_encode . The results are showing perfectly. But when i insert a javascript code within two php code blocks, then one result is shown while the other is not.. I really have no idea why this is happening.. My code
$action = isset($_GET['action']);
if($action == "get_requests"){
include("../connect.php");
$sql_song_req = "SELECT COUNT(*) FROM `song_requests`";
$sql_select_song = "SELECT * FROM `song_requests` ORDER BY id ASC";
$sql_count = $rad->prepare($sql_song_req);
$sql_count->execute();
$count = $sql_count->fetchColumn();
$select_song_prep = $rad->prepare($sql_select_song);
$select_song_prep->execute();
while($row = $select_song_prep->fetch(PDO::FETCH_ASSOC)){
$id = $row['id'];
$name = $row['name'];
$song = $row['songname'];
$dedicatedto = $row['dedicatedto'];
?>
<script>
function delete_req(id){
alert("hello");
}
</script>
<?php
$data .= ' <tr cellpadding="5" cellspacing="6" align="center" width="60%">
<td>'.$id.'</td>
<td>'.$name.'</td>
<td>'.$song.'</td>
<td>'.$dedicatedto.'</td>
<td>Delete</td>
</tr>';
}
$display = ' <table "cellspacing="4" align="center">
<tr>
<th>ID</th>
<th>Name</th>
<th>Song</th>
<th>Dedicated to</th>
<th>Delete</th>
'.$data.'
</tr>
</table>';
$response = array();
$response['data_from_db'] = $display;
$response['count'] = $count;
echo json_encode($response);
}
Here the response['count'] is showing on my php page but not $response['data_from_db'].
And when I delete the javascript code then both of them are showing.. Help needed.
I should mention that am using NGINX and php5-fpm
You have a brace mismatch.
Add a brace } after $dedicatedto = $row['dedicatedto']; Your while loop wasn't properly closed.
$action = isset($_GET['action']);
if($action == "get_requests"){
include("../connect.php");
$sql_song_req = "SELECT COUNT(*) FROM `song_requests`";
$sql_select_song = "SELECT * FROM `song_requests` ORDER BY id ASC";
$sql_count = $rad->prepare($sql_song_req);
$sql_count->execute();
$count = $sql_count->fetchColumn();
$select_song_prep = $rad->prepare($sql_select_song);
$select_song_prep->execute();
while($row = $select_song_prep->fetch(PDO::FETCH_ASSOC)){
$id = $row['id'];
$name = $row['name'];
$song = $row['songname'];
$dedicatedto = $row['dedicatedto'];
} // <- added. Brace for while loop
?>
<script>
function delete_req(id){
alert("hello");
}
</script>
<?php
$data .= ' <tr cellpadding="5" cellspacing="6" align="center" width="60%">
<td>'.$id.'</td>
<td>'.$name.'</td>
<td>'.$song.'</td>
<td>'.$dedicatedto.'</td>
<td>Delete</td>
</tr>';
$display = ' <table "cellspacing="4" align="center">
<tr>
<th>ID</th>
<th>Name</th>
<th>Song</th>
<th>Dedicated to</th>
<th>Delete</th>
'.$data.'
</tr>
</table>';
$response = array();
$response['data_from_db'] = $display;
$response['count'] = $count;
echo json_encode($response);
}