How to merge 2 arrays and print in table? - php

I want to merge $output and $output1 and then populate a HTML table.
This is my code:
<?php
$link = parse_ini_file(__DIR__ . '/config.ini', true);
include("connect.php");
$output = '';
$cnn = simplexml_load_file($link['cnn']);
$bbc = simplexml_load_file($link['bbc']);
foreach($cnn->channel->item as $item){
$title = $item->title;
$description = $item->description;
$url = $item->link;
$pubDate = $item->pubDate;
$title1 = str_replace("'","\'", $title);
$description1 = str_replace("'","\'", $description);
$output[]['title'] = $title;
$output[]['description'] = $description;
$output[]['url'] = $url;
$output[]['p_date'] = $pubDate;
$sql = mysql_query("INSERT IGNORE INTO tbl_daily_news_headlines (
title,
description,
url,
pub_date,
log_date)
VALUES (
'$title1',
'$description1',
'$url',
'$pubDate',
now())")
or die(mysql_error());
}
foreach ($bbc->channel->item as $bitem){
$bbtitle = $bitem->title;
$bbdescription = $bitem->description;
$bburl = $bitem->link;
$bbpubDate = $bitem->pubDate;
$bbtitle1 = str_replace("'", "\'", $bbtitle);
$bbdescription1 = str_replace("'", "\'", $bbdescription);
$output1[]['title'] = $bbtitle;
$output1[]['description'] = $bbdescription;
$output1[]['url'] = $bburl;
$output1[]['p_date'] = $bbpubDate;
$sql = mysql_query("INSERT IGNORE INTO tbl_daily_news_headlines(
title,
description,
url,
pub_date,
log_date)
VALUES(
'$bbtitle1',
'$bbdescription1',
'$bburl',
'$bbpubDate',now())")
or die(mysql_error());
$final_output = array_merge($output, $output1);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0">
<title>Feed Example</title>
<link rel="stylesheet" type="text/css" href="media/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="media/css/dataTables.bootstrap.css">
<script type="text/javascript" language="javascript" src="media/js/jquery-1.12.0.min.js">
</script>
<script type="text/javascript" language="javascript" src="media/js/jquery.dataTables.js">
</script>
<script type="text/javascript" language="javascript" src="media/js/dataTables.bootstrap.js">
</script>
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
$('#example').DataTable();
} );
</script>
</head>
<body class="dt-example dt-example-bootstrap">
<div class="container">
<section>
<h1>FEED Test</h1>
<div class="info">
</div>
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>URL</th>
<th>Publish Date</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Title</th>
<th>Description</th>
<th>URL</th>
<th>Publish Date</th>
</tr>
</tfoot>
<tbody>
<? foreach($final_output as $data1)
{
echo '<td>'.$data1['title'].$data1['description'].$data1['url'].$data1['p_date'].'</td>';
}
?>
</tbody>
</table>
</div>
</section>
</body>
</html>
I tried array_merge() but it's not working.
I also tried:
$data = $output + $output1;
Where am I wrong, did I incorrectly place my loops?
EDIT:
So after i try array_merge($output,$output1); its just outputs just last element of array, second method is same
i just try to do some inner foreach like
<? foreach($output as $data)
{
foreach($output1 as $data1)
{
echo '<td>'.$data.$data1'</td>';
}
}
?>
but i got 500 error, so any ideas?
EDIT 2:
Thanks to Patrick i merge these 2 outputs but still cant get printed on table, if you look my updated code right now its print them in horizontally(Everything in 1 lane), how to get fixed?

