Trim locale result from Facebook Graph API - php

I am using the Facebook Graph API to get the users locale information (updated code):
[more code]
<div id="scoreboard-overview">
<ul>';
$num_rows = mysql_num_rows($resulttt);
$i = 0;
while($row = mysql_fetch_array($resulttt)) {
$i = $i + 1;
$fb_data = json_decode(file_get_contents('http://graph.facebook.com/'. $row['fbID']));
$fb_locale_str = $fb_data->locale;
$fb_name_str = $fb_data->first_name;
$fb_country_str = strtolower(substr($fb_locale_str, -2));
$flag_uri = '/flags/unknown.gif'; //display a general flag if unknown.
if (!empty($fb_country_str) && in_array($fb_country_str, $valid_flags) )
$flag_uri = '/flags/' . $fb_country_str . '.gif';
echo '<li>
<div class="container">
<div class="black">
<img src="https://graph.facebook.com/'. $row['fbID'] .'/picture" alt="" />
</div>
<div class="grey">
'.$i.' '.$fb_name_str.'';
printf ('<div class="test"><img src="%s" /></div>', $flag_uri);
echo ' </div>
<div class="holder">
<div class="blue">
<p>0<br />'. $row['Time'] .'</p>
</div>
<div class="red">
<img src="http://ep2.nl/images/star.gif" alt="" />
</div>
<div class="yellow">
<p>'. $row['Score'] .'</p>
</div>
</div>
</div>
</li>';
}
echo '</ul>
</div>
[more code]
$row['fbID'] is the users and/or friends Facebook ID (used in a array)
Well this gives a result like: en_US where en is the users language and US is the users country. The country is where I am after.
I have a couple of flag images that look like this: us.png. These flags are named using the ISO3166-1 alpha-2 country codes where appropriate. So I want to trim this en_US to us and put .png behind it so I can show the flag image. But how to do this?
Also a general flag if the locale returns nothing like unknown.png would be nice.
Many thanks,
Maurice

