PHP: not saving apostrophe - php
I have a php page that saves some data to my database. It works with all strings with special characters (. , ? !) but it doesn't work with apostrophes (').
This is my php:
$message = trim(strip_tags($_REQUEST['message']));
$safe_variable = mysqli::escape_string($message);
$i_sql = "INSERT INTO tableName ( id_user, username, message) VALUES ( '".$id_user."', '".$username."', '".$safe_variable."')";
$i_res = mssql_query($i_sql);
I've tried with and without this line:
$safe_variable = mysqli::escape_string($message);
And I've read that I should use mysql_real_escape_string but that it is no longer supported and I should use mysqli::escape_string instead.
What am I doing wrong in my PHP or what should I be using to be able to save apostrophes?
Note:
$message is I'm when I test.
escape_string() cannot be called statically with mysqli::escape_string($message)
Furthermore mssql_query($i_sql); doesn't make any sense here as it looks like your're using mysql as db.
The code can be fixed like this:
// This is the object that represent the connection to the db
$conn = new mysqli( 'localhost', 'user', 'password', 'db_name');
$message = trim(strip_tags($_REQUEST['message']));
$safe_variable = $conn->escape_string($message); // fixed here
$i_sql = "INSERT INTO tableName ( id_user, username, message) VALUES ( '".$id_user."', '".$username."', '".$safe_variable."')";
$i_res = $conn->query($i_sql); // fixed here
The above, of course, assuming you're using mysql as database.
Anyway I would strongly suggest to use prepared statements instead of escaping strings.
Related
Is the in_array function a safe way of blocking code injection/sql injection?
If i have a php file which is receiving a $_GET['value'] is it safe from sql injection or code-injection for me to start my php file with if (in_array($_GET['value'], $allowed_values);) { /* normal page code handling the $_GET['value'] */ } else { unset($_GET['name']) } $allowed values is obviously an array of all values which i am expecting as safe for $_Get['value']. Is this still unsafe? Thank you.
Yes, that's a common and safe technique that can be used in situations where query parameters can't be used. For instance, if the value will be used as a table or column name, you can't provide it as a query parameter, you have to substitute it directly into the SQL string. Whitelisting like this is the recommended way to ensure that this is safe.
It depends on the values in the $allowed_values array, and how you are interpolating the value into your SQL query. For example: $allowed_values = [ 'a word' ]; if (in_array($_GET['value'], $allowed_values)) { $sql = "SELECT * FROM mytable WHERE id = {$_GET['value']};"; } Definitely not safe. It results in the SQL: SELECT * FROM mytable WHERE id = a word; This is a syntax error. Why would you not just use SQL query parameters? Then you don't need to worry if it's safe or not. Query parameters separate the values from the SQL parsing, so there's no way any kind of value can cause SQL injection. You won't have to have an $allowed_values array. You won't have to remember to check if the GET input is in the array. You won't have to worry about quoting or escaping. It's true that query parameters only work for values, that is in place of a quoted string literal or quoted datetime literal or numeric literal. If you need other parts of your query to be dynamic, like the table name or column name or SQL keywords, etc. then use an allow-list solution like you are showing. But the more common case of interpolating dynamic values is better handled by query parameters: $sql = "SELECT * FROM mytable WHERE id = ?"; $stmt = $pdo->prepare($sql); $stmt-execute( [ $_GET['value'] ] );
let's discuss this thing in little details: Your code is like this : if (in_array($_GET['value'], $allowed_values);) { ........... $sql = "SELECT * FROM mytable WHERE id = $_GET['value']"; ........... } else { unset($_GET['name']) } now let's assume, you have some values : the in_array() function will allow only some pre-defined values, you couldn't have the option to take custom user input by $_GET, but as only pre-defined values are allowed,any SQL command will be safe inside if statement. now take this example of $allowed_values array : $allowed_values = ['some details' , 'another details' ,3, ' 105; DROP TABLE mytable;', 22 , 'ok']; If any of these array values have a string that can have potential SQL injection capability, then there will be an issue. but I think you will not put any such string in the array $allowed_values. ( in this above-mentioned example, index 3, ' 105; DROP TABLE mytable;' can delete the table mytable ). else the SQL command will be safe. now you can add an extra layer of safety in the code, by using PDO for any SQL query. (in this example you do not need that, as in_array() function is 100% safe unless you yourself put any malicious code in the array, as per my above-mentioned example). but for other types of user input where you have to do some SQL query depend on the user input, you can use PDO -prepared statement. a PDO example is this : $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare("INSERT INTO photos (username, kname) VALUES (?, ?)"); $stmt->execute([ $username , $kname ]); For more info, try w3school link: https://www.w3schools.com/php/php_mysql_prepared_statements.asp
Bulk insert using PDO and PHP variable containing all database values
I am new to PHP and am trying to update a deprecated code from mysql to PDO. Considering that the variable $insert contains all values to bulk insert such as: ('82817cf5-52be-4ee4-953c-d3f4ed1459b0','1','EM3X001P.1a','04.03.10.42.00.02'), ('82817cf5-52be-4ee4-953c-d3f4ed1459b0','2','EM3X001P.2a','04.03.10.33.00.02'), ...etc 13k lines to insert here is the deprecated code: mysql_connect('localhost', 'root', '') or die(mysql_error()); mysql_select_db("IPXTools") or die(mysql_error()); if ($insert != '') { $insert = "INSERT INTO IPXTools.MSSWireList (ID,Record,VlookupNode,HostWireLocation) VALUES ".$insert; $insert .= "ON DUPLICATE KEY UPDATE Record=VALUES(Record),VlookupNode=VALUES(VlookupNode),HostWireLocation=VALUES(HostWireLocation)"; mysql_query($insert) or die(mysql_error()); $insert = ''; } here is the new code: try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //set the PDO error mode to exception // prepare sql and bind parameters $stmt = $conn->prepare("INSERT INTO IPXTools.MSSWireList (ID, Record, VlookupNode, HostWireLocation) VALUES (:ID, :Record, :VlookupNode, :HostWireLocation)"); $stmt->bindParam(':ID', $ID); $stmt->bindParam(':Record', $Record); $stmt->bindParam(':VlookupNode', $VlookupNode); $stmt->bindParam(':HostWireLocation', $HostWireLocation); // insert a row // loop through all values inside the $insert variable??????? how? $stmt->execute(); } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } $conn = null; During my research I found an excellent post: PDO Prepared Inserts multiple rows in single query One method says I would have to change my $insert variable to include all the field names. And other method says I dont have to do that. I am looking at Chris M. suggestion: The Accepted Answer by Herbert Balagtas works well when the $data array is small. With larger $data arrays the array_merge function becomes prohibitively slow. My test file to create the $data array has 28 cols and is about 80,000 lines. The final script took 41s to complete but I didnt understand what he is doing and I am trying to adapt my code to his. The PHP sintax is new to me so I am strugling with handling the arrays, etc... I guess the starting point would be the variable $insert which contains all the database values I need. Do I need to modify my $insert variable to include the field names? Or I could just use its content and extract the values (how?) and include the values in a loop statement? (that would probably execute my 13k rows one at at time) Thank you
If you have 13k records to insert, it is good for performance to do not use prepared SQL statement. Just generate SQL query in format like this: INSERT INTO IPXTools.MSSWireList (ID, Record, VlookupNode, HostWireLocation) VALUES ('id1', 'r1', 'node1', 'location1'), ('id2', 'r2', 'node2', 'location2'), ... ('id13000', 'r13000', 'node13000', 'location13000'); What you may do for it - use maner of your legacy code. Your try block will looks loke this: try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->exec($insert); }
Storing entire json string in mysql db using php
I am trying to store a string of data in mysql using a text field, but I keep getting an error, even though if i try putting the entire string through phpmyadmin it works fine. Error in the consult..You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\"0\":\"kevin9anderson\",\"1\":\"altitudedesign\",\"2\":\"JobSearchLO\",\"3\":\"' at line 1 $list = addslashes(json_encode($screen_names)); $datetime = date('Y-m-d H:i:s'); $query = "INSERT INTO `db`.`lists` (`id`, `list`, `date`) VALUES (NULL, $list, '2014-12-16 03:29:17')"; # execute the query. $result = $link->query($query) or die("Error in the consult.." . mysqli_error($link)); // WHAT IS CURRENTLY IN $LIST IS (without slashes): /*{"0":"kevin9anderson","1":"altitudedesign","2":"JobSearchLO","3":"xenastar","4":"bukhieade","5":"kundukundu","6":"aqbsoft","7":"blurDesigns","8":"LamidiRazaq","9":"Pixeltw1","10":"topsigsites","11":"akin_wal3","12":"Weisjvo","13":"BSEtech","14":"MikeMalott","15":"TMoellegaard","16":"TheWebBlend","17":"Segko","18":"RevConcept","19":"DesignBumper","20":"TextureDude","21":"temmyify","22":"lyndon_john","23":"KuponoProdVideo","24":"Rachaelparrott","25":"bassey569","26":"acex_hq","27":"CreatorsShop","28":"pybcc","29":"themeyourweb","30":"gpdceo","31":"boyd_mckay","32":"indranilchanda","597":"ajibade_jide","34":"twistedtar","35":"mavtrevor","36":"CheapMattress2","37":"alennwebmaster","38":"Cancun_Paradise","39":"Ambitious1s","40":"edisiblogger","41":"delords","42":"Brugbart","43":"KlassSeo","44":"goofy_is_tubguy","45":"BuyFXsignals","46":"Promo_Assistant","47":"kopphandel_de","48":"Diane_Comeau","49":"techcrates","50":"D2DLondon","51":"Sanjaydhawan512","52":"1bestcellphone","53":"39THSTREETBOYZ","54":"VaptechData","55":"krstenstwrt","56":"BenArthur2","57":"SharpPointBooks","58":"reneeaccounting","59":"jawjuhboy706","559":"wwwfunmoviescom","61":"AUSTINSFINEST11","62":"sitelph","63":"wongcody","64":"replicawatchesu","65":"SashaXarrian","66":"lexxiocom","67":"yayasworld11","68":"JMDD_Web","69":"webgeeksolution","70":"JoshSames","71":"ImajPhotoDesign","72":"clearstart1st","73":"BaileyW2B","74":"KayCockrell6238","75":"ctementor4","76":"samthaboss","77":"NnamdiOkolie","78":"MinimalWP","79":"Itsme_Amos","490":"Iyanuadebo","210":"Kolliga_","82":"sireprince","591":"ayodabs","84":"ViaMylove","85":"MicroWebWorkers","86":"Brodericktgv","87":"Eneidaonc","88":"Kunledway","618":"anjorlah","90":"Godwinask4","91":"Killmylove","92":"lychandom","93":"babatunde2u","94":"AtinaroE","95":"AbudullahiKatu","96":"ty62301","97":"lyft","98":"ThePumaGooner","99":"Femmostical","100":"_aIterations","101":"importunateIy_p","102":"amazed_n1nj4","103":"Hargyberdeyteew","104":"Mauriem88","105":"ronaldadomako","106":"kaffybean","107":"Pretteboi","108":"realemilykopp","109":"slimbabe05","110":"TheArsenal71","111":"femsalinas559","112":"vetabatonline","113":"bizibim","114":"Ms_br33zy","115":"Vickyhans101","116":"m_bash101","117":"Oluwadabbie","118":"SojiDanielx","119":"Aliveinhim19","120":"OLUWAJAMISI","121":"EminowaOluwatoy","122":"oyeleyeolamide","123":"adeogunolawale","124":"Adegoketweets","125":"kejikujjo","126":"mz_ody","127":"JdougieP","128":"Arsha_023","129":"DIEYNA_D","130":"ThePmix","131":"Dyn4casie","132":"jibademike","133":"tomifolawe","134":"fezatudok","135":"WisconsinGunner","136":"ENERGY1069","137":"Mika80m679","138":"damisiabijo","139":"kelvin_tyga","140":"MissssyDee","141":"AfricanDad","142":"FyinInc","143":"Mannyfuntimes","144":"balogunkasim","145":"shestiti","146":"Tunde_rabbi","147":"henry2166","148":"Smokey_Dimples","149":"DaParadise","150":"___andreasG","151":"Hippolite_Jnr","152":"_OLUMO_","153":"rees4life","154":"Adesholac","155":"ajibigad","156":"Bailey_Koren","157":"OmotokeAkanbi","158":"Haydeybahmboh","159":"folorunshosodi1","160":"Maffy_BeatzZ","161":"Iam_bussie","586":"TunjiAdeyeri","163":"labsigirl","164":"khlinton1","165":"topz2k480","166":"firmfaithphc","167":"MULLERFORBES","168":"I_AM_SPLASH","169":"DUUMZY","170":"i_am_Gsax","171":"LeaMarcrum8157","172":"Agags_P","173":"Swift_stunner","174":"Esterzeyl","175":"charmingcharlet","176":"MessinWithJess","177":"arsenalquotes","178":"IrishRecRoom","179":"LadyArseVN","180":"RedWhiteScarf","181":"Football_Speak","182":"Phaetonv2","183":"OPosts","184":"WalexyGooners","185":"luvabric","186":"Ghana_Royalty","187":"AiiShaa_H","188":"Maverickaizer","189":"An4ndPaTiL","190":"JustEmulate","191":"lilnelz","192":"isijay","193":"Gfad_surutu","194":"AFC_Fanbase","195":"Mz_seun","196":"EldridgeMontfor","197":"just_tomi","198":"FaithInWenger","199":"kaliejay981","200":"LaurynBillinger","201":"oniff_tommy","202":"DuntressDaynger","203":"itsJazzyF","204":"koovidcom","205":"4lex_chan","206":"ArsenalHQ","207":"Arsenal_Blogger","208":"RepFlyAsMe","209":"SociallyMilTown","211":"cheespnkprncess","212":"Rabark","213":"pau_LARGE","214":"shreysudan","215":"JamieRorison","216":"Gunnerian","217":"thegooner","218":"Oluwadamilare33","219":"kellyteigan","220":"BillingsWay","221":"Whelts","222":"TJRministries","223":"itsWeze","224":"ARSENALIFE","225":"deshola0532","226":"Tunedey61889241","227":"agate911","228":"nobbleweskey","229":"CoolDewale","230":"Barackobi","231":"Iliyasuzak","232":"b1sh4l","233":"pumafreak100","234":"tomic_L8y","235":"isalako","236":"jackelinebrown","237":"Sherrimdezr","238":"vydami","239":"Arsenal_N5","240":"Lolitamvjti","241":"celebmyswagcom","242":"Denmantrj","243":"aliciaskeeter","244":"ArsenalMOTM","245":"sabrinanusrat94","246":"bala_chn","247":"sneakerwatchcom","248":"gooneramaan","249":"Arsenal_Fanpage","250":"KatiesGooner85","251":"FCInterBlogGFT","252":"YoBenBen","253":"YusufAFC","254":"LargeKatt","255":"SexyFootball_EU","256":"Yockney","257":"OAlmasri","258":"Mysterious_Mee","259":"Timi1776","260":"tha3pLe","261":"Boluwatifesoye","262":"TheGoonerGirls","263":"Nherun","264":"arsenalnewsonly","265":"Mallamofficial","628":"DONJAZZY","267":"__nobility","268":"slimdeeone","269":"nickinala","270":"footballfreebet","271":"amyungace","272":"BishopAy0","273":"GunnersForever_","274":"Antondub","275":"shapezB","276":"01EdCooper","277":"mz_smurfz","278":"LadGooner","279":"thegoal_line","280":"catie_beauty1","281":"_Omoty_","282":"riah_reese","283":"Temmytee92","284":"BaMluvzBR33zY","285":"Retro_Chicago","286":"cityboykidmax","287":"zeegenius","288":"mal_com_XX","289":"ThaAlumni","290":"led110401","291":"FrancieBlackmon","292":"sm000th__gentle","293":"aditoteles","294":"followbackarmy_","295":"iRaptunes","296":"Miss_Timmah","297":"OnlineHYPE","298":"Mz_Stupendous","513":"BossRicky01","300":"Walegzytwet","301":"ark_PR","302":"sexy_veronicaa","303":"Todaysgist","304":"AjeigbeOluwagbe","305":"Iam_Dipor","306":"Mskoyin","307":"Numb_Tweets","308":"Sarphurhat","309":"Futa_weyrey","310":"Amara_USA","311":"yo_itsuti","312":"Prof_guage","313":"Lyricalwizzy","314":"tusheghe","315":"__Faaiza","316":"SeyiPetersBLOG","317":"galacticoHD","318":"Danbros_Media","319":"Car_Ur_Day","320":"Heart4luvEva","321":"kaystrit32","322":"femipeters8","323":"olukayodeoluda1","324":"mesho_bengahzii","325":"I_amAugustus","326":"OscaRankinG","327":"ThatGirl_Palsa","328":"iRock_LV","329":"iam_dannex","330":"bj_abruzzi","331":"Frosh_Pikin","332":"NigeriaParrottv","333":"NaGodwin","334":"Alpha_red1","335":"Bristoltlf","336":"Its_Hoe_K","337":"banjoesan","338":"5ynest_official","339":"all4allNuel","340":"mayream","341":"WETRENDN","342":"FarahNeoteric","343":"jtunga7","344":"rosek1ss","345":"JasminejoyVinni","346":"DilmaMahalia","347":"TRENDS_NG","348":"Bindervrk","349":"doo_esty","350":"adelacuna001","351":"ol_dmm","352":"opelnoni85","353":"JONABOY4","354":"iam_dasaint","355":"Khuunley","356":"_TEENSY_","357":"ShervinSinatra","358":"SinatraMGMT","359":"Qs_imole","360":"fafazi6","361":"YiOliphantino","362":"Fortunesanumi","363":"think_awkward","364":"CalebSumners","365":"coldett","366":"DizzyDortch","367":"THOSEGOODVlBES","368":"DJNARESH","369":"CuteNotesPage","370":"SG_Zu","371":"GODJTrap","372":"BeatingHerUnder","373":"NaDiah_Ash","374":"Lettie_BoyBitch","375":"Thereallaylow","376":"LovableNotebook","377":"officialbskip","378":"Officialsed_","379":"FreakingTrue","380":"EcheMadubuike","381":"TweetLikeGirIs","382":"Welly_Marshall","383":"femaIes","384":"loyal24k","385":"SammyTellem","386":"OfficialSeanB_","387":"_Kyle_Osborne_","388":"NateTheHitmaker","389":"YepillPosts","390":"squiresthetruth","391":"IamAlejandro98","392":"ianthony_H","393":"LZODADON","394":"SaulSorianopxv","395":"Araya_Hope____","396":"MrSmoothNerd","397":"bten_2go","398":"GuinnCarusoxkk","399":"AZEYBOZZ","400":"Mizz_debbie","401":"IsrealKorede","402":"Emmameks","403":"changeam","404":"Tomboy500","405":"Teetwinkles","406":"ILuvSkonk","407":"yemiedabs","408":"BonganiNdlovu_","409":"niyishandle","410":"Sizzune","411":"phemyfreshguy","412":"BabyZee_02","413":"ispeak_sarcasms","414":"ifeaboyeji","415":"JusTheOsh","416":"Ohlunikeh","417":"RyanKnowsGirls","418":"LilSwaggaBoy910","419":"i_am_mykhel","420":"The_Sports_Mind","421":"caduchii","422":"bee_jaybaba234","423":"Cecy_dunsy","424":"OmoMummyGang","425":"Adeeheart","426":"nuteIla","427":"tbhiloveboobs","428":"RealLilGodSODMG","429":"JordanPosts","430":"WorldStarHumour","431":"HotBoyGreedy","432":"obinnacharle","433":"janedanny213","434":"posh_E","435":"philtee1990","436":"IbukunOladeinde","437":"miz_becey","438":"arnoldbaze","439":"abisolajegede","440":"mandy_amazing","441":"_AnjorLaH_","442":"MELDAH_","443":"barrack08","444":"sleekdami","445":"holashegz","446":"iamHaustin","447":"DOLABOMI_","448":"MISTERR_TJ","449":"Buffy_Lautt","450":"topeolaide1","451":"babakemi2010","452":"Amy85Kemi","453":"sahizzle4lyfe","454":"MzStar_Emmy","455":"doyinlicious","456":"iam_freewindz","457":"hinnodz","458":"BolajiHawanat","459":"prizzy_BMR","460":"CeoRnL","461":"Evrybdyluv_Vito","462":"iamKobz","463":"O_oluwadamilola","464":"socialempireent","465":"TheYebowale","466":"MI_Abaga","467":"Iam_noLimits","468":"I_AM_AMAZON","469":"ideevaeva","470":"nwadiutook","471":"steezyTic","472":"Tommy_OC407","473":"Crhedrys","474":"zerah01","475":"Doc_Ade","476":"chronikquotes","477":"pwettiefreda","478":"nifex_magnum","479":"MikeDelevante","480":"ms_bhilz","481":"Shytonsax","482":"yvonne__johnson","483":"T_whizzy101","484":"debonairr","485":"NAMELESS773","486":"reelifeish_210","487":"Ebi_gurl","488":"Guze01","489":"Bluefairy_D","491":"MTN_62130","492":"internal_1","493":"babatundetohib1","494":"thayorbelle","495":"Syndicate61","496":"Tontoblogpost","497":"drboyd03","498":"somadina_arthur","499":"Enginervic","500":"adeboye_adeboye","501":"Cherrylynn991","502":"Orisafunfun","503":"dherine_91276","504":"Mr_Amechi","505":"Makinsworld","506":"Seyi__","507":"FrancescaCiccol","508":"ChandaVarela","509":"DaileEsslin","510":"GenoveraHubch","511":"MarybethKuhnke","512":"omomo14","514":"UzochukwuVera","515":"Plux_Official","516":"Teedeemarley","517":"Shigoopompey","518":"Hofemi","519":"NinjaWolfzHD","520":"martinezwoowwoo","521":"itz_Asod","522":"dixonsamanta","523":"iamdave_8","524":"AyodeleOladunni","525":"babs124qu","526":"Leye4chris","527":"Gem_Olabisi","528":"solabalogun14","529":"Pelzyking","530":"ayobellzz","531":"MrBlackRooney","532":"Eniholha","533":"thenataniel","534":"femi_colin","535":"Hesomatics","536":"TemidayoTemm","537":"DondeonBeke","538":"meedaysweet","539":"Dame_Tania","540":"bukolaokunfolam","541":"tadegboye","542":"Mojipearl","543":"mzz_ozil","544":"RealDarey_Juelz","545":"MrsGiroud","546":"blackyafrika","547":"BiyiKay","548":"leye4real","549":"Yug_isaac","550":"Bhusearyour","551":"HuntellaDotNet","552":"SeriuzBlack","553":"iamdetty","554":"Ay_Adams","555":"_MsJ__","556":"sexychacha_","557":"Ayomidejoe","558":"TrendyShrink","560":"bolagunner","561":"awalitenzube","562":"ogboye_olabisi","563":"jenny_peperempe","564":"MAFGUNTS","565":"MzAyeni","566":"sleekprincess","567":"wazobiagooners","568":"shakarababyy","569":"StudyLuck","570":"miz_khumsy","571":"barack_obash","572":"JimmyTheNerd_","573":"Elle_Toh_Cute","574":"Kassandra_josh","575":"BenOsas007","576":"pweetyboular","577":"isurboi_lance","578":"O_funmibi","579":"pheyimy","580":"ArsenalNL","581":"SoMarkHarmon","582":"Tudamhot","583":"AhmsBaba","584":"Footamb","585":"kylexdavid","587":"lome111","588":"Fapetuemma","589":"Shegsybaba","590":"haybeeone","592":"fhorlarr","593":"biggestdam","594":"tonyblackrooney","595":"pweetymoyo","596":"goonerdaily","598":"adeoyeomotayo","599":"Icelytweets","600":"hoeyn","601":"eroshypnosis","602":"YemojaNews","603":"deedammo","604":"lancelot187","605":"Jay_Trask","606":"celebfrancis","607":"Vospeaks","608":"kunleafolayan","609":"erijeniwt","610":"abssytemi","611":"tolaoguntoyinbo","612":"IllustroP","613":"icyoo7","614":"_attackk","615":"shallomills","616":"Fragiletimbz","617":"OlufemiMakinde","619":"OneBlackBoy","620":"Daetunji","621":"justdaisynow","622":"Aqueouz_B","623":"tobisnoop","624":"Yknight89","625":"ItsOnly_1Dee","626":"noah_riddle","627":"fapetuseun"} */
Me to OP: Try what FuzzyTree said (NULL,'$list','2014-12-16 03:29:17') quoting $list or '".$list."' OP to me: tried it earlier, it didn't work. but the one you just added did. put it as an answer? Encapsulate the $list variable in quoted format, since you're passing JSON string. (NULL, '".$list."', '2014-12-16 03:29:17')
You really should consider using PDO which will allow you to use a prepared statement with parameters. You don't need to worry about escaping parameter values: $pdo = new PDO('mysql:host=localhost;dbname=mydb', $username, $password); $stmt = $pdo->prepare('INSERT INTO `db`.`lists` (`list`, `date`) VALUES (:list, :date)'); $stmt->bindParam(':list', json_encode($screen_names)); $stmt->bindParam(':date', $date); $stmt->execute(); As you've tagged your question 'mysql', this will help you determine your connection string: http://php.net/manual/en/ref.pdo-mysql.connection.php And, for more on PDO and prepared statements: http://php.net/manual/en/pdo.prepared-statements.php
$list = addslashes(json_encode($screen_names)) In your $list at beginning and end added slash because of addslashes() used so, it did not made proper string. Changed your insert query to following: $query = "INSERT INTO db.lists (`id`, `list`, `date`) VALUES (NULL, '".$list."', '2014-12-16 03:29:17')"; it stored your json string within quote.
PHP: Error when inserting quotation marks in mySQL
I insert a text variable in a mySQL table. Everything works fine except in the text is a quotation mark. I thought that I can prevent an error by using "mysql_real_escape_string". But there is an error anyway. My insert statement: $insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')"; mysql_real_escape_string($insertimage); The error message: MySQL Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1413885955514','10')' at line 1
You need to escape data that you are putting into the SQL so that any special characters in it don't break the SQL. You are escaping all the special characters in the final string of SQL; even those that you want to have special meaning. If you want to use your current approach, you would do something like this: $filename = mysql_real_escape_string($filename); $text = mysql_real_escape_string($text); $timestamp = mysql_real_escape_string($timestamp); $countdown = mysql_real_escape_string($countdown); $insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')"; … but the PHP mysql_ extension is obsolete and you shouldn't use it. Modern APIs, such as mysqli_ and PDO support prepared statements, which are a better way to handle user input. This answer covers that in more detail.
The problem with your current code is that you have not correctly escaped the values you're trying to enter into the table. Better still is to avoid the mysql_* function family entirely. Those functions are now deprecated and bring security risks to the table (along with other concerns). You'd be better to use PDO and Prepared Statements, for example: $db = new PDO('param1', 'param2', 'param3'); $sql = $db->prepare( 'INSERT INTO `image` (`filename`, `text`, `timestamp`, `countdown`) VALUES (:filename, :text, :timestamp, :countdown)' ); $sql->execute( array(':filename' => $filename, ':text' => $text, ':timestamp' => $timestamp, ':countdown' => $countdown ) );
mysql_real_escape_string($insertimage); You will have to use this function to each variables before writing the query. $filename = mysql_real_escape_string($filename); $text = mysql_real_escape_string($text); $timestamp = mysql_real_escape_string($timestamp); $countdown = mysql_real_escape_string($countdown); $insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')";
Try this , $insertimage = sprintf("INSERT INTO image(filename,text,timestamp,countdown) VALUES ('%s','%s','%s','%s')", mysql_real_escape_string($filename), mysql_real_escape_string($text), $timestamp, $countdown); Why, because your inputs vars must be escaped before using them in sql then execute your sql.
Escaping the entire query is not useful. In fact, right now, you are causing syntax errors by doing so. You should be escaping the individual variables that you inject into it.
Try this: $filename = mysql_real_escape_string($filename); $text = mysql_real_escape_string($text); $timestamp = mysql_real_escape_string($timestamp); $countdown = mysql_real_escape_string($countdown); $insertimage = "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')"; mysql_query($insertimage);
Concat the php variables like this: $insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES (" . $filenamec . "," . $text . ", " . $timestamp . ", " . $countdown . ")"; with the respective single quotes in those that are text fields i.e: "... '" . $text . "' ..."
Can't insert link into mysql database
Here is a part of my insert code that troubles me: $recepient="test#email.com"; $text="Please track: http://wwwapps.ups.com/WebTracking/processInputRequest?HTMLVersion=5.0&loc=en_US&Requester=UPSHome&tracknum=123456789&AgreeToTermsAndConditions=yes&ignore=&track.x=24&track.y=9"; $date="2013-05-03 08:12:20"; $through="mail"; $status=1; $q = "INSERT INTO `messages` (`recepient`,`text`,`date`,`through`,`status`) VALUES('".mysql_real_escape_string($to)."','".mysql_real_escape_string($text)."','".date("Y-m-d H:i:s")."','".mysql_real_escape_string($rowuser['through'])."','".intval($status)."')"; try {$db->query($q);} catch(PDOException $ex) {echp" Error: ".$ex.);} If I remove the link from the $text variable I can see the data added to the database. But in the way I need it to add with the link - the script stops not reporting any errors.
use PDO's powerful prepared statements: $q = "INSERT INTO messages (recepient,text,date,through,status) "; $q .= "VALUES (:to,:text,:date,:through,:status)"; $dbinsert = $db->prepare($q); $dbinsert->execute(array( ':to' => $recipient, ':text' => $text, ':date' => $date, ':through' => $through, ':status' => $status)); This should do it. Let PDO take care of escaping.
It would appear that you're mixing database libraries, or have wrapped things yourself. If you're using something like mysqli or PDO for the ->query() call, then mysql_real_escape_string() will NOT work. m_r_e_s() requires an active connection to the DB to operate. Connections established in mysql, mysqli, and PDO are NOT shareable between the libraries. That means your m_r_e_s() calls will returning a boolean FALSE for failure, and your query will actually look like: $q = "INSERT .... VAALUES ('', '', '', etc...)";
What's the size of the text column in the database? It's mostly not the reason but I've noticed that your $text is 190 char long.
The problem is with the "?" sign in the $text variable. It is being treated as a placeholder when it is put into the query, and the $db->query expects an array of variables. The solution is to use a placeholder instead of a $text variable and submit $text variable as params: $ar[0]=$text; $q = "INSERT INTO `messages` (`recepient`,`text`,`date`,`through`,`status`)"; $q.= " VALUES('".$to."',?,'".date("Y-m-d H:i:s")."','".$through."',".$status.")"; $db->query($q,$ar);