The reason why you are only getting one element is because you are overwriting the previous value each time through your foreach loops. You need to create a new entry in your $output and $output1 arrays each time.
Instead of
$output['title'] = $title;
$output['description'] = $description;
$output['url'] = $url;
$output['p_date'] = $pubDate;
and
$output1['title'] = $bbtitle;
$output1['description'] = $bbdescription;
$output1['url'] = $bburl;
$output1['p_date'] = $bbpubDate;
You should have
$output[]['title'] = $title;
$output[]['description'] = $description;
$output[]['url'] = $url;
$output[]['p_date'] = $pubDate;
and
$output1[]['title'] = $bbtitle;
$output1[]['description'] = $bbdescription;
$output1[]['url'] = $bburl;
$output1[]['p_date'] = $bbpubDate;

for DataTables you want it in some sort of JSON format. Here's how I'd do it using what you have there, and quickly (untested)
<?php
$final_output = array_merge($output, $output1);
and HTML/Javascript
<script type="text/javascript">
var php_data = <?php echo json_encode($final_output); ?>
$("#example").DataTable({
data: php_data
});
</script>
<table id="example">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>URL</th>
<th>Publish Date</th>
<tr>
</thead>
</table>
However, a much nicer way to do this would be via ajax. Check the docs out for DataTables: https://www.datatables.net/examples/ajax/
and an example of how you might format your data if you don't use ajax:
https://www.datatables.net/examples/data_sources/js_array.html

Related

auto load data in ajax how to change it into click button

what happen in the code is that everytime i choose in multiple drop down it fetch the data what i want to happen is to click the button first then it will fetch the data...... thank u guys got the code in here https://www.webslesson.info/2018/05/ajax-live-data-search-using-multi-select-dropdown-in-php.html
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=db", "root", "");
$query = "SELECT DISTINCT Country FROM tbl_customer ORDER BY Country ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Live Data Search using Multi Select Dropdown in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="css/bootstrap-select.min.css" rel="stylesheet" />
<script src="js/bootstrap-select.min.js"></script>
</head>
<body>
<div class="container">
<br />
<h2 align="center">Ajax Live Data Search using Multi Select Dropdown in PHP</h2><br />
<select name="multi_search_filter" id="multi_search_filter" multiple class="form-control selectpicker">
<?php
foreach($result as $row)
{
echo '<option value="'.$row["Country"].'">'.$row["Country"].'</option>';
}
?>
</select>
<input type="hidden" name="hidden_country" id="hidden_country" />
<div style="clear:both"></div>
<br />
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Customer Name</th>
<th>Address</th>
<th>City</th>
<th>Postal Code</th>
<th>Country</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<br />
<br />
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query='')
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('tbody').html(data);
}
})
}
$('#multi_search_filter').change(function(){
$('#hidden_country').val($('#multi_search_filter').val());
var query = $('#hidden_country').val();
load_data(query);
});
});
</script>
fetch.php
//fetch.php
$connect = new PDO("mysql:host=localhost;dbname=dbattendancelibrary", "root", "");
if($_POST["query"] != '')
{
$search_array = explode(",", $_POST["query"]);
$search_text = "'" . implode("', '", $search_array) . "'";
$query = "
SELECT * FROM tbl_customer
WHERE Country IN (".$search_text.")
ORDER BY CustomerID DESC
";
}
else
{
$query = "SELECT * FROM tbl_customer ORDER BY CustomerID DESC";
}
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
foreach($result as $row)
{
$output .= '
<tr>
<td>'.$row["CustomerName"].'</td>
<td>'.$row["Address"].'</td>
<td>'.$row["City"].'</td>
<td>'.$row["PostalCode"].'</td>
<td>'.$row["Country"].'</td>
</tr>
';
}
}
else
{
$output .= '
<tr>
<td colspan="5" align="center">No Data Found</td>
</tr>
';
}
echo $output;
?>
It fires an ajax call because of this code:
$('#multi_search_filter').change(function(){
$('#hidden_country').val($('#multi_search_filter').val());
var query = $('#hidden_country').val();
load_data(query);
});
If you want to fire when clicking on a button, you will need to put in HTML for the button first. Then use the id for load_data event, for example you will have a button called '#btn_search':
$('#multi_search_filter').change(function(){
$('#hidden_country').val($('#multi_search_filter').val());
});
$('#btn_search').click(function(e){
e.preventDefault();
var query = $('#hidden_country').val();
load_data(query);
});
Your full HTML above becomes like this:
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=db", "root", "");
$query = "SELECT DISTINCT Country FROM tbl_customer ORDER BY Country ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Live Data Search using Multi Select Dropdown in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="css/bootstrap-select.min.css" rel="stylesheet" />
<script src="js/bootstrap-select.min.js"></script>
</head>
<body>
<div class="container">
<br />
<h2 align="center">Ajax Live Data Search using Multi Select Dropdown in PHP</h2><br />
<select name="multi_search_filter" id="multi_search_filter" multiple class="form-control selectpicker">
<?php
foreach($result as $row)
{
echo '<option value="'.$row["Country"].'">'.$row["Country"].'</option>';
}
?>
</select>
<input id="btn_search" type="button" value="Filter" />
<input type="hidden" name="hidden_country" id="hidden_country" />
<div style="clear:both"></div>
<br />
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Customer Name</th>
<th>Address</th>
<th>City</th>
<th>Postal Code</th>
<th>Country</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<br />
<br />
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query='')
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('tbody').html(data);
}
})
}
$('#multi_search_filter').change(function(){
$('#hidden_country').val($('#multi_search_filter').val());
});
$('#btn_search').click(function(e){
e.preventDefault();
var query = $('#hidden_country').val();
load_data(query);
});
});
</script>