Not too hard to do.
Try this:
$valid_flags = array ('us', 'ca', 'mx', '...') //You'll need to populate this one
$fb_data = json_decode(file_get_contents('http://graph.facebook.com/'. $row['fbID']);
$fb_locale_str = $fb_data->location;
$fb_country_str = strtolower(substr($fb_locale_str, -2));
$flag_uri = '/flags/unknown.png'; //display a general flag if unknown.
if (!empty($fb_country_str) && in_array($fb_country_str, $valid_flags) )
$flag_uri = '/flags/' . $fb_country_str . '.png';
printf ('<div class="grey"><img src="%s" /></div>', $flag_uri);
As a note, you shouldn't be calling file_get_contents inside of an echo statement.

Related

Javascript not working in PHP foreach?

I'm using this code to get a maximum of text in a p tag. For one reason this code only runs on the first card in my foreach but not on the second.
Here you see the problem: https://gyazo.com/c3ef858fb233b21b31098fb1682a7ce4
Here is my javascript code:
<script>
function truncateText(selector, maxLength) {
var element = document.querySelector(selector),
truncated = element.innerText;
if (truncated.length > maxLength) {
truncated = truncated.substr(0,maxLength) + '...';
}
return truncated;
}
</script>
[PHP CODE]
<?php
$stmt = $conn->prepare("SELECT naam, prijs, beschrijving, id, image1 FROM salontafels");
$stmt->execute([]);
$rows = $stmt->fetchAll();
foreach ($rows as $row) : { ?>
<a class="formtitellink" href="productsalontafels.php?rowid=<?= $row['id'] ?>">
<?php } echo '
<div class="col-lg-4 col-md-6 mb-4">
<div class="card h-100">
<img class="card-img-top" src="data:image/jpeg;base64,' . base64_encode( $row['image1'] ) . '" />
<div class="card-body">
<h4 class="card-title">
' . $row['naam'] . '</a>
</h4><script> document.querySelector(\'p\').innerText = truncateText(\'p\', 100);</script>
<h5> Log in voor de prijs </h5>
<p class="card-text">' . $row['beschrijving'] . '</p>
</div>
<div class="card-footer">
<small class="text-muted">beschikbaar</small>
</div>
<!-- /.row -->
</div>
<!-- /.col-lg-9 -->
</div>'?>
Does anyone knows what is wrong?
Your problem is that document.querySelector('p') returns the first Element within the document that matches the specified selector. So it just returns the first p tag every time it's run.
This means that these two lines are your problem:
document.querySelector(\'p\').innerText = truncateText(\'p\', 100)
and
var element = document.querySelector(selector)
To fix it, you will need to select the specific element you're interested in each time
[If you want working code, rather than an answer to your question, I suggest just using substr($row['beschrijving'],0,100)]

PHP while loop different images

Okay let me clarify everything.
Chars table looks like http://prntscr.com/9v8jiv .
Here is the standard html
<div id="characterone">
<h1 class="charactername">Test_Name</h1>
<p class="characterstats">DOB: 12/01/1992</p>
<p class="characterstats">Origin: Mexican</p>
<p class="characterstats">Time in Los Santos: 56</p>
<button class="choosebutton">Choose</button>
</div>
<div id="charactertwo">
<h1 class="charactername">Angelo_Damce</h1>
<p class="characterstats">DOB: 12/01/1992</p>
<p class="characterstats">Origin: American</p>
<p class="characterstats">Time in Los Santos: 26</p>
<button class="choosebutton">Choose</button>
</div>
<div id="characterthree">
<h1 class="charactername">Moemen_Walid</h1>
<p class="characterstats">DOB: 12/01/1992</p>
<p class="characterstats">Origin: American</p>
<p class="characterstats">Time in Los Santos: 26</p>
<button class="choosebutton">Choose</button>
</div>
All I want to do is, to select someone's logged in characters and then he sees the 3 in front of him and then he chooses,
I began by normaling querying them
$getchars = mysqli_query($con,"SELECT * FROM `characters` where Username = '".$user."'") or die('Error: ' . mysqli_error($con));
$check = mysqli_num_rows($getchars);
Now I need to find a way so for every char the mysql query find, to be echo'ed or written in the html up.
Eg: echo ''.$row[1]["Name"].' ';
but in each div there should be a different echo
'.$row[2]["Name"].'
^ But of course this code isn't real. just trying to explain.
Ok Here is the complete answer for your question. Just replace the Name and Time Column names with the correct Column names in the database.
$i = 1;
while($rowget = mysqli_fetch_array($getchars))
{
$id1 = 'characterone';
$id2 = 'charactertwo';
$id3 = 'characterthree';
if($i<4){
echo'<div id="'.${'id'.$i}.'">';
echo '<h1 class="charactername">'.$rowchar["Name"].'</h1>
<p class="characterstats">DOB: '.$rowchar["Birthdate"].'</p>
<p class="characterstats">Origin: '.$rowchar["Origin"].'</p>
<p class="characterstats">Time in Los Santos: '.$rowchar["Skin"].'</p>
<button class="choosebutton">Choose</button>';
echo '</div>';
}
$i++;
}
just use a counter
$i=1;
while($rowget = mysqli_fetch_array($getchars)) {
$charpost = $rowget["Character"];
echo' <img src=$i.png> ';
$i++;
}

Filtering Search Query with AngularJS and PHP

I have a music store type of application and I use php to get images and names of specific musical instruments from a database. I want to incorporate a search bar that dynamically filters the musical instruments, and I want to use AngularJS to do this. I'm having trouble after creating the $watch in AngularJS. I know how to filter using a JS object, but I am having trouble with this scenario.
I am assuming I could create a JS object from the innerHTML from the required elements. Then I could use an ng-repeat to filter through the object based on what is in the input search box. Is that a valid option? If so are there any other options available?
HTML/PHP
<div ng-controller="instController">
<div class="col-md-12" id="search-instrument-wrapper">
<input class="searchbar" type="text" ng-model="searchInst" placeholder="Search Instruments"/>
</div>
<?php foreach ($instruments as $singleInstrument) : ?>
<div class="col-md-4 instrument-wrapper">
<a href='instruments/<?php echo $singleInstrument; ?>.php#/'>
<span class="inst-thumbnail">
<img class="img-responsive instrument-images" src="images/<?php echo $singleInstrument; ?>"/>
</span>
</a>
<a href='instrument/<?php echo $singleInstrument ?>/<?php echo $singleInstrument ?>.php#/'>
<h3 class="instrumentName"><?php echo $instrumentInfo['instrumentName'];?></h3>
</a>
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>
AngularJS
instApp.controller('instController',['$scope', function($scope){
$scope.searchInst = '';
$scope.$watch('searchInst',function(newVal,oldVal){
/*** MY ATTEMPT ***/
if(!$( ".instrumentName:contains('"+newVal+"')" )){
$(this).parent().css( "display",
"none" );}
/******************/
});
}]);
I was able to figure it out doing it the way that was described in the comments:
The key is to post your data from the database into a foreach loop and concatenate a string to create a JSON object. Then use ng-init to initialize the JSON for the ng-repeat to use. Works for me
PHP
foreach($instrumentsArray as $instruments){
$jsonStatement .= '{
name:"' . $instrumentInfo['instrumentName'] . '"' .
',url: "user/' . $instruments . '/' . $instruments . '.php#/"'.
',img: "user/' . $instruments . '/images/' . $instrumentPicInfo['instrumentPic'] . '"},';
$jsonComplete = 'instruments = [' . $jsonStatement . ']';
HTML
<div ng-init='<?php echo $jsonComplete;?>'></div>
<div class="col-md-12" id="search-instruments">
<input class="searchbar" type="text" ng-model="searchinstruments" placeholder="Search Instruments"/>
</div>
<div class="col-md-4 instrumentWrapper" ng-repeat="instrument in instruments | filter: searchinstruments">
<a href='{{instrument.url}}'>
<span class="instruments-thumbnail">
<img class="img-responsive user-images" src="{{instrument.img}}"/>
</span></a>
{{instrument.name}}</h3>
</div>

Display image from server in a div (newest first) PHP

I want to display images in from server. In the database you can find the description and name of the image. the images should be displayed in a div where always the newest is on top. As the number of images increase so does the number of div's. so, the oldest will be at the bottom. I have read a number of posts and forums but I was unable to get the logic and the code on how to do it. I hope you can help me with my problem. Thanks a lot for your answer.
the only code i have is the formatting of the dive's:
<div class="gallery">
<div class= "group">
<div class="images">
</div>
<div class="details">
</div>
</div>
<div class= "group">
<div class="images">
</div>
<div class="details">
</div>
</div>
<div class= "group">
<div class="images">
</div>
<div class="details">
</div>
</div>
</div>
it's something like this:
newest image | some details here
newer image | some datails here
new image | some details here
old image | some details here
EDIT 1
I combined Lauri Elias' and iamde_coder's answer. I come up with this code which works almost similar to what is wanted. the only problem is that it displays the item (image&details in a div) 4 times. How can I eliminate the three? thanks!
$image_query = mysql_query ("SELECT filename, story FROM tbl_contest ORDER BY time DESC");
while($image_data = mysql_fetch_array($image_query)){
$imageName = stripslashes(mysql_real_escape_string($image_data['filename']));
$imageDetails = stripslashes(mysql_real_escape_string($image_data['story']));
$count = 0;
foreach($image_data as $imageName) {
echo '<div class="group">';
echo '<div class="images"><img src="/Mainfolder/image_entry/'.$imageName.'"></img></div>';
echo '<div class="details">'.$imageDetails.'</div></div>';
$count ++;
}
}
Now that you've given a little more code to help try using this:
$count = 0;
$image_query = mysql_query ("SELECT filename, story FROM tbl_contest ORDER BY time DESC") or die(mysql_error());
while($image_data = mysql_fetch_array($image_query)){
$imageName = stripslashes(mysql_real_escape_string($image_data['filename']));
$imageDetails = stripslashes(mysql_real_escape_string($image_data['story']));
$count++;
echo '<div class="group">';
echo '<div class="images"><img src="/Mainfolder/image_entry/'.$imageName.'" alt="Image '.$count.'" /></div>';
echo '<div class="details">'.$imageDetails.'</div></div>';
}
You could, for example, use a MySQL select somewhat like this:
SELECT name, description FROM my_database.images ORDER BY created_at DESC;
Then bind the result set to a variable in PHP like $images and then iterate on it and generate HTML like this:
foreach($images as $image) {
echo '<div class="group">';
echo '<div class="images"><img src="/images_folder/'.$image['name'].'"></img></div>';
echo '<div class="details">'.$image['description'].'</div></div>';
}

Output a series of images from a db into a variable?

I have a number of images in my db and they all correspond to the same project ID.
I want them to be displayed next to each other in the browser.
But the following code is output only the latest image but not all of them:
//get all the images in this project and add them to the content variable for output
if (!empty($FormProjectID)) {
$DBQuery3 = mysqli_query($dblink, "SELECT * FROM images WHERE project_id = '$FormProjectID'");
if (mysqli_num_rows($DBQuery3) < 1) {
$content = '
<p>This project is empty. Upload some files to get started.</p>
';
} else {
while($row = mysqli_fetch_array($DBQuery3)) {
$DBImageID = $row['image_id'];
$DBProjectID = $row['project_id'];
$DBImageName = $row['image_name'];
$DBImageDescription = $row['image_description'];
$DBDateCreated = $row['date_created'];
$DBLinkToFile = $row['link_to_file'];
$DBGivenName = $row['given_name'];
//if the image was given a name by the user, display it
//otherwise display the generated name
if (strlen($DBGivenName) > 1) {
$FileName = $DBGivenName;
} else {
$FileName = $DBImageName;
}
$content = '
<div class="image">
<img src="'.$DBLinkToFile.'" alt="'.$FileName.'" title="'.$FileName.'"/>
</div>
';
}
}
How do I get all the image so that in the end the html looks like this:
<div class="image">
<img src="'.$DBLinkToFile.'" alt="'.$FileName.'" title="'.$FileName.'"/>
</div>
<div class="image">
<img src="'.$DBLinkToFile.'" alt="'.$FileName.'" title="'.$FileName.'"/>
</div>
<div class="image">
<img src="'.$DBLinkToFile.'" alt="'.$FileName.'" title="'.$FileName.'"/>
</div>
Later on in my html page I have:
<?php echo $content; ?>
change $content = ' to $content .= '
PHP String Operators
Note: set the $content variable to empty string or null before your while loop
What you're looking for is string concatenation (see string operators)
to fix your problem you'll need to first initialise an empty string, do this before your while loop
} else {
$content = '';
while($row = mysqli_fetch_array($DBQuery3)) {
and then use the concatenation operator . to append each image
$content .= '
<div class="image">
<img src="'.$DBLinkToFile.'" alt="'.$FileName.'" title="'.$FileName.'"/>
</div>
';

Categories