Have a php scripts that holds 2 functions.
In the first function the query is using the $get to fetch time and date.
The second function is making im trying to use the variable from the first function.
public function Execute( ) {
if( $_GET['from'] && $_GET['to'] ){
$from = $_GET['from'];
$to = $_GET['to'];
$query = "SELECT * from historie_ordre where kode = ? AND time BETWEEN ? AND ? AND order by time desc";
$orders = DB::query( $query, $kode, $from, $to )->fetchAll( DB::FETCH_ASSOC );
Util::Debug( $orders );
$this->stats = $orders;
}
$this->kode = $kode;
$this->from = $from;
$this->to = $to;
}
second funstion:
public function XLS( ) {
//trying to use this:
$from = intval($_GET['from']);
$to = intval($_GET['to']);
$kode = intval($_GET['kode']);
$query = "SELECT * from historie_ordre where kode = $kode AND time BETWEEN $from AND $to AND order by time desc";
$orders = DB::query( $query, $kode, $from, $to )->fetchAll( DB::FETCH_ASSOC );
$this->setTemplate( false );
$oldreporting = error_reporting( 0 );
require_once 'Spreadsheet/Excel/Writer.php';
// Creating a workbook
$workbook = new Spreadsheet_Excel_Writer();
// sending HTTP headers
$workbook->send('stabburet_stats.xls');
// Creating a worksheet
$worksheet =& $workbook->addWorksheet('My first worksheet');
// overskrift
//$worksheet->write(0, 0, 'Antall');
$worksheet->write(0, 1, 'kode');
$worksheet->write(0, 2, 'name');
$worksheet->write(0, 3, 'adress');
$i=1;
// for å få inn verdiane
foreach( $orders as $order ){
$i++;
//$worksheet->write($i, 0, $order['antall']);
$worksheet->write($i, 1, $order['kode']);
$worksheet->write($i, 2, utf8_decode( $order['name'] ) );
$worksheet->write($i, 3, utf8_decode ($order['adress']) );
}
// Sender fila
$workbook->close();
error_reporting( $oldreporting );
}
}
The first function is working. second is only working with "hardcoding" the variables.
It was pointed out to you in comments you need to be more careful and use the same techniques consistently. I also don't believe that the first function works, because your query syntax in each place is wrong.
The problem at very least is that you have an incorrect SELECT syntax with a spurious AND at the end. You also are using a column named time, which is a mysql reserved word. That might also be a problem, that can be mitigated by using the `column name` syntax.
$query = "SELECT *
from historie_ordre
WHERE kode = $kode
AND time BETWEEN $from AND $to AND
order by time desc";
Needs to be:
$query = "SELECT *
FROM historie_ordre
WHERE kode = ?
AND `time` BETWEEN ? AND ?
ORDER BY `time` DESC";
Updated:
Now that we have more information from you, the problem can also be traced to here:
$from = intval($_GET['from']);
$to = intval($_GET['to']);
$kode = intval($_GET['kode']);
The problem is that your from and to need to be strings in date format. You are forcing them to be zeros by turning them into integers. So again your query is not going to function.
$from = $_GET['from'];
$to = $_GET['to'];
$kode = intval($_GET['kode']);
Related
I want to get all messages and put it all into array , but there is another way i want sort all messages by id , for example:
my json :
{"msg_c":[{"message":"Hi","sender":"2","receve":"3","name":"Muhamad Bagzada"},{"message":"Hello","sender":"3","receve":"2","name":"Danyal Join"},{"message":"What's up , How are you ?","sender":"2","receve":"3","name":"Muhamad Bagzada"},{"message":"fine and you ?","sender":"3","receve":"2","name":"Danyal Join"},{"message":"fine","sender":"2","receve":"3","name":"Muhamad Bagzada"}]}
Exactly i want :
show messgaes in array by different value , ( message_u : my msg , messages_m : his msg)
{
"msg_c":
[
{"message_u":"Hi","sender":"2","receve":"3","name":"Muhamad Bagzada"},
{"message_m":"Hello","sender":"3","receve":"2","name":"Danyal Join"},
{"message_u":"What's up , How are you ?","sender":"2","receve":"3","name":"Muhamad Bagzada"},
{"message_m":"fine and you ?","sender":"3","receve":"2","name":"Danyal Join"},
{"message_m":"fine","sender":"2","receve":"3","name":"Muhamad Bagzada"}
]
}
php function :
public function MessageApp ($user_id,$sender){
$data ='';
$Messg = mysqli_query($this->_join, "SELECT * FROM `messages` WHERE (`from` = '$sender' AND `to` = '$user_id') OR (`from` = '$user_id' AND `to` = '$sender') ORDER BY dates ASC LIMIT 12 ");
while ($m = mysqli_fetch_assoc($Messg)) {
$from = $m['from'];
$to = $m['to'];
$chat = $m['chat'];
$dates = $m['dates'];
$id = $m['id'];
if ($user_id === $sender) {
$select_id = $to;
}else{
$select_id = $from;
}
$user = new user($from);
$fullname = ($user->data()->fname)." ".($user->data()->lname);
$gettype['msg_c'][] = array(
'message' => $chat,
'sender' => $from,
'receve' => $to,
'name'=>$fullname
);
$data = json_encode($gettype);
}
return json_encode($gettype);
}
I called json data here :
<?php
include $_SERVER['DOCUMENT_ROOT']."/php/core/init.php";
include $_SERVER['DOCUMENT_ROOT']."/php/core/connect.php";
$my_id = input::get('user_id');
$user = new user($my_id);
$sender = $user->data()->id;
$db = db::getInstance();
$message = new message();
$id = input::get("id");
$user = new user($id);
$user_id = $user->data()->id;
echo $message->MessageApp($user_id,$sender);
?>
When you building the row in msg_c, you can separate the set key in different situation like this
<?php
$msg_row = array(
'sender' => $from,
'receve' => $to,
'name'=> $fullname
);
if ($user_id === $sender) {
$msg_row['message_m'] = $chat;
} else {
$msg_row['message_u'] = $chat;
}
$gettype['msg_c'][] = $msg_row;
Or even build the array in the if else statement before to reuse the code
I have some difficulties getting the XLS function to add the query result in a xls file.
I have a html and a php file who is doing the job.
The query is working as it should, but i think the XLS function is not fetching the query result. I get "whitescreen" after pressing the button in the html file.
<div class="right" style="width:940px;">
Download as .XLS
</div>
i want the query to be saved in an xls file that can be saved localy.
The php is looking like this:
<?PHP
import( 'pages.admin' );
class AdminPortalStatistics extends AdminPage implements IView {
protected $template = 'order.stats';
public
function Execute() {
$kode = 'ST1';
$from = '2017-06-20';
$to = '2017-07-29';
if ($_GET['from'] && $_GET['to']) {
$from = $_GET['from'];
$to = $_GET['to'];
$query = "SELECT * from history_ordrer ho INNER JOIN history_cusomer hc ON ho.ordrenr = hc.ordrenr INNER JOIN history_mal hm ON ho.ordrenr = hm.ordrenr INNER JOIN histort_orderline hol ON ho.ordrenr = hol.ordrenr INNER JOIN kunde k ON ho.uid = k.uid WHERE ho.kode = ? AND ho.time BETWEEN ? AND ? AND ho.deleted is null order by ho.ordernr desc";
$orders = DB::query($query, $kode, $from, $to) - > fetchAll(DB::FETCH_ASSOC);
$this - > stats = $orders;
}
$this - > kode = $kode;
$this - > from = $from;
$this - > to = $to;
}
public function XLS( ) {
$this->Execute( );
$this->setTemplate( false );
$oldreporting = error_reporting( 0 );
require_once 'Spreadsheet/Excel/Writer.php';
// Creating a workbook
$workbook = new Spreadsheet_Excel_Writer();
// sending HTTP headers
$workbook->send('test.xls');
// Creating a worksheet
$worksheet =& $workbook->addWorksheet( 'Report' );
// write the data
$fields = array_merge( array( 'Period' ), $this->series );
$worksheet->writeRow( $row++, 0, $fields );
foreach( $this->values as $graph ) {
$line = array_merge( array( $graph['label'] ), $graph['data'] );
$worksheet->writeRow( $row++, 0, $line );
}
// Let's send the file
$workbook->close();
error_reporting( $oldreporting );
}
}
?>
I need your help on this php function.
The function takes the data from the db, does the account of the score and exports it. In practice the score must be calculated for both the buyer and for the seller ($type) but when I go to export I only have one of the buyers. The code in question is below. Thanks in advance for the help.
function shop_get_ratings($user_id, $type = 'seller'){
$type = strtolower($type);
$valid = array('seller','buyer');
if( !in_array($type, $valid)){
return false;
}
$conn = getConnection();
$sql = 'SELECT AVG(i_%s_score) as %s_rating FROM %st_shop_transactions WHERE fk_i_user_id = %d AND i_%s_score IS NOT NULL';
$rs = $conn->osc_dbFetchResults(sprintf($sql,$type,$type, DB_TABLE_PREFIX, $user_id, $type));
$seller_r = 0;
if( false !== $rs && isset($rs[0]['seller_rating']) && !is_null($rs[0]['seller_rating']) ){
$seller_r = (int)$rs[0]['seller_rating'];
}
$sql = 'SELECT COUNT(*) as rating_count FROM %st_shop_transactions WHERE fk_i_user_id = %d AND i_%s_score IS NOT NULL';
$rs = $conn->osc_dbFetchResults(sprintf($sql, DB_TABLE_PREFIX, $user_id, $type));
$seller_r_c = 0;
if( false !== $rs && isset($rs[0]['rating_count']) && !is_null($rs[0]['rating_count']) ){
$seller_r_c = (int)$rs[0]['rating_count'];
}
$percentage = 0;
if( $seller_r > 0 ){
$percentage =($seller_r/5)*100;
}
$stats = array(
'average_rating' => (int)$seller_r,
'rating_percentege' => (float)$percentage,
'rating_count' => (int)$seller_r_c,
);
View::newInstance()->_exportVariableToView($type.'_ratings', $stats);
return $stats;
}
From reading the code, it looks like you should get a rating for the seller ok, but it's the buyer who ends up with a 0 rating.
This is because in the line $sql = 'SELECT AVG(i_%s_score) as %s_rating you are inserting $type in to the query to have the field named seller_type or buyer_type, depending on the type of rating you're trying to get with the function.
However when querying the result set you are explicitly looking for the field named seller_rating. This field won't be set when $type is buyer, so $seller_r will always be 0.
The simplest fix here is likely to name the field as something like avg_rating in the sql, with no $type-dependent var name injection. So, something like:
$sql = 'SELECT AVG(i_%s_score) as avg_rating
FROM %st_shop_transactions
WHERE fk_i_user_id = %d
AND i_%s_score IS NOT NULL';
$rs = $conn->osc_dbFetchResults(
sprintf($sql, $type, DB_TABLE_PREFIX, $user_id, $type)
);
$seller_r = 0;
if (false !== $rs
&& isset($rs[0]['avg_rating'])
&& !is_null($rs[0]['avg_rating'])
){
$seller_r = (int)$rs[0]['avg_rating'];
}
I have a form with 4 checkboxes; debut, batted, no and bowled. When adding, if one is checked, it will add in the data with this code (in this instance, debut):
if(!empty($_POST["debut"])) {
try
{
$sql = 'INSERT INTO performance SET
matchid = :matchid,
playerid = :playerid,
team = :team,
debut = 1,
batted = 0,
batpos = :batpos,
runs = :runs,
ballsfaced = :ballsfaced,
fours = :fours,
sixes = :sixes,
no = 0,
howout = :howout,
fielder = :fielder,
bowler = :bowler,
bowled = 0,
ballsbowled = :ballsbowled,
maidens = :maidens,
wickets = :wickets,
runsconceded = :runsconceded,
catches = :catches,
stumpings = :stumpings,
runouts = :runouts';
$s = $pdo->prepare($sql);
$s->bindValue(':matchid', $_POST['matchid']);
$s->bindValue(':playerid', $_POST['playerid']);
$s->bindValue(':team', $_POST['team']);
$s->bindValue(':batpos', $_POST['batpos']);
$s->bindValue(':runs', $_POST['runs']);
$s->bindValue(':ballsfaced', $_POST['ballsfaced']);
$s->bindValue(':fours', $_POST['fours']);
$s->bindValue(':sixes', $_POST['sixes']);
$s->bindValue(':howout', $_POST['howout']);
$s->bindValue(':fielder', $_POST['fielder']);
$s->bindValue(':bowler', $_POST['bowler']);
$s->bindValue(':ballsbowled', $_POST['ballsbowled']);
$s->bindValue(':maidens', $_POST['maidens']);
$s->bindValue(':wickets', $_POST['wickets']);
$s->bindValue(':runsconceded', $_POST['runsconceded']);
$s->bindValue(':catches', $_POST['catches']);
$s->bindValue(':stumpings', $_POST['stumpings']);
$s->bindValue(':runouts', $_POST['runouts']);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error adding submitted performance.';
include 'error.html.php';
exit();
}
}
And it works perfectly fine. But if I try a combination (eg debut and batted) it doesnt work by using this code:
else if(!empty($_POST["debut"]) && (!empty($_POST["batted"]))) {
try
{
$sql = 'INSERT INTO performance SET
matchid = :matchid,
playerid = :playerid,
team = :team,
debut = 1,
batted = 1,
batpos = :batpos,
runs = :runs,
ballsfaced = :ballsfaced,
fours = :fours,
sixes = :sixes,
no = 0,
howout = :howout,
fielder = :fielder,
bowler = :bowler,
bowled = 0,
ballsbowled = :ballsbowled,
maidens = :maidens,
wickets = :wickets,
runsconceded = :runsconceded,
catches = :catches,
stumpings = :stumpings,
runouts = :runouts';
$s = $pdo->prepare($sql);
$s->bindValue(':matchid', $_POST['matchid']);
$s->bindValue(':playerid', $_POST['playerid']);
$s->bindValue(':team', $_POST['team']);
$s->bindValue(':batpos', $_POST['batpos']);
$s->bindValue(':runs', $_POST['runs']);
$s->bindValue(':ballsfaced', $_POST['ballsfaced']);
$s->bindValue(':fours', $_POST['fours']);
$s->bindValue(':sixes', $_POST['sixes']);
$s->bindValue(':howout', $_POST['howout']);
$s->bindValue(':fielder', $_POST['fielder']);
$s->bindValue(':bowler', $_POST['bowler']);
$s->bindValue(':ballsbowled', $_POST['ballsbowled']);
$s->bindValue(':maidens', $_POST['maidens']);
$s->bindValue(':wickets', $_POST['wickets']);
$s->bindValue(':runsconceded', $_POST['runsconceded']);
$s->bindValue(':catches', $_POST['catches']);
$s->bindValue(':stumpings', $_POST['stumpings']);
$s->bindValue(':runouts', $_POST['runouts']);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error adding submitted performance.';
include 'error.html.php';
exit();
}
}
And in this instance only debut will be inserted as 1. What am I doing wrong?
I notice this is inside an elseif statement... maybe the first condition is met and this part of the code is never executed?
If this code follows the above if statement, that would definitely be the case.
[edit]
You should check for code duplication as well, if the only difference is setting 'batted' and 'debut' to 0 or 1, there is a much shorter way of doing it without the 'if' statement.
$debut = (isset($_POST['debut']) ? 1 : 0);
$batted = (isset($_POST['batted']) ? 1 : 0);
Then just bind the values as you did with the others. see http://davidwalsh.name/php-ternary-examples for examples of ternary statements
I'm trying to work out how to move the $sql_pay_det query outside of the $sql_pay loop (so in effect query on $rs_pay_det rather than creating a new $rs_pay_det for each iteration of the loop)
At the moment my code looks like:
//Get payroll transactions
$sql_pay = 'SELECT Field1, DescriptionandURLlink, Field5, Amount, Field4, PeriodName FROM tblgltransactionspayroll WHERE CostCentreCode = "'.$cc.'" AND SubjectiveCode = "'.$subj.'" AND PeriodNo = "'.$month.'"';
$rs_pay = mysql_query($sql_pay);
$row_pay = mysql_fetch_assoc($rs_pay);
while($row_pay = mysql_fetch_array($rs_pay))
{
$employee_name = $row_pay['Field1'];
$assign_no = $row_pay['DescriptionandURLlink'];
$pay_period = $row_pay['Field5'];
$mth_name = $row_pay['PeriodName'];
$amount = $row_pay['Amount'];
$total_amount = $total_amount + $amount;
$amount = my_number_format($amount, 2, ".", ",");
$sql_pay_det = 'SELECT ElementDesc, Amount, WTEWorked, WTEPaid, WTEContract, Payscale FROM tblpayrolldetail WHERE CostCentreCode = "'.$cc.'" AND SubjectiveCode = "'.$subj.'" AND AccountingPeriod = "'.$mth_name.'" AND EmployeeRef = "'.$assign_no.'"';
$rs_pay_det = mysql_query($sql_pay_det);
$row_pay_det = mysql_fetch_assoc($rs_pay_det);
while($row_pay_det = mysql_fetch_array($rs_pay_det))
{
$element_det = $row_pay_det['ElementDesc'];
$amount_det = $row_pay_det['Amount'];
$wte_worked = $row_pay_det['WTEWorked'];
$wte_paid = $row_pay_det['WTEPaid'];
$wte_cont = $row_pay_det['WTEContract'];
$payscale = $row_pay_det['Payscale'];
//Get band/point and annual salary where element is basic pay
if ($element_det =="3959#Basic Pay"){
$sql_payscale = 'SELECT txtPayscaleName, Salary FROM tblpayscalemapping WHERE txtPayscale = "'.$payscale.'"';
$rs_payscale = mysql_query($sql_payscale);
$row_payscale = mysql_fetch_assoc($rs_payscale);
$grade = $row_payscale['txtPayscaleName'];
$salary = "£" . my_number_format($row_payscale['Salary'], 0, ".", ",");
}
}
}
I've tried doing this:
//Get payroll transactions
$sql_pay = 'SELECT Field1, DescriptionandURLlink, Field5, Amount, Field4, PeriodName FROM tblgltransactionspayroll WHERE CostCentreCode = "'.$cc.'" AND SubjectiveCode = "'.$subj.'" AND PeriodNo = "'.$month.'"';
$rs_pay = mysql_query($sql_pay);
$row_pay = mysql_fetch_assoc($rs_pay);
//Get payroll detail recordset
$sql_pay_det = 'SELECT ElementDesc, Amount, WTEWorked, WTEPaid, WTEContract, Payscale, EmployeeRef FROM tblpayrolldetail WHERE CostCentreCode = "'.$cc.'" AND SubjectiveCode = "'.$subj.'" AND AccountingPeriod = "'.$mth_name.'"';
$rs_pay_det = mysql_query($sql_pay_det);
while($row_pay = mysql_fetch_array($rs_pay))
{
$employee_name = $row_pay['Field1'];
$assign_no = $row_pay['DescriptionandURLlink'];
$pay_period = $row_pay['Field5'];
$mth_name = $row_pay['PeriodName'];
$amount = $row_pay['Amount'];
$total_amount = $total_amount + $amount;
$amount = my_number_format($amount, 2, ".", ",");
//Query $rs_pay_det
$sql_pay_det2 = 'SELECT ElementDesc, Amount, WTEWorked, WTEPaid, WTEContract, Payscale FROM ('.$sql_pay_det.') tpd WHERE EmployeeRef = "'.$assign_no.'"';
$rs_pay_det2 = mysql_query($sql_pay_det2);
$row_pay_det2 = mysql_fetch_assoc($rs_pay_det2);
while($row_pay_det2 = mysql_fetch_array($rs_pay_det2))
{
$element_det = $row_pay_det2['ElementDesc'];
$amount_det = $row_pay_det2['Amount'];
$wte_worked = $row_pay_det2['WTEWorked'];
$wte_paid = $row_pay_det2['WTEPaid'];
$wte_cont = $row_pay_det2['WTEContract'];
$payscale = $row_pay_det2['Payscale'];
//Get band/point and annual salary where element is basic pay
if ($element_det =="3959#Basic Pay"){
$sql_payscale = 'SELECT txtPayscaleName, Salary FROM tblpayscalemapping WHERE txtPayscale = "'.$payscale.'"';
$rs_payscale = mysql_query($sql_payscale);
$row_payscale = mysql_fetch_assoc($rs_payscale);
$grade = $row_payscale['txtPayscaleName'];
$salary = "£" . my_number_format($row_payscale['Salary'], 0, ".", ",");
}
}
}
But I get an error on $row_pay_det2 saying that "mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource"
Your subquery syntax (... FROM "'.$rs_pay_det.'" ...) is wrong.
According to the manual - dev.mysql.com/doc/refman/5.0/en/from-clause-subqueries.html
Subqueries are legal in a SELECT statement's FROM clause. The actual
syntax is:
SELECT ... FROM (subquery) [AS] name ...
Try changing to-
$sql_pay_det2 = 'SELECT ElementDesc, Amount, WTEWorked, WTEPaid, WTEContract, Payscale FROM ('.$sql_pay_det.') tpd WHERE EmployeeRef = "'.$assign_no.'"';
Edit - Issue #2
You are only getting the 2nd row in your data set as you have duplicate code (mysql_fetch_assoc() & mysql_fetch_array()) that moves the internal data pointer ahead after the using mysql_fetch_assoc(). So when you do mysql_fetch_array() you will get every row except the 1st row.
//Get payroll transactions
...
$row_pay = mysql_fetch_assoc($rs_pay);
//Get payroll detail recordset
...
while($row_pay = mysql_fetch_array($rs_pay))
{
...
$row_pay_det2 = mysql_fetch_assoc($rs_pay_det2);
while($row_pay_det2 = mysql_fetch_array($rs_pay_det2))
{
...
}
}
}
You need to remove - $row_pay = mysql_fetch_assoc($rs_pay); & $row_pay_det2 = mysql_fetch_assoc($rs_pay_det2);