linking rows of mySQL database to the referred page

I am having difficulty in linking each row of my database to display the link which will show another mySQL database table. I think the error comes from the second part of my code not the first where my query might not be right but i cant figure out which part I need to change.
these are my codes so far:
</tr>
</thead>
<?php
while($row = mysqli_fetch_array($result))
{
$id = $row['my30_rsl_id'];
$SupplierName = $row['SupplierName'];
$Commodity = $row['Commodity'];
echo '
<tr>
<td>'.$row["my30_rsl_id"].'</td>
<td>' . $SupplierName . '</td>
<td>' . $Commodity . '</td>
<td>'.$row["Sub-Category"].'</td>
<td>'.$row["Status"].'</td>
<td>'.$row["Location"].'</td>
</tr>
';
}
?>
</table>
the page where the link refers to :
(it returns error at $result)
<?php
$connect = mysqli_connect("localhost", "root", "password", "database");
$id = $_GET['id'];
$result = mysqli_query($con,"SELECT * FROM my30_rsl WHERE my30_rsl_id = $id");
?>
<!DOCTYPE html>
<html>
<head>
<title>Details</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container">
<h3 align="center">Details</h3>
<br />
<div class="table-responsive">
<table id="supplier_data" class="table table-striped table-bordered">
<thead>
<tr>
<td>SupplierName</td>
<td>Comments</td>
</tr>
</thead>
<?php
while($row = mysqli_fetch_array($result))
{
echo '
<tr>
<td> <a href=#>'.$row["SupplierName"] . '</a> </td>
<td>'.$row["Comments"].'</td>
</tr>
';
}
?>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#supplier_data').DataTable();
});
</script>
probably some naming issues? Your code with comment
$connect = mysqli_connect("localhost", "root", "password", "database");
$id = $_GET['id'];
$result = mysqli_query($con,"SELECT * FROM my30_rsl WHERE my30_rsl_id = $id");
// ^--- where does that come from? you only have $connect
so you probably have to name it $connect. If that's not the problem, maybe you should look at the error messages, use search engines for that error message and find out what's wrong.
Also, your code is vulnerable to sql injections. Learn how to use prepared statements, please.

Get data of multiple columns from SQL Server using PHP

