I have constructed an SQL query to provide a summary of stock holdings, i.e. group all stock transactions for a given stock, using PHP, PDO, MySQL. The SQL works when tested PHPMyAdmin, ( by changing named parameters from :c_code to c.code, :exchange to "LSE", :p_portfolio_id to p.portfolio_id )
I am unsure how to construct the bindParam statement(s) in such a scenario, or if I must use a JOIN statement in the query. I am relatively new to thsi but learning fast, many thanks for any help Cheers Colin here is the code.
changed the code returns no errors but no records either ..
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT
t.user_id AS tuser_id,
p.user_id AS puser_id,
t.exchange AS exchange,
t.code AS code,
c.name AS name,
p.name AS portfolio,
CEILING(c.price * t.quantity / 100) AS value,
DATE_FORMAT(t.trade_date,'%d%m%y') AS trade_date,
t.type AS type,
SUM(t.quantity) AS quantity,
t.price AS price,
SUM(t.commission) AS commission,
SUM(t.total_cost) AS total_cost
FROM
transaction t, company c, portfolio p
WHERE
t.code = :c_code
AND
t.exchange = :t_exchange
AND
t.portfolio_id = :p_portfolio_id
GROUP BY
t.code
ORDER BY
t.code ";
if(isset($_POST["search"]["value"]))
{
$query .= 'AND trade_date LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR exchange LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR code LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR type LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR quantity LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR price LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR commission LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR total_cost LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY id DESC ';
}
if($_POST["length"] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$exchange = "LSE";
$statement = $connection->prepare($query);
$statement->bindParam(':t_exchange', $exchange, PDO::PARAM_STR);
$statement->bindParam(':c_code', $_POST['company.code'], PDO::PARAM_STR);
$statement->bindParam(':p_portfolio_id', $_POST['portfolio.id'], PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row["trade_date"];
$sub_array[] = $row["exchange"];
$sub_array[] = $row["code"];
$sub_array[] = $row["type"];
$sub_array[] = $row["quantity"];
$sub_array[] = $row["price"];
$sub_array[] = $row["commission"];
$sub_array[] = $row["total_cost"];
$sub_array[] = '<button type="button" name="update" id="'.$row["id"].'" class="btn btn-warning btn-xs update">Update</button>';
$sub_array[] = '<button type="button" name="delete" id="'.$row["id"].'" class="btn btn-danger btn-xs delete">Delete</button>';
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
?>
This SQL below run in PHPMyAdmin SQL works ok
SELECT
t.user_id AS tuser_id,
p.user_id AS puser_id,
t.exchange AS exchange,
t.code AS code,
c.name AS name,
p.name AS portfolio,
CEILING(c.price * t.quantity / 100) AS value,
DATE_FORMAT(t.trade_date,'%d%m%y') AS trade_date,
t.type AS type,
SUM(t.quantity) AS quantity,
t.price AS price,
SUM(t.commission) AS commission,
SUM(t.total_cost) AS total_cost
FROM
transaction t, company c, portfolio p
WHERE
t.code = c.code
AND
t.exchange = "LSE"
AND
t.portfolio_id = p.id
GROUP BY
t.code
ORDER BY
t.code
I am trying to integrate some of code recommended here by calling holdg_fetch.php from holdg_home.php to display the MySQL data in a table but I am getting an error "DataTables warning:table id=transaction_data - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1 " I can run holdg_fetch.php on its own successfully, no errors. I can run holdg_home.php calling trans_fetch.php successfuly, no errors.
Note: I will sort out the security and structure from your recommendations, once I fix this JSON error. Many Thanks in advance Colin
trans_fetch.php
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "
SELECT
*,
DATE_FORMAT(trade_date,'%d%m%y') AS trade_date
FROM
transaction ";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE trade_date LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR exchange LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR code LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR type LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR quantity LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR price LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR commission LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR total_cost LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY id DESC ';
}
if($_POST["length"] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row["trade_date"];
$sub_array[] = $row["exchange"];
$sub_array[] = $row["code"];
$sub_array[] = $row["type"];
$sub_array[] = $row["quantity"];
$sub_array[] = $row["price"];
$sub_array[] = $row["commission"];
$sub_array[] = $row["total_cost"];
$sub_array[] = '<button type="button" name="update" id="'.$row["id"].'" class="btn btn-warning btn-xs update">Update</button>';
$sub_array[] = '<button type="button" name="delete" id="'.$row["id"].'" class="btn btn-danger btn-xs delete">Delete</button>';
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
?>
holdg_home.php
<?php include 'db.php'; ?>
<?php include("header-nav2.php"); ?>
<main>
<div class="container box">
<br />
<div class="table-responsive">
<br />
<div align="right">
<button type="button" id="add_button" data-toggle="modal" data-target="#transactionModal" class="btn btn-warning"><i class="fa fa-plus" aria-hidden="true"></i></button>
</div>
<br />
<table id="transaction_data" class="table table-bordered table-striped">
<thead class="blue-grey lighten-4">
<tr>
<th width="11%">TradeDate</th>
<th width="11%">Exchange</th>
<th width="11%">Code</th>
<th width="11%">Type</th>
<th width="11%">Quantity</th>
<th width="11%">Price</th>
<th width="11%">Commission</th>
<th width="11%">TotalCost</th>
<th width="6%">Edit</th>
<th width="6%">Delete</th>
</tr>
</thead>
</table>
</div>
</div>
<?php include("footer.php"); ?>
</body>
</html>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
$('#add_button').click(function(){
$('#transaction_form')[0].reset();
$('.modal-title').text("Add Transaction");
$('#action').val("Add");
$('#operation').val("Add");
});
var dataTable = $('#transaction_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"holdg_fetch.php",
type:"POST"
},
"columnDefs":[
{//removes sort from columns given by targets, where 0 - remove Column 1 sort etc.
"targets":[8, 9],
"orderable":false,
},
],
});
...
holdg_fetch.php
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "
SELECT
t.user_id AS tuser_id,
p.user_id AS puser_id,
t.exchange AS exchange,
t.code AS code,
c.name AS name,
p.name AS portfolio,
CEILING(c.price * t.quantity / 100) AS value,
DATE_FORMAT(t.trade_date,'%d%m%y') AS trade_date,
t.type AS type,
SUM(t.quantity) AS quantity,
t.price AS price,
SUM(t.commission) AS commission,
SUM(t.total_cost) AS total_cost
FROM
transaction t
inner join company c on (t.code=c.code)
inner join portfolio p on (t.portfolio_id = p.id)
GROUP BY
t.code";
// WHERE
// 1=1
//if(isset($_POST["search"]["value"]))
//{
// $query .= ' WHERE trade_date LIKE "%'.$_POST["search"]["value"].'%" ';
// $query .= 'OR exchange LIKE "%'.$_POST["search"]["value"].'%" ';
// $query .= 'OR code LIKE "%'.$_POST["search"]["value"].'%" ';
// $query .= 'OR type LIKE "%'.$_POST["search"]["value"].'%" ';
// $query .= 'OR quantity LIKE "%'.$_POST["search"]["value"].'%" ';
// $query .= 'OR price LIKE "%'.$_POST["search"]["value"].'%" ';
// $query .= 'OR commission LIKE "%'.$_POST["search"]["value"].'%" ';
// $query .= 'OR total_cost LIKE "%'.$_POST["search"]["value"].'%" ';
//}
//if(isset($_POST["order"]))
//{
// $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
//}
//else
//{
// $query .= 'ORDER BY id DESC ';
//}
//if($_POST["length"] != -1)
//{
// $query .= ' LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
//}
//$query .= ' GROUP BY t.code';
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
var_dump($result);
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row["trade_date"];
$sub_array[] = $row["exchange"];
$sub_array[] = $row["code"];
$sub_array[] = $row["type"];
$sub_array[] = $row["quantity"];
$sub_array[] = $row["price"];
$sub_array[] = $row["commission"];
$sub_array[] = $row["total_cost"];
// $sub_array[] = '<button type="button" name="update" id="'.$row["id"].'" class="btn btn-warning btn-xs update">Update</button>';
// $sub_array[] = '<button type="button" name="delete" id="'.$row["id"].'" class="btn btn-danger btn-xs delete">Delete</button>';
$data[] = $sub_array;
}
$output = array(
// "draw" => intval($_POST["draw"]),
//"recordsTotal" => $filtered_rows,
//"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
?>
I have now fixed the JSON error, mismatch of data and selected columns, please ignore above error, now fixed