Mysql insert from XML with "hyphen" in field name - php

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.

Related

PHP/MySQL: Strange output issue when echoing variable from MySQL database

I have a MySQL table that contains names and e-mail addresses. The data was originally imported from a .csv file, and it did not originally contain complete e-mail addresses. We had to append the #place.domain to the user's alias.
When the data is sitting in the MySQL table, it looks normal: person#place.domain; however, when I output the content in PHP, I get this: person #place.domain. There's always a space between the person and the #. It doesn't look like that in the MySQL column, nor does it look like that when I copy/paste the data into Notepad, Word, Excel, etc. Furthermore, if I erase the data in the column and manually replace it with person#place.domain, it displays normally in my PHP app. So I'm guessing there's some hidden character that PHP is picking up that I can't detect. Is there a way for me to clean this up? I've tried TRIM(), REPLACE,(), etc., all to no avail.
UPDATE: I've discovered that, when I click in the MySQL field and move among the characters using my arrow keys, I have to hit the arrow key TWICE to move past the # symbol, yet there is no visible space.
I made this sample code for you:
<?php
$test = "user #mail.com";
$aux = explode("#",$test);
$mailok = trim($aux[0])."#".trim($aux[1]);
echo $test." vs ".$mailok;
?>
This is likely something like non-breaking space (ascii 160). To get rid of it:
UPDATE my_table SET e_mail = REPLACE(e_mail, CHAR(160), '');
Try with a foreach cycle, and do the chr($char) function to every character in the string, it will display you the ascii code of each character in the string, and you will find the wrong character. It's the only solution I found. Hope to be useful

Different results between print_r($something) and writing the same $something in database

I am parseing a page and saving the retrived data in mysql db. Everything is ok except the price of the product. After extracting price,when i use print_r($price) i get the actual value but while saving the same $price in my database, i get only a part of it.
for example:-
while using print_r($something); //output is 2 458
while saving in database $something, the saved value is only 458.
I think that the problem is due to space between 2 and 4. I can understand that this is a very simple question for most of you, but right now i am not able to solve it.
Thanks a lot ahead for support!
MySQL is pretty permissive about what data you can insert into its fields. In this case you are trying to insert a string that contains two numbers into a numeric field, it's doing its best to extract a single number from that data but is getting it wrong.
All you need to do is remove the space(s) before you insert:
$something = str_replace(' ', '', $something);
or using a regular expression you could remove any non-numeric character:
$something = preg_replace("'[^0-9]'", '', $something);

PHP json_decode returns null

I'm writing PHP code that uses a database. To do so, I use an array as a hash-map.
Every time content is added or removed from my DB, I save it to file.
I'm forced by my DB structure to use this method and can't use mysql or any other standard DB (School project, so structure stays as is).
I built two functions:
function saveDB($db){
$json_db = json_encode($db);
file_put_contents("wordsDB.json", $json_db);
} // saveDB
function loadDB(){
$json_db = file_get_contents("wordsDB.json");
return json_decode($json_db, true);
} // loadDB
When echo-ing the string I get after the encoding or after loading from file, I get a valid json (Tested it on a json viewer) Whenever I try to decode the string using json_decode(), I get null (Tested it with var_dump()).
The json string itself is very long (~200,000 characters, and that's just for testing).
I tried the following:
Replacing single/double-quotes with double/single-quotes (Without any backslashes, with one backslash and three backslashes. And any combination I could think of with a different number of backslashes in the original and replaced string), both manually and using str_replace().
Adding quotes before and after the json string.
Changing the page's encoding.
Decoding without saving to file (Right after encoding).
Checked for slashes and backslashes. None to be found.
Tried addslashes().
Tried using various "Escape String" variants.
json_last_error() doesn't work. I get no error number (Get null, not 0).
It's not my server, so I'm not sure what PHP version is used, and I can't upgrade/downgrade/install anything.
I believe the size has something to do with it, because small strings seem to work fine.
Thanks Everybody :)
In your JSON file change null to "null" and it will solve the problem.
Check if your file is UTF8 encoded. json_decode works with UTF8 encoded data only.
EDIT:
After I saw uploaded JSON data, I did some digging and found that there are 'null' key. Search for:
"exceeding":{"S01E01.html":{"2217":1}},null:{"S01E01.html":
Change that null to be valid property name and json_decode will do the job.
I had a similar problem last week. my json was valid according to jsonlint.com.
My json string contained a # and a & and those two made json_decode fail and return null.
by using var_dump(json_decode($myvar)) which stops right where it fails I managed to figure out where the problem was coming from.
I suggest var_dumping and using find dunction to look for these king of characters.
Just on the off chance.. and more for anyone hitting this thread rather than the OP's issue...I missed the following, someone had htmlentities($json) way above me in the call stack. Just ensure you haven't been bitten by the same and check the html source.
Kickself #124

stripslashes issue in php

when i use stripslashes in php but i did not get the exact solution. I have menstion below which i used in my code those are
Example if i have the value in table like suresh\'s kuma\"r
i trying to display the value in the following three formats but no one is giving exact value
1) value=<?=stripslashes($row[1])?> //output is suresh's
2) value='<?=stripslashes($row[1])?>' //output is suresh
3) value="<?=stripslashes($row[1])?>" //output is suresh's kuma
But the exact output i need is suresh's kuma"r
let me know how to resolve the this issue?
The issue has nothing do to with stripslashes. If I guess correctly, the problem lies in the fact that in your examples quotes break the html field attribute;
I'll show you by manually echoing out your $row content as per your infos:
value=sures kumar --> leads to browser to interpret this as value="sures" kumar
value='suresh'khumar --> well, same story value='sures' khumar
value="Suresh"Khumar -->what can I say...you know the drill
Escaping the quotes won't affect html, since backslashes has no meaning in html.
Both value="Suresh" and value="Suresh\" will work fine for the browser, but your name will always be interpreted by the browser as some unknown attribute, leaving only the first part inside the value.
What you might do, instead, is apply htmlentities($row[1],ENT_QUOTES) so that they get converted in the equivalent entity (&quote;,for ex.) and not break your value attribute. See manual.
Another issue is that you shouldn't be having backslashes in your database in the first place; this might be due to the presence of magic_quotes enabled in your provider, or you passing manually addslashes() or other wrong trickery. If you want to insert into a database values containing quotes, use the escaping mechanism provided by your database driver (mysql_real_escape_string() in mysql, for ex.), or better tools (preparated statements with query bindings).
You should first get rid of all the slashes using that stripslashes and re-saving back the content; but slashes or not, the issue would appear again if you don't format that appropriately for your html, as I showed above.
Are you sure you want stripslashes instead of addslashes? Is the purpose is to quote the " characters?

PHP Double Quotes In Array Key

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.

Categories