I am trying to select the data from SQL Server but only the columns stored in the variable SelectedColumns. This variable store the columns' names separated by comma from a drop Down list. For example : echo $SelectedColumns will display Country,Product,Date
I could create the header of the table by exploding the variable and use foreach. Now I want to get the data of these columns display it in the <tbody> </tbody>
Here is my php page :
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ser="********";
$db="********";
$user="********";
$pass="********";
$query = 'SELECT '.$_POST['selectedColumns'].' FROM ********';
$dbDB = new PDO("odbc:Driver=ODBC Driver 13 for SQL Server;Server=********,1456;Database=********;Port=1456", $user, $pass);
?>
<!DOCTYPE html>
<html>
<head>
<title>table</title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
</head>
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<?php
$row = $_POST["selectedColumns"];
$rows = explode(",",$row);
echo "<tr>";
foreach ($rows as $r ) {
echo "<td>";
echo $r;
echo "<td>";
}
echo "</tr>";
?>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
<script>
$(document).ready(function() {
$('#example').DataTable();
} );
</script>
I was trying this solution to use foreach twice
<?php
$row = $_POST["selectedColumns"];
$rows = explode(",",$row);
foreach ($dbDB->query($query) as $dataRow) {
echo "<tr>";
foreach ($rows as $r ) {
echo "<td>" . $dataRow[$r] . "</td>"; }
echo "</tr>";
}
?>
But it's not working. Any suggestions please ? Thank you very much.

AngularJS and PHP

I'm learning AngularJS and wondered how I could get the PHP database results into an angular model. What I have:
<!DOCTYPE html>
<html data-ng-app="statsApp">
<head>
<title>Student Stats</title>
<script src="angular.min.js"></script>
<link href="bootstrap.css" rel="stylesheet" />
<link href="bootstrap-theme.css" rel="stylesheet" />
<?PHP
// Include dbcreds.inc for db info.
include('dbcreds.inc');
if(isset($_GET['fname']) && $_GET['fname'] !== "")
{
$lname = $_GET['fname'] . "%";
$sql = $conn->prepare("select * from students where fname like ?");
$sql->execute(array($lname));
$res = $sql->fetchAll();
$rownum = 0;
echo "\n <SCRIPT>";
echo "\n var model = [";
foreach($res as $r)
{
$rownum++;
echo "\n ";
print_r(json_encode(array("ID" => intval($r['id']),"FNAME" => $r['fname'],"LNAME" => $r['lname'],"GPA" => doubleval($r['gpa']))));
// Add a comma, if it's not the last datarow.
if($rownum < count($res))
{
echo ",";
}
}
echo "\n ];";
echo "\n ";
echo "\n var statsApp = angular.module(\"statsApp\",[]);";
echo "\n ";
echo "\n statsApp.controller(\"statsAppCtrl\", function (\$scope) {";
echo "\n \$scope.stats = model;";
echo "\n });";
echo "\n </SCRIPT>\n ";
}
?>
</head>
<body data-ng-controller="statsAppCtrl">
<div class="page-header">
<h2>
<span class="label label-default">{{ stats.length }}</SPAN>
</h2>
</div>
<div class="panel">
<table class="table table-striped">
<thead>
<TR>
<TH>ID</TH>
<TH>First Name</TH>
<TH>Last Name</TH>
<TH>GPA</TH>
</TR>
</thead>
<tbody>
<tr data-ng-repeat="stats_item in stats | orderBy:'ID'">
<td>{{ stats_item.ID }}</td>
<td>{{ stats_item.FNAME }}</td>
<td>{{ stats_item.LNAME }}</td>
<td>{{ stats_item.GPA }}</td>
</tr>
</tbody>
</table>
</div>
</body>
</HTML>
It seems to work ok, but I'm questioning whether I'm on the right track with this method of doing things. Thanks.
Basically you want to make a call to a separate php file, which runs the query and echos a JSON encoded array for the Angular request to use.
Here is an example fiddle of the Angular side: https://jsfiddle.net/cmnv20ps/
function StudentsService($http) {
var service = {
getStudents: getStudents
};
return service;
function getStudents(fname) {
return $http.get('students.php', {
params: {
fname: fname
}
}).then(function(response) {
return response.data;
});
}
}
function Controller(StudentsService) {
var vm = this;
StudentsService.getStudents('Ro').then(function(data) {
vm.students = data.students;
});
}
PHP Example:
$fname = $_GET["fname"];
$sql = $db->prepare("select * from students where fname like :fname");
$sql->execute(array("fname"=>"%" . $fname . "%"));
$res = $sql->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(array("students"=>$res));

