Jump to content


Photo

Ao Inserir Caracteres Especiais Não Grava No Db


  • Faça o login para participar
10 replies to this topic

#1 Nicholas Pufal

Nicholas Pufal

    Impossível: só existe até alguém duvidar e provar o contrário.

  • Usuários
  • 1655 posts
  • Sexo:Masculino
  • Localidade:Porto Alegre

Posted 15/02/2008, 08:33

Tô iniciando no php ainda, e agora tava fazendo uns testes de conexão com o database (mysql). Tá tudo funcionando perfeitamente, com excessão de quando eu coloco o conteúdo de algum campo assim por exemplo:

¨%4263123564""%$8503274823647 8012 307263'539#$@"@12341'9o\'23/c3\z$3¨@#"3519UYIUY&(¨623'\/]ad


Não retorna erro. Aparece a minha mensagem de "inserido com sucesso", porém não insere no DB.

É algum tipo de proteção do php/mysql isso ou eu estou fazendo cagad.. mesmo?

Trecho do meu código:

if (isset($_POST['submit'])) {

$nome = $_POST['nome'];
$email = $_POST['email'];
$comentario = $_POST['comentarios'];

$conectar = mysql_connect($dbhost,$dbuser,$dbpass);
$db = mysql_select_db($dbacesso,$conectar);

$query = "Insert into cadastro value ('$nome','$email','$comentario')";

$acao = mysql_query($query);

echo 'Cadastro realizado com sucesso!';

mysql_close($conectar);

}

Aproveitando o tópico: no php tem como eu fazer o script "trancar" em um ponto em função de algum item do formulário enviado não ter sido preenchido? Quando eu pergunto isso, não é com Ifs ou coisa similar, mas sim alguma função/método específico, que valha para o geral (independente de quantos campos eu submeti).

Abraço!
BLOG Touché Criação - Vamos trocar idéias? -> http://blog.touchecriacao.com.br/
// Links úteis: Busca || Regras
// Não respondo dúvidas via mensagem privada. Use o fórum para buscar ou perguntar.

#2 Paulo André

Paulo André

    Why so serious?

  • Ex-Admins
  • 5114 posts
  • Sexo:Masculino
  • Localidade:Belo Horizonte - MG
  • Interesses:O.Q.F.J.?

Posted 15/02/2008, 08:38

Tente:

$query = "Insert into cadastro value ('$nome','$email','" . $comentario . "')";

Sobre a segunda dúvida, isto seria uma espécie de validação, certo?

Você pode fazer condições em caso de preenchimento inadequado como e-mail por exemplo, ou simplesmente verificação de campos vazios.

Funções como preg_match() ou empty() você consegue fazer isto.

Ops... agora que eu vi a observação... ^_^

Bom, neste caso você mesmo pode fazer uma função que seja geral, pegando por exemplo o $_POST vindo do formulário.

Flws...
(ok2)Até mais
Paulo André G Rodrigues,
ex-administrador Fórum WMO.


www.CanalDev.com.br

#3 Nicholas Pufal

Nicholas Pufal

    Impossível: só existe até alguém duvidar e provar o contrário.

  • Usuários
  • 1655 posts
  • Sexo:Masculino
  • Localidade:Porto Alegre

Posted 15/02/2008, 09:18

Valeu o rápido retorno.

Bah, mas não rolou!

Inclusive tentei usar htmlspecialchars em todos meus campos pra ver se auxiliava, mas nada também.

Se eu testo apenas com aspas simples/duplas, funciona (ele insere). Agora, com aqueles caracteres loucos ele nunca insere os dados vindos do form no db.

Alguma outra sugestão?

Abraços
BLOG Touché Criação - Vamos trocar idéias? -> http://blog.touchecriacao.com.br/
// Links úteis: Busca || Regras
// Não respondo dúvidas via mensagem privada. Use o fórum para buscar ou perguntar.

#4 Crab

Crab

    Da paz, mas preparado para Guerra

  • Ex-Admins
  • 2521 posts
  • Sexo:Masculino
  • Localidade:Florianópolis - SC
  • Interesses:Desenvolvimento Gráfico e Web.

Posted 15/02/2008, 09:37

