Get all messages from array - php - php

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

Related

Query data laravel

I want to know how get this working in laravel:
I have two tables: "orders" and "delivery_boys".
When an order is created I want to get "id" in table "delivery_boys" that correspond to the "store_id" in the "order" table.
which looks like that in mysql
SELECT `id` FROM `delivery_boys` WHERE store_id = '3'
Thanks for your help.
I use this function:
protected $table = 'orders';
public function addNew($data)
{
$user = AppUser::find($data['user_id']);
if(isset($data['address']) && $data['address'] > 0)
{
$address = Address::find($data['address']);
}
else
{
$address = new Address;
}
$add = new Order;
$add->user_id = $data['user_id'];
$add->store_id = $this->getStore($data['cart_no']);
$add->d_boy = $add->?????; <---- here i want to add from "delivery_boys" table the "id" that correspond to the "store_id" added just above from the "order" table ---->
$add->name = $user->name;
$add->email = $user->email;
$add->phone = $user->phone;
$add->address = $address->address;
$add->lat = $address->lat;
$add->lng = $address->lng;
$add->address = $address->address;
$add->d_charges = $this->getTotal($data['cart_no'])['d_charges'];
$add->discount = $this->getTotal($data['cart_no'])['discount'];
$add->total = $this->getTotal($data['cart_no'])['total'];
$add->payment_method = $data['payment'];
$add->payment_id = isset($data['payment_id']) ? $data['payment_id'] : 0;
$add->type = isset($data['otype']) ? $data['otype'] : 1;
$add->notes = isset($data['notes']) ? $data['notes'] : null;
$add->save();
run this before $add = new Order;
$d_boy = DB::table('delivery_boys')
->select('id')
->where('store_id', $this->getStore($data['cart_no']))
->first();
and then add it where you need it:
$add->d_boy = $d_boy->id;
$id= DB::table('delivery_boys')->select('id')->where('store_id', '=', $this->getStore($data['cart_no']))->get();

adding database query in XLS

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

Can I retrieve data from a table in laravel with multiple array conditions?

I am trying to dynamic populate the report based the values select in dropdown.
For the same, I need to retrieve one or more columns from table using laravel 5.2. I am getting error "Trying to get property of non-object"
class ReportController extends Controller
{
public function index()
{
$apartmentNumber = Report:: lists('apartment_number','id')->all();
$commonArea = Report:: lists('common_area_name','id')->all();
$createdDate = Report:: lists('created_date_time','id')->all();
$status = Report:: lists('status','id')->all();
$priority = Report:: lists('priority','id')->all();
$assign = Report:: lists('assign_to','id')->all();
$reportDatas=Report::all();
return view('Report.index', compact('apartmentNumber','commonArea','createdDate','status','priority','assign','reportDatas','report'));
}
public function storeData(Request $request)
{
$report = new Report();
$report1 = $request->input();
$report->id = trim($report1['apartment_number']);
$aptNumber = Report::find($report->id)->apartment_number;
$report->id = trim($report1['common_area_name']);
$commonAreaName = Report::find($report->id)->common_area_name;
$report->id = trim($report1['created_date_time']);
$createdDateTime = Report::find($report->id)->created_date_time;
$report->id = trim($report1['status']);
$status1 = Report::find($report->id)->status;
$report->id = trim($report1['priority']);
$priority1 = Report::find($report->id)->priority;
$report->id = trim($report1['assign']);
$assign1 = Report::find($report->id)->assign_to;
$apartmentNumber = Report:: lists('apartment_number','id')->all();
$commonArea = Report:: lists('common_area_name','id')->all();
$createdDate = Report:: lists('created_date_time','id')->all();
$status = Report:: lists('status','id')->all();
$priority = Report:: lists('priority','id')->all();
$assign = Report:: lists('assign_to','id')->all();
$reportDatas=Report::where('apartment_number', '=',$aptNumber)
->where('common_area_name', 'like' , $commonAreaName)
->where('created_date_time', '=' , $createdDateTime)
->where('status', 'like' , $status1)
->where('priority', 'like' , $priority1)
->where('assign_to', 'like' , $assign1)
->get();
return view('Report.index', compact('apartmentNumber','commonArea','createdDate','status','priority','assign','reportDatas','report'));
}
}

Codeigniter foreach Undefined variable

I want to calculate hargaLama and hargaBaru, then insert it into database. To do so, I retrieve hargaLama from a view in mysql to my controller while hargaBaru is a user input. Even though I'm using foreach I got Undefined variable hargaLama and I also got error
Unknown column 'kodeProduksi' in 'field list'.
Here's my controller:
public function proses_tambahBarang(){
$kode = $_POST['kode'];
$kodeProduksi = $_POST['kodeProduksi'];
$nama = $_POST['nama'];
$tipe = $_POST['tipe'];
$ukuran = $_POST['ukuran'];
$merk = $_POST['merk'];
$satuan = $_POST['satuan'];
$jumlah = $_POST['jumlah'];
$harga = $_POST['hargaSatuan'];
// echo "proses_tambahBarang";
$data_insert = array(
'kodeBarang' => $kode,
'kodeProduksi' => $kodeProduksi,
'namaBarang' => $nama,
'tipeBarang' => $tipe,
'ukuran' => $ukuran,
'merk' => $merk,
'satuan' => $satuan,
'jumlah' => $jumlah,
'hargaSatuan' => $harga,
'keterangan' => 'n/a',
'idUser' => $this->session->userdata('username'),
'waktuMasuk' => 'n/a',
'waktuEdit' => 'n/a'
);
//$cek = $this->mhome->Barang("where kodeBarang = $data_insert[kodeBarang]");
// if($cek >= 1)
// {
$cek = $this->mhome->BarangHistory("where kodeProduksi = '$data_insert[kodeProduksi]'");
// $cek = $this->db->get_where('baranghistory',array('kodeProduksi' =>$data_insert['kodeProduksi']));
if($cek >= 1);
{
$query = $this->mhome->TableSelect('listBarang',"where kodeProduksi = '$data_insert[kodeProduksi]'");
foreach ($query as $row) {
$hargaLama = $row[0]['hargaSatuan'];
$jumlahLama = $row[0]['jumlah'];
}
$hargaBaru = $data_insert['hargaSatuan'];
$jumlahBaru = $data_insert['jumlah'];
$jumlahBaru = $jumlahBaru + $jumlahLama;
$data_insert['jumlah'] = $jumlahBaru;
$data_insert['waktuEdit'] = date("Y-m-d h:i:sa");
$data_insert['keterangan'] = "Updated";
$this->mhome->UpdateData('baranghistory',$data_insert,array("kodeProduksi" => $data_insert['kodeProduksi']));
$this->mhome->UpdateData('barang',$data_insert,array("kodeBarang" => $data_insert['kodeBarang']));
}
// $this->mhome->hitungHargaSatuan("where kodeBarang = '$data_insert[kodeBarang]'");
$hitung = $this->mhome->hitungHargaSatuan($data_insert['kodeBarang']);
if($hitung){
$this->session->set_flashdata('pesan','Tambah Barang Sukses');
redirect('userhome/index');
}
if($cek == 0) {
$data_insert['waktuMasuk'] = date("Y-m-d h:i:sa");
$data_insert['keterangan'] = "Baru";
$res = $this->mhome->InsertData('barang',$data_insert);
$res2 = $this->mhome->InsertData('baranghistory',$data_insert);
}
if($res >= 1 && $res2 >=1)
{
$this->session->set_flashdata('pesan','Tambah Barang Sukses');
redirect('userhome/index');
}
else {
echo "Tambah barang gagal";
}
}
And here's my model:
public function TableSelect($table,$where="")
{
$stmt = $this->db->query('select * from '.$table.' '.$where);
return $stmt->result_array();
}
I am sure you need not to put 0 here
foreach ($query as $row) {
$hargaLama = $row['hargaSatuan'];//remove [0] from here
$jumlahLama = $row['jumlah'];//remove [0] from here
}
like this.you need to use count on codition because this is returned array.and use result_array() for getting result in array format.
$cek = $this->mhome->BarangHistory("where kodeProduksi = $data_insert['kodeProduksi']")->result_array();
// $cek = $this->db->get_where('baranghistory',array('kodeProduksi' =>$data_insert['kodeProduksi']))->result_array();
if(count($cek) >= 1);
{
$query = $this->mhome->TableSelect('listBarang',"where kodeProduksi = $data_insert['kodeProduksi']");
foreach ($query as $row) {
$hargaLama = $row['hargaSatuan'];
$jumlahLama = $row['jumlah'];
}

PHP get the results of a function into another

I have this function
function getTwitterAuth($user_id) {
$d = "SELECT * FROM `twitterAccounts` WHERE `user_id`='".$user_id."'";
$dr=mysql_query($d) or die("Error selecting twitter account: ".mysql_error());
$drow = mysql_fetch_assoc($dr);
**$twitter_auth_token** = $drow['oauth_token'];
**$twitter_auth_secret** = $drow['oauth_token_secret']
}
It will tell me the result of two variables that I will need to pass then to this other function:
function twitterReply($twitter_message, $reply_to_id) {
$twitterObj->setToken(**$twitter_auth_token**, **$twitter_auth_secret**);
$twitter_user = $twitterObj->get_accountVerify_credentials();
try{
$twitter_user->id;
$twitterObj->post_statusesUpdate(array("status" => $message, "in_reply_to_status_id" => $reply_to_id);
//echo "done";
}
catch(EpiTwitterException $e){}
}
How do I do it??
Thank you very much
function getTwitterAuth($user_id) {
$d = "SELECT * FROM `twitterAccounts` WHERE `user_id`='".$user_id."'";
$dr=mysql_query($d) or die("Error selecting twitter account: ".mysql_error());
$drow = mysql_fetch_assoc($dr);
$twitter_auth_token = $drow['oauth_token'];
$twitter_auth_secret = $drow['oauth_token_secret'];
return Array("token" => $twitter_auth_token, "secret" => $twitter_auth_secret);
}
function twitterReply($twitter_auth_token, $twitter_auth_secret, $twitter_message, $reply_to_id) {
$twitterObj->setToken($twitter_auth_token, $twitter_auth_secret);
$twitter_user = $twitterObj->get_accountVerify_credentials();
try{
$twitter_user->id;
$twitterObj->post_statusesUpdate(array("status" => $message, "in_reply_to_status_id" => $reply_to_id);
//echo "done";
}
catch(EpiTwitterException $e){}
}
$res = getTwitterAuth($user_id);
twitterReply($res["token"], $res["secret"], $twitter_message, $reply_to_id);
Edit: As seen in another answer setting the $twitter_auth_token and $twitter_auth_secret is redundant the last three lines of the function getTwitterAuth could be appended to:
return Array("token" => $drow['oauth_token'], "secret" => $drow['oauth_token_secret']);
function getTwitterAuth($user_id) {
$d = "SELECT * FROM `twitterAccounts` WHERE `user_id`='".$user_id."'";
$dr=mysql_query($d) or die("Error selecting twitter account: ".mysql_error());
$drow = mysql_fetch_assoc($dr);
$array = array();
$array['twitter_auth_token'] = $drow['oauth_token'];
$array['twitter_auth_secret'] = $drow['oauth_token_secret'];
return $array
}
$twitterTokens = getTwitterAuth($user_id);
Now you can access those values using $twitterTokens['twitter_auth_token'] and $twitterTokens['twitter_auth_secret']
AS the above peope have said,
function getTwitterAuth($user_id) {
....
**$twitter['auth_token']** = $drow['oauth_token'];
**$twitter['auth_secret']** = $drow['oauth_token_secret'];
return($twitter);
}
function twitterReply($twitter,$twitter_message, $reply_to_id) {
$twitterObj->setToken(**$twitter['auth_token']**, **$twitter['auth_secret']**);
...
}
$twitter_info = getTwitterAuth($user_id);
twitterReply($twitter_info, $twitter_message, $reply_to_id)

Categories