PHP Double Quotes In Array Key - php

I know this is really bad practice, but it's already been put in place because it is an existing system. Anyways, I have a table that has an id and a description. What the code does is it creates an array from this table, but to make it easy to search, we made the description they key and the id the value. Now the issue is that the description contains double quotes, example 4"x6", and that is preventing the program from finding the id. Is there any special escape sequence that I can use to get around this issue?
Here is an example of simplified code:
$my_ary = array('4"x6"'=>22, 'test'=>3);
echo $my_ary['4"x6"']; // Does not work
echo $my_ary['test']; // Works
$quote_key = '4"x6"';
echo $my_ary[$quote_key]; // Does not work
Hopefully with that example that will help out my explination.
this is with version 5.2.6-3ubuntu4.2 of PHP

It actually works for me on php 5.3.2

Your code works for me under PHP 5.3.2.

Related

PHP Array in Google Maps

I'm pulling google map data into a php array from MySQL. I have used this code as a base:
https://github.com/rajkavinchetty/Google-Maps-API-with-PHP-MySQL/blob/master/index.php
It almost works perfectly. The lat/long data is pulled from the array and sets-up the markers.
...
$locations[]=array( 'name'=>$name, 'lat'=>$latitude, 'lng'=>$longitude, 'lnk'=>$link );
...
But I'm having problem with the Title/Content of the infowindow.
With the base example I'm using, the content is formatted as a link:
var locations = [
<?php for($i=0;$i<sizeof($locations);$i++){ $j=$i+1;?>
[
'AMC Service',
'<p><?php echo $locations[0]['name'];?></p>',
<?php echo $locations[$i]['lat'];?>,
<?php echo $locations[$i]['lng'];?>,
0
]<?php if($j!=sizeof($locations))echo ","; }?>
];
but the variable pulls only the first link and name from the array, it does not go through the loop. I have tried many different variables, such as
<?php echo $locations[$i]['name'];?>
but this gives an error.
I'm not an expert in either php arrays or loop or java, so I'm fumbling around for clues. I've looked through all of the related questions here for help, and also consulted the Google stack as well.
Any help would be appreciated.
UPDATE:
The first three replies were useful, thank you, but no there yet.
After the comment from Andy, and encouragement from Divyamohan that the original solution should have worked, I realised that there must be some json formatting problem, so I tried:
<?php echo json_encode($locations[$i]['name']);?>
This worked and now I'm able to have these loop through.
But still trying to get this to work as an href link. I tried to solve with backslashes as Hardik and David observed, but still this does not work. Half way there.
'<p><?=$locations[$i]["name"]?></p>'
Just Replace this in your code and it should work.
You need to change this line
'<p><?php echo $locations[0]['name'];?></p>'
to
'<p><?php echo $locations[0][\'name\'];?></p>'
You need to add backslash ( \ ) character to escape quote from string literals.
So finally I found the solution to the problem. Thanks to the comments from everyone that helped me to look at it another way.
In the end, the problem was not with the code. The problem was the data. This should have been obvious. In the links column I had URLs with slashes and text in the names column included apostrophes and foreign characters. These combined were throwing off the json errors. I cleaned all the data and the modified code works perfectly.
<p><?=$locations[$i]['name']?></p>
Many thanks again for the comments.

Using variable type variables as array names in php

I'm trying to make a dynamic menu in my web, in which only some pages from each section will appear.
The code I wrote was:
$menulist=array();
$menulist[1]='file1%#16';
$menulist[2]='file2%#9';
$menulist[3]='file3%#19';
$menulist[4]='file4%#8';
$menulist[5]='file5%#13';
$menulist[6]='file6%#14';
$menulist[7]='file7%#10';
$menulist[8]='file8%#23';
$menulist[9]='file9%#19';
$menulist[10]='file10%#18';
$menulist[11]='file11%#12';
function actualizaciones($matriz)
{
$linea=explode("%#",$matriz);
echo '<li><a href="first_chunk_of_URL'.$linea[0].'middle_chunk_of_url'.$linea[1].'last_chunk_of_URL">'.${$linea[0]}[$linea[1]].'</li>;
}
echo '<ul>';
array_walk($menulist,'actualizaciones');
echo '</ul>';
Every $linea[0] string is the name of another array (not shown in this code) which contains the text that should be in every possible link corresponding to every key passed by $linea[1].
I must have done something wrong, because the hyperlinks work fine but there's no text showing on them.
use the simple character like below
echo '<li><a href="first_chunk_of_URL'.$linea[0].'middle_chunk_of_url'.$linea[1].'last_chunk_of_URL">'.${$linea[0]}[$linea[1]].'<li>';
and the problem in your code is
.'</li>;
^^^^^
here is the problem it should be
.'</li>';
If I'm reading the question right, you're asking how to use variable variables in PHP.
This can be done using the double-dollar syntax - ie $$linea[0]. See the PHP manual for more info: http://uk.php.net/manual/en/language.variables.variable.php
But if that is what you're doing, I would say you're not writing good code: if variable variables are involved, there's almost always a better way of doing it.
Can't really offer much better assistance here without understanding more about what you're trying to do, but it sounds like you should be using subarrays rather than separate named variables for everything.
Hope that helps.

