Cliftwalker
Cliftwalker

Reputation: 369

PHP, strip out Currency symbol before posting to MySQL

I have an issue when posting the £ symbol to my DB it seems to add some strange characters before it. I've decided that the best thing to do is to strip the symbol before it goes in to the DB and add it back in again when I read the data.

Is there a simple PHP function that will take my $variable, take out that specific character before I send it and then create a new $variable_new that I can send to the DB.

Thanks, Jonny

Upvotes: 2

Views: 6249

Answers (5)

simshaun
simshaun

Reputation: 21466

You can always just use str_replace(), or you could use preg_replace to replace all non-numeric/dot/comma characters. However, I don't think either one is the best solution.

I think it would be best to alter your script so that the symbol is never tacked on to the numerical value in the first place. Do keep track of the symbol though, and perhaps store it in a separate column in the database so you know what currency was used. Having a strictly numerical value allows you to (more easily) do more that you might want in the future.

Upvotes: 0

Daniel Cannon
Daniel Cannon

Reputation: 614

This should be what you are looking for.

$variable_new = str_replace('£','',$variable);

Upvotes: 4

Sarfraz
Sarfraz

Reputation: 382806

You can use SUBSTRING function from within your query:

SUBSTRING(fieldName FROM 1)

Or check out:

To know how to change the charset of your database to support symbols.

Upvotes: 1

JasonWoof
JasonWoof

Reputation: 4196

The easiest (and best) solution is probably to get your character encodings right. First make sure you've got the web browser sending you stuff in utf-8

Then make sure your database is storing utf-8 or is encoding ignostic. I know MySQL cares about character encoding and that conversion happens (somewhere, in PHP and/or MySQL) if your character set isn't right.

I put: AddDefaultCharset UTF-8

in my .htaccess file for all sites to be sure all data is sent to me in UTF-8

Upvotes: 1

Capt Otis
Capt Otis

Reputation: 1260

I would use string replace as a quick solution, but ideally I would never add the symbol to the variable in the first place.

$newvar = str_replace('£', '', $oldvar);

Upvotes: 0

Related Questions