se no teu servidor não estiver com magic_quotes_gpc ON então tente usar addslashes() antes da string

Para saber se está on ou não use:

get_magic_quotes_gpc()


Mas talvez não seja isso, dado que poderia retornar erro de inserção caso fosse :ponder:

Qual o tipo que definiu para o campo que recebe os dados que disse não estar inserindo??

TEXT VARCHAR etc...

Quanto ao que poderia parar o processamento de um script é die() ou exit() que pra mim faz a mesma coisa...

Da uma lida no manual a respeito antes...

(y)Até mais

#5 Nicholas Pufal

Nicholas Pufal

    Impossível: só existe até alguém duvidar e provar o contrário.

  • Usuários
  • 1655 posts
  • Sexo:Masculino
  • Localidade:Porto Alegre

Posted 15/02/2008, 10:01

Crab,

valeu também.

get_magic_quotes_gpc() retorna 0, então tentei utilizar a função addslashes(), mas mesmo assim continua não inserindo.

Edit: tu editou o post ou eu tô louco? Eu não tinha visto a segunda pergunta antes :huh:

Então, respondendo: estou tentando inserir essa loucura em todos os campos, sendo que nos campos "Nome" e "E-mail" é "loucurinha", porque não coloco muita coisa. Estão assim:

Nome - varchar
Email - varchar
Comentario - text

Edit2: O problema reside também com aspas simples, quando elas usadas desta forma: Passo d'Areia

Edit3: Por alguma razão que desconheço, está funcionando agora (com addslashes). Talvez eu estivesse fazendo alguma besteira, como não dar refresh no arquivo atualizado :unsure:

De qualquer forma, valeu pela ajuda Crab e Paulo André!

Abraços ;)

Edição feita por: Firehalk, 16/02/2008, 11:21.

BLOG Touché Criação - Vamos trocar idéias? -> http://blog.touchecriacao.com.br/
// Links úteis: Busca || Regras
// Não respondo dúvidas via mensagem privada. Use o fórum para buscar ou perguntar.

#6 HaroNism

HaroNism

    Super Veterano

  • Usuários
  • 13822 posts
  • Sexo:Masculino
  • Localidade:San Miguel de Tucuman

Posted 23/10/2017, 22:13

Propecia O Proscar Wheretobuylevitrapills viagra Kamagra 50 Gel Oral Kamagra Jalea Efectos Secundarios Xenical Online
Where To Purchase Stendra levitra brand Amoxicillin Antibiotic
Kamagra Achat 150 Mg viagra Microzide

#7 RonsisM

RonsisM

    Super Veterano

  • Usuários
  • 15724 posts
  • Sexo:Masculino
  • Localidade:Plovdiv

Posted 25/10/2017, 04:35

Zithromax Kills Chlamydia viagra Acheter Viagra Pas Cher Paris
Cheapest Place To Buy Viagra Online online pharmacy Healthy Male Viagra Offer Rx Sites No Prescription Needed
Peut On Acheter Du Viagra Sans Ordonnance Priligy Sintomas Discount Zentel Ups In Internet Quick Shipping Price Kirklees viagra Zentel Usa Pills Free Doctor Consultation Low Price propranolol
Acheter Baclofene Suisse Viagra Als Droge Prix Du Cialis 5 Mg viagra Amoxil Dosage Weight Need Secure Ordering Clobetasol Medicine
Viagra Remboursement Prostate viagra Do Not Take Amoxicillin If
Viagra Comprare Line Amoxicillin Dose For Acne buy cialis Want To Buy Dutasteride
20mg Generique Acheter Levitra viagra online prescription Propecia Aerosol

#8 BobbyCak

BobbyCak

    договор ок

  • Usuários
  • 12238 posts
  • Sexo:Feminino
  • Localidade:Liberia
  • Interesses:115141

Posted 25/10/2017, 18:17

приказ об отмене отпуска образец