Setting language for user

I would like my php website to be able to be multilinguistic. I thought of using:
echo $lang[$_SESSION['lang']]['WellcomeMessage'];
but I found that I will be needing to format the text, say for example male/female or putting some values from the DB. So I thought that simple strings might not do the trick for formatting?
I know #define might have worked in C as the string translates to code, but I don't know how php does that. For example:
define ($lang['en']['credit_left'],'you have $credits_left');
define ($lang['sp']['credit_left'],'tienes $credits_left creditos mas');
Any suggestions?

Mysql insert from XML with "hyphen" in field name

I am trying to insert into mysql from an xml using PHP, but the field name contains a "hyphen" and for some reason it is not inserting this field, the rest are fine. I have tried using the hex codes x002D, x2010,x2012, and none have worked. As you can see in my xml, the hyphen is not being changed like the space, but if I just remove the x002D inserts everything after the "E" in other words just inserts -mail_x0020_Address.
This is my xml:
<encuestas>
<ID>9949</ID>
<E-mail_x0020_Address>email#email.com</E-mail_x0020_Address>
<ZIP_x002F_Postal_x0020_Code>90001</ZIP_x002F_Postal_x0020_Code>
</encuestas>
This is my insert statement ( I removed fields, I have 20 on that xml):
"INSERT INTO New_Encuestas_Datos(ID,`email`,`Zip/Postal Code`) VALUES('$product->ID','$product->E-mail_x0020_Address','$product->ZIP_x002F_Postal_x0020_Code')";
The variables are coming from an array reading the xml and like I said, everything is imported except email. I have tried the following combinations:
E-mail_x0020_Address
E_x002D_mail_x0020_Address
E_x2010_mail_x0020_Address
E_x2012_mail_x0020_Address
Can anyone point me what I am doing wrong? Thanks !
Hmm, I doubt you can use it in a string, but in plain PHP it is $product->{'E-mail_x0020_Address'};. But that doesn't matter anyway, as you should escape you values prior to sending them to a database you can nicely name an escaped variable as you like.
Try using:
"INSERT INTO New_Encuestas_Datos(ID,`email`,`Zip/Postal Code`) VALUES('{$product->ID}', '{$product->E-mail_x0020_Address}', '{$product->ZIP_x002F_Postal_x0020_Code}')";
Edited:
Just found here Validate class/method names with regex that '-' is not valid in method names.

how to eval() a segment of a string

I have a string that has HTML & PHP in it, when I pull the string from the database, it is echo'd to screen, but the PHP code doesn't display. The string looks like this:
$string = 'Hello <?php echo 'World';?>';
echo $string;
Output
Hello
Source Code
Hello <?php echo 'World';?>
When I look in the source code, I can see the php line there. So what I need to do is eval() just the php segment that is in the string.
One thing to consider is that the PHP could be located anywhere in the string at any given time.
* Just to clarify, my PHP config is correct, this is a case of some PHP being dumped from the database and not rendering, because I am echo'ing a variable with the PHP code in it, it fails to run. *
Thanks again for any help I may receive.
$str = "Hello
<?php echo 'World';?>";
$matches = array();
preg_match('/<\?php (.+) \?>/x', $str, $matches);
eval($matches[1]);
This will work, but like others have and will suggest, this is a terrible idea. Your application architecture should never revolve around storing code in the database.
Most simply, if you have pages that always need to display strings, store those strings in the database, not code to produce them. Real world data is more complicated than this, but must always be properly modelled in the database.
Edit: Would need adapting with preg_replace_callback to remove the source/interpolate correctly.
You shouldn't eval the php code, just run it. It's need to be php interpreter installed, and apache+php properly configured. Then this .php file should output Hello World.
Answer to the edit:
Use preg_replace_callback to get the php part, eval it, replace the input to the output, then echo it.
But. If you should eval things come from database, i'm almost sure, it's a design error.
eval() should work fine, as long as the code is proper PHP and ends with a semicolon. How about you strip off the php tag first, then eval it.
The following example was tested and works:
<?php
$db_result = "<?php echo 'World';?>";
$stripped_code = str_replace('?>', '', str_replace('<?php', '', $db_result));
eval($stripped_code);
?>
Just make sure that whatever you retrieve from the db has been properly sanitized first, since you're essentially allowing anyone who can get content into the db, to execute code.

Categories