How to get data from a database using a loop? - arrays

In my database I've got different username: "fabio97", "antonino", "lauretta". I want to get them from DB to have an array like this:
$dati = array("str"=>array("n1"=>"fabio97", "n2"=>"antonino", "n3"=>"lauretta"));
is it correct write:
...
"str" => array("n".$i=>"Ti sei incrociato con ".$array_db[username]),
...
into a loop
...
$i = 0;
$array_user = mysql_fetch_array($query);
while ($array_db = mysql_fetch_array ($query_db)) {
...
if ($array_user[square] == $array_db[square]) {
$dati = array(
"data" => array(
'address_complete'=>$data->results[0]->formatted_address,
'address_square'=>$data->results[0]->address_components[1]->long_name,
'location'=>$data->results[0]->address_components[2]->long_name,
'postal_code'=>$data->results[0]->address_components[7]->long_name,
'data_ora'=>$tmp_date
),
"str" => array("n".$i=>"Ti sei incrociato con ".$array_db[username]),
"index" => $i
);
$i++;
}
}
and to call them with Ajax:
... success:function(msg){
if(msg){
$("#location").html(Object.keys(msg.str).map(x => msg.str[x]).join(", "));
}else{
$("#location").html('Not Available');
}

Related

How to pass multi-dimensional arrays through url as query parameters? and access these parameters in laravel 6.0

I am trying to pass a multi-dimensional array as a query parameter in the below URL:
{{serverURL}}/api/v1/classes?with[]=section.courseteacher&addl_slug_params[0][0]=test&addl_slug_params[0][1]=test1&addl_slug_params[0][2]=test0
what is wrong with the above URL?
My code to access these parameters in Laravel 6.0 is below:
$addl_slug_params = $request->query('addl_slug_params');
$i=0;
foreach ($addl_slug_params as $s) {
$j=0;
foreach($s as $asp) {
print_r('addl_slug_params : ('.$i.':'.$j.') : '.$asp); die();
$j=$j+1;
}
$i = $i+1;
}
Result:
addl_slug_params : (0:0) : test
Problem: test1 and test0 are not accessible..
What should I do?
The problem is the die(); after printr(), the loop will run once, aka only addl_slug_params : (0:0) : test
To help you visualize it better, I added an extra break after each loop:
foreach ($addl_slug_params as $s) {
$j=0;
foreach($s as $asp) {
echo('addl_slug_params : ('.$i.':'.$j.') : '.$asp);
echo nl2br(PHP_EOL);
$j=$j+1;
}
$i = $i+1;
}
Will result in the following:
addl_slug_params : (0:0) : test
addl_slug_params : (0:1) : test1
addl_slug_params : (0:2) : test0
here is a solution for multi-dimensional arrays. Developed in 2~ hours, definitely needs improvement but hopefully helps you out :)
Route::get('example', function (\Illuminate\Http\Request $request) {
$addl_slug_params = [
[
1 => [
'title' => 'Test 1',
'slug' => 'test1'
],
2 => [
'title' => 'Test 2',
'slug' => 'test2'
],
3 => [
'title' => 'Test 3',
'slug' => 'test3'
],
],
];
// Encode
$prepend = 'addl_slug_params';
$query = "?$prepend";
$tempSlugs = $addl_slug_params[0];
$lastIndex = count($tempSlugs);
foreach ($addl_slug_params as $pIndex => $params) {
foreach ($params as $sIndex => $slugData) {
$tempQuery = [];
foreach ($slugData as $sdIndex => $data) {
// Replace '-' or ' -' with ''
$encodedString = preg_replace('#[ -]+#', '-', $data);
// title = test1
$tempString = "$sdIndex=$encodedString";
$tempQuery[] = $tempString;
}
$dataQuery = implode(',', $tempQuery);
$appendStr = ($sIndex !== $lastIndex) ? "&$prepend" : '';
// Set the multidimensional structure here
$query .= "[$pIndex][$sIndex]=[$dataQuery]$appendStr";
}
}
// DECODE
// ?addl_slug_params[0][1]=[title=Test-1,slug=test1]&addl_slug_params[0][2]=[title=Test-2,slug=test2]&addl_slug_params[0][3]=[title=Test-3,slug=test3]
$slugParams = $request->query('addl_slug_params');
$slugParamData = [];
foreach ($slugParams as $slugItems) {
foreach ($slugItems as $slugItem) {
// Replace [title=test,slug=test1] into 'title=test,slug=test1' and explode
// into into an array, and split title=test into [title => test]
$splitArray = explode(',', (str_replace(array('[', ']'), '', $slugItem)));
$slugItemData = [];
foreach ($splitArray as $value) {
$data = explode('=', $value);
$slugItemData[$data[0]] = $data[1];
}
$slugParamData[] = $slugItemData;
}
}
dd($slugParamData);
});
I have solved the problem using associative arrays as it gives more flexibility and Garrett's solution definitely helped
new url: {{serverURL}}/api/v1/classes?with[]=section.courseteacher&addl[users][params]=name
laravel code:
`
foreach ($addl_data_array as $addl_slug => $addl_slug_data) {
foreach ($addl_slug_data as $key => $value) {
$params = null;
$where_raw = null;
$where_has = null;
$with_relationships = null;
$with_timestamps = null;
}
}
`