образец справки с места работы о неполучении единовременного пособия образец приказа о ликвидации отдела образец заполнения транспортной накладной 2017 восточный банк справка по форме банка скачать отчет по практике следственный отдел Письменное обязательство для использования маткапитала образец Образец заключения узи Устав некоммерческой организации образец 2017 Уведомление о смене банковских реквизитов организации образец Ходатайство в суд о рассмотрении дела без моего участия образец бланк сопроводительного письма к документам авансовые отчеты в 2017 году изменения суд возвращает исковое заявление в случаях письмо во вселенную 27 числа образец заполнения пример акт испытания газопровода на герметичность образец заявление за свой счёт на 2 дня образец анкета для парня от девушки вопросы Акт приема-передачи имущества в аренду Реестр договоров ресурсоснабжения в гис жкх Пилотный проект фсс в 2017 году брянск образцы заявлений Положение о закупках по 223 фз на 2017 год образец Карточка образцов подписей в казначействе образец заполнения заявление на куплю продажу автомобиля бланк приказ на контрактного управляющего по 44 фз образец коммерческое предложение образец продажа товара

оформление отчета по учебной практике торг-4 акт о приемке товара поступившего без счета поставщика

бланк заявления на расторжение договора с ростелеком договор на возмещение расходов образец деловое письмо на немецком языке образец разделы проекта по 87 постановлению проект судебного акта арбитражного суда образец соединения букв при письме образец справка об отсутствии кассового аппарата срок действия справки о несудимости в россии складская справка об остатках тмц образец образец обязательства по материнскому капиталу калькуляция на транспортные расходы образец паспорт группы детского сада образец по фгос бланк заявления на льготу пенсионерам по налогу на имущество фары от маза на газель старого образца приходная накладная бланк скачать excel торговая фирма арма заключила с фирмой астраханские арбузы договор поставки книга учета доходов и расходов для ип на усн 2017 образец заполнения заявление о пересмотре заочного решения суда образец бланк штатное расписание на 2017 год оформляем по всем правилам письмо в военкомат от работодателя образец образец отчета об оценке рыночной стоимости арендной платы критически важные объекты постановление правительства договор аренды земельного участка сельхозназначения образец

согласие участника аукциона на поставку товара образец 44 фз форма мед. справки для водителей бланк извещения о дорожно-транспортном происшествии. бланк уведомления о двойном гражданстве 2017 справка об обучении в колледже образец

#9 LarPhozyHah

LarPhozyHah

    Super Veterano

  • Usuários
  • 14515 posts
  • Sexo:Masculino
  • Localidade:San Miguel de Tucuman

Posted 26/10/2017, 00:48

Commander Baclofene En Ligne Precio Levitra 20 Mg Farmacia viagra Buy Female Viagra Reviews
Best Cheapest Price Tadafil viagra Acheter Cialis Original Ligne
Viagra Pfizer Apotheke Cialis Prices Walmart viagra Sale Cheapeast Progesterone In Internet Medication Shop No Doctor Carmarthenshire
buy roche accutane online uk Viagra Temoignages Allergy To Amoxicillin viagra online prescription Is Cephalexin Good For Cellulitis
Antibiotics Double Vision Keflex Cialis 200 Mg In India Genuine Viagra Cheap viagra Viagra Suppliers Uk Buying Cialis On Line Safe Website 400 Mg Viagra
Usa Pharmacy Canadiana Pharmcy In Sarasato viagra Chlamydia Pills Online Abbreviation Viagra Acheter Pharmacie

#10 vapedlok

vapedlok

    Ativo

  • Usuários
  • 326 posts
  • Sexo:Feminino
  • Localidade:Bogota

Posted 26/10/2017, 06:39

