PHP: trying to put href HTML attribute into a `echo` - php

I can't seem to get a URL into echo. I want to make a link to open Google Maps:
I can't figure out what's wrong with my code:
$query = mysql_query("SELECT * FROM cev")or die(mysql_error());
while($row = mysql_fetch_array($query))
{
$name = $row['sitecode'];
$lat = $row['latitude'];
$lon = $row['longitude'];
$type = $row['sitetype'];
$city = $row['city'];
$id = $row['id'];
echo("addMarker($lat, $lon,'<b>$name</b>View<br><br/>$type<br/>$city');\n");

You have to fix the quotes:
echo "addMarker($lat, $lon,'<b>$name</b>View<br><br/>$type<br/>$city');\n";
Alternative ways
Here document
echo <<<EOS
addMarker($lat, $lon, '<b>$name</b>View<br><br/>$type<br/>$city');
EOS;
Concatenation
echo "addMarker($lat, $lon, '<b>$name</b>" .
"View" .
"<br><br/>$type<br/>$city)";
Using addshashes
The addMarker looks like a JavaScript function. You might pre-process the HTML string by means of addslashes:
$html = <<<EOS
<b>$name</b>View<br><br/>$type<br/>$city
EOS;
$html = addslashes($html);
echo "addMarker($lat, $lon, '$html');\n";
Recommendations
I recommend using an editor with support of syntax highlighting.
Read about PHP strings. Especially the matter of escaping.
Finally, I wouldn't recommend writing any HTML/JavaScript within a PHP code. Use template engines such as Smarty or Twig instead.

It seems like you are trying to use method inside the echo statement. If you want to use methods, variables or some php stuffs you should not use quotes at most case unless it is an eval featured object or method.
Try like this
echo addmarker($lat, $lon,
'<b>'.$name.'</b> <a href="'.editcev.php?id=.' '.$row['id'].
".'>View</a><br><br/>'
.$type.
'<br/>'
.$city.');'."\n");
I don't know your exact situation but i think this works

echo("addMarker(".$lat.",".$lon.",<b>".$name."</b>View<br><br/>".$type."<br/>".$city.");\n");

Related

PHP variable within an echo?

My WordPress site needs to have a different RSS feed on every page. In the short-term, I need to find a way to output an RSS feed with category = "2" (which will later become a number from different pages). I'm relatively new to PHP though.
Is there a way to get a variable echo'd WITHIN an echo?
I've tried:
<?php
$category = '2';
echo do_shortcode('[rssfeed cat="$category"]');
?>
and
<?php
$category = '2';
echo do_shortcode('[rssfeed cat='echo "$category"']');
?>
... But obviously they don't work. Can anyone suggest a work-around? Thanks
You can just concatenate your strings like this:
$category = '2';
echo do_shortcode("[rssfeed cat='" . $category . "']");
You can adapt your first attempt but swap the " and ' around - variables will be parsed if you use double quotes http://php.net/manual/en/language.types.string.php#language.types.string.parsing
<?php
$category = '2';
echo do_shortcode("[rssfeed cat='$category']");
?>
Variable interpolation only happens between double quotes. But shortcodes can use either single or double quotes for their attributes, so if you put your quotes the other way around, it should just work:
<?php
$category = '2';
echo do_shortcode("[rssfeed cat='$category']");
?>
The PHP string now has double quotes, so $category will be interpolated to its value, and the attribute has single quotes, which will still work fine ("Shortcode macros may use single or double quotes for attribute values"), and not terminate the enclosing PHP string.
Rizier123's answer above worked great:
<?php
$category = '2';
echo do_shortcode("[rssfeed cat='" . $category . "']");
?>
I actually needed to pull a value from each WordPress page through Advanced Custom Fields, using the_field(category). When I tried to do:
<?php
$category = the_field(category);
echo do_shortcode("[rssfeed cat='" . $category . "']");
?>
It didn't work - even though
echo $category;
produced the right value. Lots of suggested variations didn't work either - possibly this is a problem with Wordpress. I figured I needed to somehow pass a printed value of a variable into another variable, for it to work. For anyone trying to do what I was doing, a solution I found that worked is:
<?php
function abc(){
print the_field(category);
}
ob_start();
abc();
$category = ob_get_clean();
echo do_shortcode("[rssfeed cat='" . $category . "']");
?>

PHP: Complicated String With Single and Double Quotes

I'm trying to pass GET variables inside the URL with a bit of html inside of my PHP but can't figure out the quotes situation. I need to embed two variables inside the URL. I have one in but don't know how to embed the other. Here is the string:
echo "<a href='?id=".($id-1)."' class='button'>PREVIOUS</a>";
and here is what I need to go inside
&City=$City
Thanks for the help
Its pretty simple,
echo "<a href='?id=".($id-1)."&city=" . $City . "' class='button'>PREVIOUS</a>";
In php double quotes "" can eval variables inside them.
$test = "123;"
echo "0$test456"; // prints 0123456
In your case you better use single quote ''.
echo '<a href=\'?id=' . ($id-1) . '&City=' . $City . '\' class=\'button\'>PREVIOUS</a>';
or better
echo 'PREVIOUS';
Use something like this:
echo "<a href='?id=".$id."&City=".$city."'>";
You do need (well, it's good practice anyway) to use & for your ampersand. Otherwise it's fairly straight forward;
echo "<a href='?id=".($id-1)."&City=$City' class='button'>PREVIOUS</a>";
This is because you are using double quotes, which means you can put variables directly into the string (there are some exceptions which you might need to put in curly brackets {}).
I suggest you get a text editor with syntax highlighting, such as jEdit (other editors are available).
Hope this helps.
Maybe is it better to use the sprintf function
$id = 100;
$previousId = $id - 1;
$City = 'Amsterdam';
$link = 'PREVIOUS';
echo sprintf($link, $id, $City);

Get attribute with file_get_contents PHP

I have a sql query that I store in a variable and I displayed. I get the contents of this with file_get_contents from another file, I would like to recover some of this code (which is html) in order to make link. More precisely retrieve the id.
My api.php
$base = mysql_connect ('localhost','root','');
mysql_select_db('administrations', $base);
if(isset($_GET['cp']))
{
$sql = 'SELECT NOM_organisme, ID_organisme
FROM organismes
WHERE code_postal LIKE "%'.$_GET['cp'].'%"
ORDER BY NOM_organisme;';
$req = mysql_query($sql) or die('SQL Error !<br>'.$sql.'<br />'.mysql_error());
}
while ($data = mysql_fetch_array($req))
{
echo '<p id="'.$data['ID_organisme'].'"'.
$data['NOM_organisme'].'</br>'.
$data['ID_organisme'].'</p></br>';
}
I want to get the id="I WANT THIS".
And my index.php (part of my code that retrieves the contents).
if(isset($_POST['cp']))
{
$api = "http://mywebsite.fr/api.php?cp=".$_POST['cp'];
$var = file_get_contents($api);
echo $var;
}
How can I get the id="" in my index.php ?
please look at php get documentation. you need to link to your script with url parameters and access them in your php code.
http://php.net/manual/en/reserved.variables.get.php
echo ''.$data['NOM_organisme'].'</br>'.$data['ID_organisme'].'</br>';
php
if(isset($_GET['id']))
{
$api = "http://mywebsite.fr/api.php?cp=".$_GET['id'];
$var = file_get_contents($api);
echo $var;
}
if you dont want to use url parameter you can use post values
http://php.net/manual/en/reserved.variables.post.php
I understand what your trying to do, but dont find it logical without knowing the purpose of this tiny code :)
Do you have a link or some sort?
Basicly what i should do is:
$base = mysql_connect ('localhost','root','');
mysql_select_db('administrations', $base);
if(isset($_POST['cp']))
{
$sql = 'SELECT NOM_organisme, ID_organisme FROM organismes WHERE code_postal LIKE "%'.$_GET['cp'].'%" ORDER BY NOM_organisme;';
$req = mysql_query($sql) or die('SQL Error !<br>'.$sql.'<br />'.mysql_error());
while ($data = mysql_fetch_array($req))
{
echo '<p id="'.$data['ID_organisme'].'"'.$data['NOM_organisme'].'</br>'.$data['ID_organisme'].'</p></br>';
}
} else {
echo 'show something else';
}
If I get you correctly, you are
Sending a GET request in index.php using file_get_contents() to your website.
The website (api.php) performs an SQL query and prints the result in HTML.
index.php takes this HTML output and stores it in the variable $var.
You want to retrieve all values contained inside the id attribute of the paragraph.
In this case, you probably want to use regular expressions. preg_match_all seems to be appropriate. It should work for you like this:
$out = array();
preg_match_all("/id=\"([^\"]*?)\"/U", $var, $out);
foreach ($out as $value) {
echo 'I found some id ' . htmlspecialchars($out[$value][2]) . '<br />';
}
And additionally:
A decent HTML parser would be much more appropriate in this case (eg. it would not match id="X" in flow text).
Your PHP code is vulnerable to SQL injections.
You should sanitize plain text to HTML appropriately.
First of all, you should try to display your API reply as a JSON-string, this is much more convenient.
If you still want to use your api.php, you first need to close your opening paragraph! You did forget a '>'!
echo '<p id="'.$data['ID_organisme'].'">'.
$data['NOM_organisme'].'</br>'.
$data['ID_organisme'].'</p></br>';
Then you need to parse your paragraph.
You can do it like that:
if(isset($_POST['cp']))
{
$api = "http://mywebsite.fr/api.php?cp=".$_POST['cp'];
$var = file_get_contents($api);
preg_match("#<p id='(.*)'#", $var, $matches);
id = $matches[1];
echo $id;
}

php code inside variable with html code

I want to add code php to variable with html, for example
$html = '<b></b> <?php echo $lang["text"] ?>';
but it don't interpret php code. What am I doing wrong?
Use string concatenations like this:
$html = '<b></b>' . $lang['text'];
or insert variable in double quoted string like this:
$html = "<b></b>${lang['text']}";
both versions are correct, use the one that you like.
What you want is called string interpolation (read about how it works for PHP).
Your particular example would be solved using
$html = "<b></b> {$lang['text']}";
String interpolation only happens in double quoted string ("string here").
its very important to escape the output. (security basics)
$html = sprintf('<b>%s</b>', htmlspecialchars($lang['text']));
You can't switch from "Output raw text mode" to "Run PHP code mode" in the middle of a string while you are already in "Run PHP code mode"
$html = "<b></b> ${lang['text']}";
… although why you want an empty bold element is beyond me.
<?php
$html = '<b>'.$lang['text'].'</b>';
?>
make sure file extension is php.
<?php
$html = '<b>' . $lang["text"] . '</b>';
?>

IMG SRC inside PHP with more PHP inside how to

I always have trouble mixing languages and I recently started with MYSQL. In this case I have this code:
<?php
$data = mysql_query("SELECT * FROM Badges")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
Print "http://www.google.com/s2/favicons?domain=".$info['Website'] . "";
}
?>
And I need it to print an image instead of the link it's printing.
http://www.google.com/s2/favicons?domain=".$info['Website'] . " being the image's url
How would that be written? Thanks a lot
print '<img src="http://www.google.com/s2/favicons?domain=' . $info['Website'] . '" alt="" />';
Some other tips...
mysql_* are old functions, PDO is much better to use now it is available.
or die() is old too - have you considered exceptions?
echo is more commonly used than print, and you should use the case that is stated in the manual, e.g. print instead of Print.
You should learn about separation of concerns, e.g. you should do your query and data management on a different layer where you pass the relevant data to your view which would consist solely of HTML and some PHP constructs used to generate it.
i usually find it easier to try and express what differs from case to case in an abstract manner. in your case it's the website (after ?domain=) that differs, all the rest is the same. so the url to the image could abstractly be expressed as http://www.google.com/s2/favicons?domain={website} where {website} is a place holder for future replacement.
replacement would then be performed using the function
$result = str_replace($what_to_replace, $what_to_replace_with, $original_string);
the advantage of this is that you're never mixing languages on one line, and this makes the code easier to develop :) just look at this quite easily read piece of code:
<?php
$img = '<img src="http://www.google.com/s2/favicons?domain={website}" />';
$data = mysql_query("SELECT * FROM Badges")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
$concrete_img = str_replace("{website}", $info['Website'], $img);
print $concrete_img;
}
?>

Categories