How do i change the format of an SQL output? - php

I am using Laravel 5.5, and when I am trying to export data from another DB, i use:
$fname = DB::connection('smallplanet')->table('pilots')->where('id', Auth::user()->id)->get(['fname']);
echo $fname;
and this is the output:
[{"fname":"Aidas1"}]
how do i change the output to just "Aidas1"?

Its JSON ,try this:
$output = json_decode($fname,true);
echo $output[0]["fname"];
//********* OR **********
foreach($output as $row)
echo $row["fname"];

Couldn't it be easier to change the source instead of the result ?
For one pilot
$pilot = DB::connection('smallplanet')->table('pilots')->find(Auth::user()->id);
if($pilot){
echo $pilot->fname;
}else{
echo "pilot not found";
}
For many pilots
$pilots = DB::connection('smallplanet')->table('pilots')->where('your_field', $value)->get();
foreach($pilots as $pilot){
echo $pilot->fname . PHP_EOL;
}

Related

I am unsure what kind of loop to use in php

I am newer to PHP and I am able to get the desired output but I am doing it one index position at a time. I am returning data from a .txt file and I need to insert this data into an HTML table I am creating using PHP. BUT FIRST I need to be able to get the same output without typing out every index position. I tried to use a forloop but it kept outputting only one line.
I manually outputted the lines from the file and it works. What loop in PHP would be best to achieve the same results and output these elements? IMPORTANT, as is I am able to sort and rsort (I want to be able to do this so if it can be implemented in the loop that would be awesome) any help is more than I have right now.
PHP
$books = array();
if ($fp)
{
while(true)
{
$lines_in_file = count(file($filename));
$line = fgets($fp);
if (feof($fp))
{
break;
}
$line_ctr++;
list($title, $author, $pubdate, $isbn) = explode('*', $line);
$new_line = explode('*', $line);
for($ii= 1; $ii <= $lines_in_file; $ii++){
$lines = fgets($fp); //Read each line
$member = trim($lines);
array_push($books, $member);
}
//This foreach only brings back the first like in the txt file, why?
$cntr = 0;
foreach($books as $element){
$cntr++;
$table .= "<tr>";
$table .= "<td>".$title."</td>";
$table .= "<td>".$author."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$isbn."</td>";
$table .= "</tr>\n"; //added newline
echo $element;
}
//sort($books);
// rsort($books);
echo $books[0];
echo "<br>";
echo $books[1];
echo "<br>";
echo $books[2];
echo "<br>";
echo $books[3];
echo "<br>";
echo $books[4];
echo "<br>";
echo $books[5];
echo "<br>";
echo $books[6];
echo "<br>";
echo $books[7];
echo "<br>";
echo $books[8];
echo "<br>";
echo $books[9];
echo "<br>";
echo $books[10];
echo "<br>";
echo $books[11];
echo "<br>";
echo $books[12];
echo "<br>";
echo $books[13];
echo "<br>";
echo $books[14];
echo "<br>";
echo $books[15];
echo "<br>";
echo $books[16];
echo "<br>";
echo $books[17];
}//END WHILE LOOP
fclose($fp ); //Close file
}
Having to make a few guesses here but i believe the file is going to look like:
title*author*pubdate*isbn
title*author*pubdate*isbn
title*author*pubdate*isb
if this is wrong, let me know
as long as the fie is not to large read it in to an array:
$book_array=file('book_file.txt');
//print_r($book_array); //is it an array of the books, one book per array key
now to separate each line:
foreach($book_array as $line){
$line_sep=explode('*',$line);
// with no sorting option you could just echo inside the loop
//if you want to keep sorting options we have to keep the separated lines
$new_book_array[]=$line_sep;
}
unset($book_array);//free up memory if needed
//print_r($new_book_array);//is it a multi-d array, book then the 4 elements
to sort our new multidimensoanl array:
usort($new_book_array, function($a, $b) {
return strcmp($a['0'], $b['0']);;
}); //this sorts on key 0 in your case title:
//print_r($new_book_array); // has it sorted properly
for display:
loop again
echo '<table><tr><th>Title</th><th>Author</th><th>Pub Date</th><th>ISBN</th></tr>';
foreach($new_book_array as $book){
//print_r($book); //is it each indervidual book array with 4 elements
echo '<tr><td>'.$book[0].'</td><td>'.$book[1].'</td><td>'.$book[2].'</td><td>'.$book[3].'</td></tr>';
}
echo '</table>';

How to print jSON values with loop