Discounts! best us products progect13.jpg Products which fall under this return policy can be returned domestically, as long as they are unused and in the original packaging. No questions asked! If a product that falls under this guarantee is found to be counterfeit, you will get a full refund (shipping costs included). buy.png READ MORE V-neck lightning pattern print long sleeve slimming men's t-shirt ( 11.67 $)Lenovo Moto Z Play 4G Phablet ( 379.99 $)2016 new Industrial retro style Art Pendant light black white Edison light bulb American village lamps Hanging Lamps luminaries ( 60.00 $)Ophir pro 3 tips dual action airbrush gravity paint gun kit with compressor for temporary tattoo nail art 110v,220v#ac090+ac070 ( 104.71 $)Portable 2.5 x dental loupe medical surgical loupes binocular microscope magnifying glasses optical glasses ce approved with box ( 110.40 $)замена передних амортизаторов ваз 21102016 Electronic kit Circuit Board DIY Kit LM317 Adjustable Regulated Voltage Step-down Power Supply Suite Module ( 6.68 $)shopping live первый немецкий телемагазин shopHot Sale New Fashion Women Wallet Hit Color Flowers Printing Zip PU Leather Wallet Long Ladies Clutch Cash Card Purse LL1026 ( 6.10 $)купить аккаунт бателфилд 4Cube TALK79 U55GT-C8 Protective Case ( $5.94 )Bolsos mujer fashion women shoulder bag &messenger bags girl pink vs secret packets traveling bags pouch size 50cm24cm ( 33.91 $)Keyes ZND - 05 Multifunctional Electronic Bricks Inclination Sensor Module Works with Official Arduino ( $1.86 )демпферный шкив коленвала пежо 406Sunny shop fashion skull diamonds women bag crystal ladies evening bag bride tote bag women wedding handbag brand designer ( 65.82 $) 100.png
Discounts! best hair styling cream

progect13.jpg
Products which fall under this return policy can be returned domestically, as long as they are unused and in the original packaging. No questions asked!
If a product that falls under this guarantee is found to be counterfeit, you will get a full refund (shipping costs included).

buy.png

READ MORE
battlefield 1943 скачать торрент +на русском
Cosmetics Vichy. Official website and online store pharmacy cosmetics Vichy
Gray s Shirt ( 51.50 $)
Men's solid color zip fly denim pants ( 24.71 $)
Dver (Igra prestolov)
развертка шкворень газель
Men's simple turn-down collar letter printed short sleeves shirt ( 14.02 $)
GPIO Expansion Breadboard + 40P Rainbow Plat Cable for Raspberry Pi ( $5.51 )
Red Quilted Eco Leather Shoulder bag wZip Pocket ( 106.50 $)
1PC NEW Arrival 6 Colors Popfeel Matte Lipstick Lipgloss Red Wine Bottle Lipstick Matte Waterproof Colorful ( 3.69 $)
Midnight blue leather pointed pump ( 203.28 $) Loriblu
Motorola MOTO X ( 1581 ) 4G Smartphone ( 299.99 $)
220V 4 in 1 Men's Electric Shaver Beard Razors Waterproof Barbeador Rechargeable Shavers Nose Trimmer Hair Clipper Men Face Care ( 41.98 $)
Dreambeauty water repellant canvas wig head for wig making styling and display premium quality wig stand ( 28.00 $)
Beyonce — Naughty Girl


16.jpg
Discounts! 10 makeup products you need

progect13.jpg
Products which fall under this return policy can be returned domestically, as long as they are unused and in the original packaging. No questions asked!
If a product that falls under this guarantee is found to be counterfeit, you will get a full refund (shipping costs included).

buy.png

READ MORE
H588 speed car dvr camera radar detector speed radar combo 2in1 2.7 ( 39.99 $)
шоппинг лайф первый немецкий интернет телемагазин
Earings Promotion Direct Selling Women Brincos Sterling Jewelry 2015 Newest Arrival Peacock Shape Long Tassel Drop Earrings ( 1.20 $)
Horse head mask animal costume n toys party halloween ( 12.22 $)
купить скраб боди блендз
Animal Print Haircalf Leather Belt ( 144.00 $)
Clear heel red leather pump ( 315.62 $) Moschino
2016 new 7 inch screen color video door phone intercom system aluminum alloy camera video doorbell intercom video doorbell 1to1 ( 114.57 $)
Kinglux 6 x 21 Roof BK — 7 Prism Laser Rangefinders with LCD Display 94.59$
поселок красный
Ulefone Vienna Android 5.1 5.5 inch 4G Phablet Corning Gorilla Glass Screen MTK6753 64bit Octa Core 3GB RAM 32GB ROM Fingerprint ID HiFi Cameras 172.59$
Icon Brass and Enamel Armlet ( 117.50 $)
Zanzea women blouses shirts 2016 autumn blusas long sleeve o neck fashion ladies solid asymmetrical tops ( 14.52 $)
Boapt double deck knitted wool real natural raccoon fur pompon hat female winter braid cap headgear ( 24.46 $)
H7 xenon hid kit 55w h1 h3 h4 h8 h9 h11 9005 hb3 9006 hb4 881 h27 lamp for car headlight car styling xenon h7 ( 18.00 $)