controller store function array laravel 5.5

I need some help. I have a problem with store function with array in laravel. When I submit my form, I got error massage that "ksort() expects parameter 1 to be array, string given".
This is my store function :
public function store(request $request) {
$input=$request->all();
$images=array();
$total = count($request->path_scan_ijazah);
// return $total;
if($files=$request->file('path_scan_ijazah')){
for ($i=0; $i < $total; $i++) {
$nip[] = $request->nip;
$instansi[] = $request['nama_instansi_pendidikan'][$i];
$jurusan[] = $request['nama_jurusan'][$i];
$jenjang[] = $request['jenjang_pendidikan'][$i];
$gelar[] = $request['gelar'][$i];
$thn_masuk = $request['tahun_masuk'][$i];
$thn_lulus = $request['tahun_lulus'][$i];
$path = $request['path_scan_ijazah'][$i]->store('public/upload/ijazah');
$images[] = $path;
$data[] = Education::insert([
'nip_employee' => $nip,
'nama_instansi_pendidikan' => $instansi,
'nama_jurusan' => $jurusan,
'jenjang_pendidikan' => $jenjang,
'gelar' => $gelar,
'tahun_masuk' => $thn_masuk,
'tahun_lulus' => $thn_lulus,
'path_scan_ijazah' => $images
]);
}
// dd($data);
}
Please help me, what should I do?

Rendering view for DOMPDF in phalconPHP

I have been try to convert template to PDF with DOMPDF in phalconPHP with angularJS at the front. But I am getting 500 internal server error response from it. DOMPDF is included fine in the controller as I loaded static HTML in load_html() function, it worked fine. Below is the report action from ReportsController. Don't bother with the whole code and just skip to the DOMPDF related code at the end. And $patients is the array that contains all the data which the template is going to need.
ReportController's reportAction:
public function reportAction()
{
$patientsModel = new Patients();
$patients = array();
$patients['data'] = array();
$tmpfilters = $this->queryfilters;
unset($tmpfilters['limit']);
$tmpfilters2 = array();
$tmpfilters2['models'] = "PRM\\Models\\Patients";
if( isset( $tmpfilters['conditions'] ) )
{
$tmpCondition = preg_replace("/[^0-9]/", '', $tmpfilters['conditions']);
$tmpfilters2['conditions'] = "clinic = " . $tmpCondition . " AND status = 24";
}
else
{
$tmpfilters2['conditions'] = "status = 24";
}
$tmpActivePatients = new Patients();
$tmpActivePatients = $tmpActivePatients->find($tmpfilters2);
$patients['activeTotal'] = $tmpActivePatients->count();
$tmpfilters3 = array();
$tmpfilters3['models']['m'] = "PRM\\Models\\Activity";
$tmpfilters3['models']['s'] = "PRM\\Models\\Patients";
if( isset( $tmpfilters['conditions'] ) )
{
$tmpCondition2 = preg_replace("/[^0-9]/", '', $tmpfilters['conditions']);
$tmpfilters3['conditions'] = "m.clinic = " . $tmpCondition2 . " AND " . "s.clinic = " . $tmpCondition2 . " AND m.patient=s.id AND m.duration > 1";
}
else
{
$tmpfilters3['conditions'] = "m.patient = s.id AND m.duration > 1";
}
$tmpPatientDuration = new Query($tmpfilters3);
$tmpPatientDuration = $tmpPatientDuration->getQuery()->execute();
//$builder = $this->modelsManager->createBuilder();
$patients['billableTotal'] = $tmpPatientDuration->count();
//$builder->addFrom('PRM\\Models\\Activity', 'a')->innerJoin('PRM\\Models\\Patients', 'p.id=a.patient', 'p')->where('a.duration > 1 AND p.status = 24');
//$result = $builder->getQuery()->execute();
//$patients['billableTotal'] = $result->count();
foreach ($tmpPatientDuration as $patient) {
array_push($patients['data'], array(
'id' => $patient->id,
'firstname' => $patient->s->firstname,
'lastname' => $patient->s->lastname,
'duration' => $patient->m->duration,
'billingCode' => "CPT 99490"));
/*'icd1' => Ccm::findFirstById($patient->icd1)->icdcode,
//'icd2' => Ccm::findFirstById($patient->icd2)->icdcode,
//'clinic' => Clinics::findFirstById($patient->clinic)->name,
'duration' => Activity::sum([
"column" => "duration",
"conditions" => "patient = '{$patient->id}'",
]),
'response' => Activity::findFirst([
"conditions" => "patient = '{$patient->id}' and activity='Communication' ",
"order" => "id desc"
])->description,
'status' => Status::findFirstById($patient->status)->name));*/
}
$html = $this->view->getRender("reports", "report", $patients);
$dompdf = new domPdf();
$dompdf->load_html($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
//$this->response->setJsonContent($patients);
$this->response->setContentType('application/pdf');
$this->response->setContent($dompdf->stream());
$this->response->send();
}
Here is the angularJS controller's code:
$http.get('common/reports/report', {responseType: 'arraybuffer'}).success(
function (data) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}).error(
function (data) {
angular.forEach(data, function (error) {
$scope.error[error.field] = error.message;
console.log(error.field);
});
$alert({title: 'Error!', content: data.flash.message, placement: 'top-right', type: data.flash.class , duration: 10, container: '.site-alert'});
}
);
error logs:
error log for the above problem

Persisting data to database. persist not working

I wrote a controller action that is supposed to add an element (meeting) to the database here it is:
public function newAction(Request $request){
$meeting = new Meeting();
$meetingUser = new MeetingUser();
$project = new Project();
$projectName = "SocialPro";//$request->get('projectName');
echo($projectName);
$users = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findProjectUser($projectName);
//$form = $this->createForm('SocialPro\MeetingBundle\Form\MeetingType', $meeting);
//$form->handleRequest($request);
//if ($form->isSubmitted() && $form->isValid()) {
$userconn = $this->container->get('security.token_storage')->getToken()->getUser();
echo($userconn->getId());
if ($request->isMethod('POST')) {
echo("message form");
$role = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findUserRole($userconn)[0]['role'];
$date = $request->get('date');
if ($role == "PROJECT_MASTER" || $role == "TEAM_MASTER") {
for ($i = 0; $i < count($users); $i++) {
$meetings = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findMeetingUser($users[$i]['id'], $date);
}
if ($meetings == null || count($meetings) == 0) {
$project = $this->getDoctrine()->getRepository('SocialProProjectBundle:Project')->findBy(array("name" = >$projectName));
$meeting->setDescription($request->get('description'));
$meeting->setDate(new \DateTime($request->get('date')));
$meeting->setTime($request->get('time'));
$meeting->setProjectName($request->get('projectName'));
$meeting->setProject($project[0]);
$meetingUser->setMeetings($meeting);
$meetingUser->setUsers($userconn);
var_dump($meetingUser);
$meeting->setMeetingUser(array($meetingUser));
//$project->setMeetings($meeting->getId());
$em = $this->getDoctrine()->getManager();
$em->persist($meeting);
$em->persist($meetingUser);
$em->flush();
// $meetingUser->setUsers($request->get(''));
return $this->redirectToRoute('reunion_show', array('id' = > $meeting->getId()));
}
else {
echo("Membre indisponible");
}
}
else {
echo("Must be MASTER to create meeting");
}
}
return $this->render('SocialProMeetingBundle::ajoutMeeting.html.twig', array('users' = >$users));
// $em = $this->getDoctrine()->getManager();
//$em->persist($meeting);
//$em->flush($meeting);
// return $this->redirectToRoute('meeting_show', array('id' => $meeting->getId()));
//}
//return $this->render('SocialProMeetingBundle:ajouMeeting', array(
// 'meeting' => $meeting,
//'form' => $form->createView(),
//));
}
When I submit the form it gives me a site not available page. I tested it line by line and everything is working perfectly. Turns out the problem is in the
$em->persist($meeting);
And I have no idea how to fix it.
You must call flush immediately after calling persist like so:
$em->persist( $meeting );
$em->flush();
$em->persist( $meetingUser );
$em->flush();
Then it will persist both.

Array output value is null on separating string value using implode function by comma output displays in exta comma? how to solve it?

$drstring1 = stristr($drstring, 'DR', false);
//drupal_set_message($drstring1);
$drbrkstring = $drstring1;
$drval = explode('DR', $drbrkstring);
array_shift($drval);
$drdata_array = array();
foreach ($drval as $drv) {
$drdata = process_drstring('DR' . $drv);
$Colarray = array();
foreach ($drdata as $key => $value) {
array_push($Colarray, $key);
print 'key='. $key .' <br />';
}
$ColNames = implode(',' ,$Colarray);
print 'colunames=' .$ColNames.' <br />';
function process_drstring($string) {
$result = array();
$tag_text = array(
'DR' => 'segmenttag',
'01' => 'dateofentry',
'02' => 'dispute_remarks1',
'03' => 'dispute_remarks2',
'04' => 'dispute_remarks3',
'05' => 'dispute_remarks4',
'06' => 'dispute_remarks5',
'07' => 'dispute_remarks6',
);
$tag = substr($string, 0, 2);
$length = substr($string, 2, 2);
$data = substr($string, 4, $length);
$result[$tag_text[$tag]] = $data;
$newstring = substr($string, $length + 4, strlen($string));
if ($newstring) {
$newresult = process_drstring($newstring);
$result = array_merge($result, $newresult);
return $result;
}
else {
return $result;
}
}
output:
key=segmenttag
key=
key=dateofentry
key=dispute_remarks2
key=dispute_remarks1
key=dispute_remarks3
key=dispute_remarks4
key=dispute_remarks5
key=dispute_remarks6
colunames=segmenttag,,dateofentry,dispute_remarks2,dispute_remarks1,dispute_remarks3,dispute_remarks4,dispute_remarks5,dispute_remarks6
From this function , I need to get an columnames, but i'm receiving an extra key='' key element.
getting extra key value. Key='' it should not appear. Please help me solve this problem.

Resources