Can I pass a blade variable into a php one in Laravel? - php

i'm super new to Laravel and I've been doing some research on how to get the google maps api to work with laravel.
I've already made my blade to fetch content from my database with eloquent etc, so I know that wwhen you use blade you can put the vars between two curly brackets to then "echo" them on the webpage (like this {{$training->Location}} )
The problem is that in the following snippet of code I need to pass the data from the Location table into a php var and I don't know how to pass it. That's how I did it , but obviously it didn't work out well , it just passes it as direct text I guess...
So when I put this $adress = '{{$training->Location }}; and I echo it on my page for testing purposes I get this string as a result: %7B%7B%24training-%3ELocation%7D%7D which the googleMapsApi will not recognize as a correct adress.
Here's the code snippet: `
<div>
<H4>Location: {!!$training->Location!!}</H4>
</div>
<div>
<H4>Starting Date: {!!$training->DateTime!!} </H4>
</div>
<?php
$adress = '{{$training->Location}}';
//$adress = 'Universitätsring 1, 1010 Wien';
$adress = urlencode($adress);
$url = 'http://maps.googleapis.com/maps/api/geocode/xml?address=' . $adress . '&sensor=true';
$xml = simplexml_load_file($url);
$status = $xml->status;
if ($status == 'OK') {
$latitude = $xml->result->geometry->location->lat;
$longitude = $xml->result->geometry->location->lng;
} ?>`
I hope you understand my problem , sorry my English isn't the best, but if you don't understand I can always provide screenshots or a better explaination

Although the suggest answer works this is not a good design practice.
In your blade files should not be anny php code other then absolutely necessary for displaying values. The code you wrote in your blade file should be located in the controller. I would suggest you get familiar with the MVC concept Laravel is build on. From the laravel docs (https://laravel.com/docs/5.5/views):
Views contain the HTML served by your application and separate your
controller / application logic from your presentation logic.
Making an callout to get the geometric location should be in your controller (or some helper class) at least not in your view.
Also this would be a good read: https://scotch.io/#ARKASoftwares/mvc-development-the-need-of-the-changing-world

The simplified workflow is as follows: any Blade code is converted to the equivalent PHP, then the PHP code is executed server-side and the resulting HTML is then passed to the client.
You are using Blade because this is what you want to do (probably because of the much nicer syntax) and certainly not because of some unspoken Laravel constraint. Any variables "available in Blade" are also available in plain PHP for you to use.
Replacing
$address = '{{$training->Location}}';
with
$address = $training->Location;
is perfectly "legal" and should be the way to go if you consider you are in the need for plain PHP.

Related

Implementing SmartyBC

Just a small question for anyone out there that uses smarty. I am trying to pass PHP directly into my code, but when I do, the cached version cuts out the PHP and just prints it directly like so.
<div class="dashboard-card-content">
<?php
$con = mysqli_connect(Nice,Try,Fly,Guy);
$company_id = $_smarty_tpl->tpl_vars['auth']->value['user_id'];
$company_id = mysqli_query($con,"SELECT company_id FROM cscart_users WHERE user_id = $company_id")->fetch_object()->company_id;
$company_id = mysqli_query($con,"SELECT goal FROM cscart_companies WHERE company_id = $company_id")->fetch_object()->goal;
echo "Your current goal is: ".$company_id;
?>
This just prints all of it out on my webpage, so I tried using the following:
{Literal}
{Include_php}
{php}
And I just can't find a way to get my PHP code to go into my TPL how I want it. This is becoming really frustrating and all I want is for my cache files to leave the PHP code alone. Sorry if this is a dumb question but I have been researching this for a while. How do I implement SmartyBC so that I can still use PHP injections. And if using SmartyBC is a bad idea, can someone give me a dumbed down version of how to use a seperate PHP function page to set variables to show in the Template?
Smarty is a template engine for presentation logic only. You cannot put application logic inside a template. It was possible in older versions of Smarty but fortunately not anymore. Just execute those funcions in a php file and pass the result to the template.
And yes, you can use SmartyBC: http://www.smarty.net/docs/en/bc.tpl, but that's supposed to be used for compatibility with existing projects. It's a really bad idea and shouldn't be used for new projects.
Why do you want to use php in Smarty?
Put your logic into a class or function, and pass the data via the controller: Registry::get('view')->assign('smarty_variable', $data), and you are good to go.
You can create PHP function which gets necessary data from database. E.g.
function fn_get_company_goal($user_id)
{
$company_id = db_get_field("SELECT company_id FROM ?:users WHERE user_id = ?i, $user_id");
$goal = db_get_field("SELECT goal FROM ?:companies WHERE company_id = ?i, $company_id");
return $goal;
}
Put it to your addon. Then you can use it in the Smarty template in the following manner:
{$goal = $user_id|fn_get_company_goal}

PHP : integrating static HTML content with resolved PHP variables?

I am working in a project which has the following restriction defined:
My PHP files must not have more than one opening or closing tag.
So it's PHP from top to bottom, but I am allowed to add static content by the means of 'import'.
What are proper/elegant ways to add static HTML content to my PHP index file (like outputting a website menu header or a formular) and at the same time resolve PHP variables inside the file.
Like a formular which makes a HTTP POST (login or register) and displays the previously entered email address in case of a mismatch, etc etc.
One way would be
echo "<form ...> \n <input ... value='$lastemail'>";
But I dislike the quoting. echo <<< EOF is also not great for the purpose imho.
I think HTML code should stay together without separating it into multiple echos so it can be validated.
So I am looking for a good solution to import/integrate static HTML code, like a template system and still resolve PHP variables.
Update:
The restriction is made to not mix HTML and PHP code.
I think I will need an engine/class/function which replaces variables inside a HTML template with PHP code. Like searching for ${variable} and replacing it with the php $variable as if it was PHP code.
I just thought maybe there is already something existing within PHP to solve that.
Update:
Should I oppose the requirement ?
Would be very interesting to hear the oppinion of a professional PHP developer with long history in that area. (On The restriction is made to not mix HTML and PHP code. )
Perhaps you could use a templating system? There are plenty out there for PHP. Some nice ones are (in my opinion):
Twig, which is very small and fast
Smarty, a little larger, but also fast and very popular
The solution that I provide now may seem lengthy and strenuous to enact but would one of the best ways to solve problems with such constraints. Create a database with two tables, one of which would store all the static data i.e. HTML code whereas the other would store dynamic data i.e. data that you want to be personalised. You can then use the database to separately eject dynamic and static data, all using just pure PHP.
<?php
$host = "127.0.0.1";
$user = "root";
$password = "****";
$db = "project";
$txt = NULL;
$conn = mysqli_connect($host, $user, $password, $db);
if(!conn){
header("location:error.htm");
}
$query1 = "SELECT dynamicdata FROM projectdynamicdata WHERE pagename ='index'";
$resultset1 = mysqli_query($conn, $query1);
while($row = mysqli_fetch_assoc($resultset1){
$txt = $row["dynamicdata"];
}
$query2 = "SELECT htmlpage FROM projectstaticdata WHERE pagename='index'";
$resultset2 = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($resultset){
echo $row["htmlpage"];
}
mysqli_close($conn);
?>
This is what I would to solve such a problem.

How to pick up the database name and table name from the URL in PHP?

I am new to PHP.
I need a help regarding the methods of extracting DB name and table name from the given URL name.
For example, let's say, I have an URL like the one below:
/test.php?db=...&table=.../
How to extract the DB name and table name from this URL using PHP and use the result for other query purposes.
If you mean how to parse an existing URL for it's parameters:
parse_url() and parse_str() will help you strip the components of the url. You will primarily be looking at the following
$elements = parse_url($url);
$kvps = $elements->query;
$db = parse_str($kvps['db']);
$table = parse_str($kvps['table']);
But, if you mean how to GET variables from the current page before render:
<?php
$dbname = $_GET['db'];
$tablename = $_GET['table'];
?>
And yea, there are major security risks involved in opening up 'direct' access to your database this way. Best to obfuscate / encapsulate / wrap your functions in tasks like index.php&addUser=tim instead of index.php&insert=tim&db=boofar&table=users&dbuser=root&dbpassword=secure.
If you're just learning, what you're doing is fine, as long as you realize why it's wrong. If you're coding for production, you really need an alternate solution.
There are two ways to pass variables or data to another page.
GET (via the URL)
and
POST (usually a form submission)
You can alway get via
$_GET
http://php.net/manual/en/reserved.variables.get.php
or
$_POST
http://nl.php.net/manual/en/reserved.variables.post.php

PHP Zend_Paginator on mySql query using GET

I am trying to call pages using Zend_Paginate() on a query that loads based on a GET search string the query essentially does the following:
SELECT * FROM table WHERE column LIKE '%searchstring%' OR alt_column LIKE '%searchstring%';
The query works fine when called via search/submit text form and the URL returns something similar to
URLINK.php?search=searchstring
However when trying to move onto the next page the program dumps me back to the paginate alternate URL (used for errors or no page display)-- hope this last line makes sense it is late and am doing my best to type this up with transparency.
What is the best method when using paginate against URL.php?search=searchstring"?
A bit more on the call to the url
//search query
$search = searchQuery('search', 'list_sql_rows.php');
$results - searchTable($dbRead, $search);
search method using the variables above in the order below
if(isset($_POST['submit_search'])) { $searchstring = $_POST['searchstring'];
if($searchstring) { header('Location: results.php?search=' . $searchstring); } }
This bit works well, but when I try to call the results.php?page=2 with paginator the system reverts me to the fall back URL list_sql_rows.php as mentioned above. Any thoughts/comments are appreciated.
Just to clarify a search field/form from the search.php page sends the $searchstring to the results.php page via $_POST && $_GET as fail safe. The get method sends the $searchstring in the URL header so the results of the search DO work on the first page results.php?search=$searchstring. This works just fine. The pagination seems to lose the $searchstring, and I wonder if this is due to a loss of the $_POST/$_GET when paginator begins to 'paginate' it returns URL results.php?page=2 so it seems $_GET may not be the method of choice?
UPDATE
On the write track now paginate works it is my link structure that is broken.
_results_samples.php?search=robert&page=4_ will in fact return page 4 of the paginated results using the word ROBERT
SOLUTION FOUND VIA variant suggestion by ROCKYFORD
variant of recommended method by first persisting $searchstring
change to paginate links as shown below
<a href='" . $_SERVER['PHP_SELF'] . "?search=" . $searchstring . "&page={$page}'>$page</a>
Here is the example of correct using of pagination:
in action-method:
$select = $clients->getAll();
$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
$paginator->setCurrentPageNumber($this->_getParam('page'));
$paginator->setItemCountPerPage(20);
$this->view->clients = $paginator;
in a view script:
<?php if (count($this->clients) > 0): ?>
...
<?php echo $this->paginationControl($this->clients, 'Sliding', 'partials/paginator.phtml'); ?>
<?php else: ?>
<h3 class="notice">No registered clients found!</h3>
<?php endif; ?>
But even if you will fail with this variant, you can always try to compose your own component, Zend only aids us in solving some tasks.
you need to make sure you preserve the query strings between requests, use Zend_Session_Namespace or Zend_registry.
Everytime Zend_Paginator loads a page when using the DbTableSelect or DbSelect adapters it has to hit the db with the query, it just changes the limit option.
Or you could just dump the whole query result into a Zend_Paginator_Adapter_Array and it will page through the array.
[edit]
you are going to have to persist the query string between requests someway so you can put it back in the url string, I usually use Zend_Registry, but then I use the whole MVC stack. You don't seem to be using the whole stack so you'll need another method, probably $_SESSION would work. I'm sure there are many other ways to persist this data.
P.S. you didn't mention which adapter you are using so I'm making some assumptions.
[edit]
Personally I always use $_post for this when possible to avoid all this, only seem to have this problem with $_get.

Getting info from Wikipedia - how do I get HTML form?

I'm using curl to retrieve information from wikipedia. So far I've been successful in retrieving basic text information but I really would want to retrieve it in HTML.
Here is my code:
$s = curl_init();
$url = 'http://boss.yahooapis.com/ysearch/web/v1/site:en.wikipedia.org+'.$article_name.'?appid=myID';
curl_setopt($s,CURLOPT_URL, $url);
curl_setopt($s,CURLOPT_HEADER,false);
curl_setopt($s,CURLOPT_RETURNTRANSFER,1);
$rs = curl_exec($s);
$rs = Zend_Json::decode($rs);
$rs = ($rs['ysearchresponse']['resultset_web']);
$rs = array_shift($rs);
$article= str_replace('http://en.wikipedia.org/wiki/', '', $rs['url']);
$url = 'http://en.wikipedia.org/w/api.php?';
$url.='format=json';
$url.=sprintf('&action=query&titles=%s&rvprop=content&prop=revisions&redirects=1', $article);
curl_setopt($s,CURLOPT_URL, $url);
curl_setopt($s,CURLOPT_HEADER,false);
curl_setopt($s,CURLOPT_RETURNTRANSFER,1);
$rs = curl_exec($s);
//curl_close( $s );
$rs = Zend_Json::decode($rs);
$rs = array_pop(array_pop(array_pop($rs)));
$rs = array_shift($rs['revisions']);
$articleText = $rs['*'];
However the text retrieved this way isnt well enough to be displayed :( its all in this kind of format
'''Aix-les-Bains''' is a [[Communes of
France|commune]] in the [[Savoie]]
[[Departments of France|department]]
in the [[Rhône-Alpes]] [[regions of
France|region]] in southeastern
[[France]].
It lies near the [[Lac du Bourget]],
{{convert|9|km|mi|abbr=on}} by rail
north of [[Chambéry]].
==History== ''Aix'' derives from [[Latin]] ''Aquae'' (literally,
"waters"; ''cf'' [[Aix-la-Chapelle]]
(Aachen) or [[Aix-en-Provence]]), and
Aix was a bath during the [[Roman
Empire]], even before it was renamed
''Aquae Gratianae'' to commemorate the
[[Emperor Gratian]], who was
assassinated not far away, in
[[Lyon]], in [[383]]. Numerous Roman
remains survive. [[Image:IMG 0109 Lake
Promenade.jpg|thumb|left|Lac du
Bourget Promenade]]
How do I get the HTML of the wikipedia article?
UPDATE: Thanks but I'm kinda new to this here and right now I'm trying to run an xpath query [albeit for the first time] and can't seem to get any results. I actually need to know a couple of things here.
How do I request just a part of an article?
How do I get the HTML of the article requested.
I went through this url on data mining from wikipedia - it put an idea to make a second request to wikipedia api with the retrieved wikipedia text as parameters and that would retrieve the html - although it hasn't seemed to work so far :( - I don't want to just grab the whole article as a mess of html and dump it. Basically my application what it does is that you have some locations and cities pin pointed on the map - you click on the city marker and it would request via ajax details of the city to be shown in an adjacent div. This information I wish to get from wikipedia dynamically. I'll worry about about dealing with articles that don't exist for a particular city later on just need to make sure its working at this point.
Does anyone know of a nice working example that does what I'm looking for i.e. read and parse through selected portions of a wikipedia article.
According to the url provided - it says I should post the wikitext to the wikipedia api location for it to return parsed html. The issue is that if I post the information I get no response and instead an error that I'm denied access - however if I try to include the wikitext as GET it parses with no issue. But it fails of course when I have waaaaay too much text to parse.
Is this a problem with the wikipedia api? Because I've been hacking at it for two days now with no luck at all :(
The simplest solution would probably be to grab the page itself (e.g. http://en.wikipedia.org/wiki/Combination ) and then extract the content of <div id="content">, potentially with an xpath query.
There is a PEAR Wiki Filter that I have used and it does a very decent job.
Text Wiki
Phil
Try looking at the printable version of the desired Wikipedia article in question.
In other words, change this line of your source code:
$url.=sprintf('&action=query&titles=%s&rvprop=content&prop=revisions&redirects=1', $article);
to something like:
$url.=sprintf('&action=query&titles=%s&printable=yes&redirects=1', $article);
Disclaimer: Have not tested, and this is just a guess at how your API might work.
As far as I understand it, the Wikipedia software converts the Wiki markup into HTML when the page is requested. So using your current method, you'll need to deal with the results.
A good place to start is the Mediawiki API. You can also use http://pear.php.net/package/Text_Wiki to format the results retrieved via cURL.

Categories