26.jpg
Discounts! best product to

progect13.jpg
Products which fall under this return policy can be returned domestically, as long as they are unused and in the original packaging. No questions asked!
If a product that falls under this guarantee is found to be counterfeit, you will get a full refund (shipping costs included).

buy.png

READ MORE
Solid Woven Silk Tie ( 60.00 $)
New sexy white crochet thong one piece swimsuit 2015 strappy high waist swimwear women bodysuit leotard bathing suits monokinis ( 15.00 $)
Argilak Dyurrandon â Game of Thrones
North Korea celebrates rocket engine test
LONGING LY - 250 5.8G FPV 2.4G 6 Channel 6 Axis Gyro 0.3MP CAM Racing Quadcopter With 7 inch FPV Monitor 349.99$
Fayee FY804 Mini Quadcopter-18.49 $
21 fret one pcs wood tiger flame material maple electric guitar neck guitar parts guitarra musical instruments accessories ( 125.55 $)
wwii weapons
XiaoMi Redmi 3 Pro 32GB ROM 4G Smartphone-186.23 $
Pumpkin embossed grained leather large simple pouch ( 200.60 $) Victoria Beckham
Ciclop Desktop Laser 3D Scanner-123.39 $
2x led door warning light for bmw m performance logo projector for bmw e60 e90 f10 f15 f16 f30 m3 m5 f01 f02 gt ( 15.00 $)
KAIDENG PANTONMA K80 RC Quadcopter ( 41.99 $)
магазин резиновой обуви +на краснобогатырской каталог товаров
Fragola patent leather pump ( 379.81 $) Valentino


100bb.png
Discounts! best skin care products reviews

progect13.jpg
Products which fall under this return policy can be returned domestically, as long as they are unused and in the original packaging. No questions asked!
If a product that falls under this guarantee is found to be counterfeit, you will get a full refund (shipping costs included).

buy.png

READ MORE
Sales 480 x 272 4.3 ( 32.70 $)
team fortress 2 jungle inferno update
Car dvr camera video recorder universal hidden dvrs dashcam novatek 96658 wireless wifi app manipulation full hd 1080p dash cam ( 85.70 $)
Vibe - Leather Flap Wallet ( 151.00 $)
Ophir 2 air brush guns with pro tank air compressor 110v 220v airbrush set for model hobby carcaketoys paint _ac090+004a+006 ( 119.37 $)
Modern fashion shopping girls patterns soft tpu back cases cover for iphone 4 4s 5 5s ( 1.40 $)
Brazilian virgin hair straight 4 bundles straight brazilian hair bundles 100gpc human hair extensions brazilian straight hair ( 51.10 $)
Hair Bun Clip In Hair Pieces Chignon Synthetic Hairpieces Bun Extension Donut Roller Hairpieces Postiche Chignon Bun ( 7.08 $)
michael jackson +the experience wii
Xiaomi mi5 case xiaomi mi5 cover nillkin super frosted shield hard back cover case with free screen protector and retail package ( 7.57 $)
2 patterns sheet flying dandelion nail art water decals transfer sticker born pretty bp w13 ( 0.99 $)
датчик положения выпускного распредвала
Full Throttle Classic Stripes OrangeBlack Ballpoint Pen ( 75.00 $)
GTeng T901F 5.8G Real-time Transmission 2MP 2.4GHz 4CH 6 Axis Gyro Quadcopter Speed Up Down 89.99$
Blue Water Wave Effect Ripple Projector 3W Led Stage Light for Party Disco Light DJ Show Home Entertainment KTV Background ( 18.74 $)


15.jpg

#11 Miguceamma

Miguceamma

    MiguPenjisse

  • Usuários
  • 11724 posts

Posted 26/10/2017, 08:14

Amoxicillin Sulbactam Injection Stability Levitra Bayer Prezzo levitra 40 mg samples Canidian Pharmacies




0 user(s) are reading this topic

0 membro(s), 0 visitante(s) e 0 membros anônimo(s)

IPB Skin By Virteq