JQuery Barcode Only Generates One Barcode From Query Results

I have finally got a barcode to appear in my table that is generated from a Query. But now I am having an issue getting a code on each of the results from $row[1]. I tried to use PHP-BARCODE but it require too much memory to create all the barcodes. Jquery looks like it uses less memory to create them. Hence why I chose that method.
Any help on this would be AWESOME
My script is mainly PHP with an odd splash from JQUERY.
JQUERY for screen refresh and Barcode Generation. With soon more once i get past this hurdle.
<?php
include('inc/database.php');
// MSSQL Query
$sql = "SELECT warehouse, pick_order_number, order_status, pick_order_type, customer_order_number
FROM pick_order_header
WHERE warehouse = 'XDGM'
AND order_status <> 'Complete'
AND order_status <> 'Closed'
AND pick_order_type <> 'Backorder'
AND customer_order_number LIKE '%1 hr%'";
?>
<!DOCTYPE HTML>
<link rel="stylesheet" type="text/css" href="css/master.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="js/jquery-barcode.js"></script>
<script>
setTimeout(function(){
window.location.reload(1);
}, 5000);
</script>
<html>
<title>Current Orders</title>
<body>
<table>
<?php
// SQLSRV Query
$results = sqlsrv_query( $conn, $sql );
if( $results === false) {
die( print_r( sqlsrv_errors(), true) );
}
echo "
<table border=1>
<tr>
<th>Order Number</th>
<th>Order Status</th>
<th>Order Type</th>
<th>Customer Order</th>
<th>Barcode</th>
</tr>";
while ($row = sqlsrv_fetch_array($results))
{
$odrnum = $row[1];
$odrstatus = $row[2];
$odrtype = $row[3];
$custorder = $row[4];
$barcode = $row[1];
echo "
<tr>
<td>$odrnum</td>
<td>$odrstatus</td>
<td>$odrtype</td>
<td>$custorder</td>
<td>
<div id="bcTarget_'.$odrnum.'"><input type="button" id="bc" name="bc" value="Click Here" /></div>
</td>
<script>
$("#bc").click(function(){$("#bcTarget_'.$odrnum.'").barcode("'.$row[1].'", "code39",{barWidth:2.5, barHeight:30, showHRI: true, bgColor: "#DEF3CA"});});</script>
</tr>';
}
echo "</table>";
?>
</table>
</body>
</html>
I am a complete noob at this, so if you do find a solution could you explain it to me as well so I can learn?
Thanks a bunch
The problem is that you have more then one of the same ids bcTarget and jquery will select the first found within the DOM.
Try to make your ids for the selector unique:
echo '
<tr>
<td>'.$odrnum.'</td>
<td>'.$odrstatus.'</td>
<td>'.$odrtype.'</td>
<td>'.$custorder.'</td>
<td>
<div id="bcTarget_'.$odrnum.'"></div>
</td>
<script>
$(function(){$("#bcTarget_'.$odrnum.'").barcode("'.$row[1].'", "code39",{barWidth:2, barHeight:30});});</script>
</tr>';
u can use this code
<div class="bcTarget" rel="4874214545"></div>
//rel= 'barcode digits'
javascript
$(document).ready(function() {
$(".bcTarget").each(function() {
var bcdigits = $(this).attr('rel');
$(this).barcode(bcdigits, "code39",{barWidth:2, barHeight:30});
});
});

Categories