I am using the following code to print the output of the jSON response but when I try to print
echo $obj->HotelListResponse->customerSessionId; // This is working.
echo $obj->HotelListResponse->HotelList->HotelSummary->name; // This is not working.
When the response contains only one node then its printing perfectly but when there are multiple nodes with same name then its not printing. I tried using foreach just like the below. I also tried using while loop but still I am unable to print the list of hotel names.
My jSON decoded output is like http://pastebin.com/Fr21DkEk
Total code:
$url = "https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55505&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_AU&currencyCode=AUD&xml=<HotelListRequest><city>Brisbane</city><stateProvinceCode>QLD</stateProvinceCode><countryCode>AU</countryCode><arrivalDate>10/16/2014</arrivalDate><departureDate>10/18/2014</departureDate><RoomGroup><Room><numberOfAdults>2</numberOfAdults></Room></RoomGroup><numberOfResults>25</numberOfResults></HotelListRequest>";
$json = file_get_contents($url);
$obj = json_decode($json);
foreach($obj as $val) {
echo $val->HotelListResponse->HotelList->HotelSummary->name;
}
Try this
foreach($obj->HotelListResponse->HotelList->HotelSummary as $val) {
echo $val->name . '<br/>';
}
HotelSummary is an array:
echo $val->HotelListResponse->HotelList->HotelSummary[0]->name;
If you want all of the hotel summaries:
foreach($obj as $val) {
foreach($val->HotelListResponse->HotelList->HotelSummary as $sum) {
echo $sum->name;
}
}
Yes you can directly access them inside the foreach. Like this:
foreach($obj->HotelListResponse->HotelList->HotelSummary as $val) {
// ^^
// since you're interested on just names, you can point it directly on that object, then each of that batch is in `$val`
echo $val->name . '<br/>';
}
// or start from the parent
foreach($obj as $values) {
$customerSessionId = $values->customerSessionId;
echo $customerSessionId . '<hr/>';
$hotelList = $values->HotelList;
foreach($hotelList->HotelSummary as $hotelsummary) {
echo $hotelsummary->name . '<br/>';
}
}

PHP Concatenation for displaying from the db

How do I make this line of code work?
echo $row['Headings'.' '.'Contents']; //
I want to display what's in the 'Headings' column from the database, then a page break, then what's in the 'Contents' column in the db. Please help.
Try this
echo $row['Headings'] .'<br />'. $row['Contents'];
echo $row['headings'] . '&nbsp' . $row['contents'];
Should do the trick.
You can use it as :
$result = mysql_query('select concat(Headings, Contents) as final_string from table_name');
while ($row = mysql_fetch_assoc($result)){
echo $row['final_string'];
}
Please correct me if I am wrong.
Set glue
$glue = "<br />"; // or even what you want
Store it in one variable
$variable = $row['Headings'];
$variable .= $glue;
$variable .= $row['Contents'];
== OR implode by Array ==
$variable = implode($glue, Array($row['Headings'], $row['Contents']));
And then display
echo $variable;
Just do
echo "{$row['Headings']}<br />{$row['Contents']}";
Or the way I should do it
$headings = $row['Headings'];
$contents = $row['Contents'];
echo $headings.'<br />'.$contents
Try this way :
echo $row['Headings'];
echo '<br />';
echo $row['Contents'];

How to store data in xml?

I have one php file in which i am displaying data of xml file by this code
<?php
$xml = simplexml_load_file("note.xml") or die("Error: Cannot create object");
foreach($xml->xpath('//agent') as $item) {
$row = simplexml_load_string($item->asXML());
$v = $row->xpath('//id[. ="1"]');
if($v[0]){
print $item->id;
print $item->image;
print $item->name;
print $item->company;
print $item->street;
print $item->city;
print $item->phone;
}
else{
echo 'No records';
}
?>
Now i want to store this displayed data into other pages of my site and i am begginer of php so not expert in session.
and i want to store this detail in session for displaying this data into other pages of my site. for storing this data into session i have tried this code on same page
<?php
session_start();
$name = $_session_['$item->name'];
?>
But thats not help, So please guys can you suggest me where i am wrong.
any suggestion should be appreciable.
Start ur session in first doc.
<?php
session_start();
$xml = simplexml_load_file("note.xml") or die("Error: Cannot create object");
foreach($xml->xpath('//agent') as $item) {
$row = simplexml_load_string($item->asXML());
$v = $row->xpath('//id[. ="1"]');
if($v[0]){
print $item->id;
print $item->image;
print $item->name;
print $item->company;
print $item->street;
print $item->city;
print $item->phone;
}
else{
echo 'No records';
}
$name = $_session['name'][$item->name]; // dont quote ''
?>
http://www.w3schools.com/php/php_sessions.asp
your session code is not valid, you may try this one ;
$name = $_session['name'][$item->name];

$string is not showing up in php search

Just got some help with my ajax/php search but now my issue is that the link is not even showing up on the search page. The echo results are showing up but the $string isn't.
Thanks for the help.
//echo $query;
$result = mysqli_query($link, $query);
$string = '';
if($result){
if(mysqli_affected_rows($link)!=0){
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
echo '<p> <b>'.$row['title'].'</b> '.$row['post_ID'].'</p>' ;
$string .= "<p><a href='set-detail.php?recordID=".$row['post_ID']."'>".$row['title']."</a></p>";
}
} else {
echo 'No Results for :"'.$_GET['keyword'].'"';
}
I don't see where you echo $string. If you put the echo command in there for $string it may begin to work.
You're not printing $string anywhere.
Are you sure you meant to use $string, and not just echo it, like you have with the line above?
You need to include echo $string; or simple echo the line as it is generated if you are calling this inline i.e.
echo "<p><a href='set-detail.php?recordID=".$row['post_ID']."'>".$row['title']."</a></p>";
You do not echo the string above.
After your loop you need to echo it.
if(mysqli_affected_rows($link)!=0){
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo '<p> <b>'.$row['title'].'</b> '.$row['post_ID'].'</p>' ;
$string .= "<p><a href='set-detail.php?recordID=".$row['post_ID']."'>".$row['title']."</a></p>";
}
echo $string;

Categories