PHP - Handling Apostrophes
I am inserting last names into the database using mysql_real_escape_string(), and outputting the data into a textbox using addslashes().
When I try to display O'Brian "O\" is displayed in the text box. The name is saved corretly as O'Brian in the database. I am printing the string like this: Code: [Select] echo "<input type='text' value='" . addslashes($customer['lName']) . "' blah blah..."; anybody have any ideas? Similar TutorialsHi. Apologies in advance if this is a stupid question, but hoping someone can help. I'm trying to help a friend who is running a photo gallery script on his website. The developer of the script is not supporting it any longer and I have limited php knowledge. I've been told by his ISP that the script will only work on PHP version 5.6. The problem he has is that when he is adding descriptions to the photos via a back end form, if he uses an apostrophe as in O'Sullivan for example, when he saves the entry, the description text does not show at all. This seems to be a conflict with the php language. Is there a line of code that I can add to the config file or somewhere that will get around this problem? Thanks in advance for any help you can give. i have a textarea in my form. If my validation script detects an error it will send it to the same page with what they had in that textarea encoded in the url. The script detects the $_GET['variable'], decodes it, and stores it as the default in the textarea so they don't have to retype it all again. The problem is the apostrophes add 7 slashes when it gets added back to the textarea. heres the relevant snippets.. Code: [Select] <?php function clean_post($variable) { $cxn = mysqli_connect($host,$user,$passwd,$dbname) or (mysqli_error($cxn)); return mysqli_real_escape_string($cxn, strip_tags($variable)); } $description = clean_post($_POST['description']); $description = str_replace(array('\r\n', '\r', '\n'), ' ', $description); $description = urlencode($description); $base = "http://mywebsite.com/"; $url = $base."?mm=1&tt=".$description; $location = "Location:".$url; die(header($location)); and then to output it in the textarea Code: [Select] <?php $tt = urldecode(strip_tags($_GET['tt'])); <textarea id=location name=location maxlength="140" > <?php echo $tt; ?> </textarea> and this is what my url ends up looking like http://mysite.com/wordpress/?mm=3&tt=what\\\%27s+the+deal%3F and this ends up in my textarea "what\\\\\\\'s the deal?" This is driving me nuts and I'm hoping someone can help me figure it out. I have a site with PHP/MySQL. I have a form where people can submit a comment. This comment then goes into a MySQL database and gets displayed back on another page of the website. NOTE: I put this question in the PHP Forum because I think the problem is happening somewhere BEFORE the info gets entered into MySQL. But of course, I could be wrong. The problem is that some of the comments are coming in with a "\" in front of apostropes, but NOT ALL OF THEM (which is really confusing me). For example, someone entered this comment which shows in the MySQL database exactly like this... I predict Lena's gonna win a lifetime Grammy. It's long overdue. Someone else entered a comment which shows in the MySQL database exactly like this... can\\\'t wait to see first pics of the next addition. Congrats! They both have apostrophes in them, but only that second one added those slashes (and 3 of them for some reason). There are more instances of this where some comments have the slashes before the apostrophe and some don't. Anyone know what might be causing this seemingly random insertion of slashes? I am trying to insert product descriptions into a mysql database, however they are failing because of apostrophes in the text. How do I fix this? Everything is working fine except $productdescription $ProductDescription contains, "Record In Stereo Sound, Then Play Back Your Videos Instantly On You Computer. The Sx130 Is Is All About Creativity, With Fun New Scene Modes Like Miniature Effect For Movies, And Fisheye Effect For Artistically Distorted Stills. While You're Having Fun Creating, The Camera's Smart Flash Exposure And Advanced Smart Auto Systems Are Ensuring That Every Image Is The Best It Can Be. Add The Digic 4 Image Processor, 12.1 Megapixels And Canon's Optical Image Stabilizer, And You've Got The Ideal Camera For Making The Good Times Last." SQL Error on insert, "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 're Having Fun Creating, The Camera's Smart Flash Exposure And Advanced Smart Aut' at line 1 " Code: [Select] mysql_select_db("testdb") or die(mysql_error()); mysql_query ("INSERT INTO product (merchantname, producttitle, productdescription, gtin, availability, price) VALUES ('$merchantname[1]','$producttitle[1]','$productdescription[1]','$gtin[1]',''$availability[1]','$price[1]')"); Hi All, I'm working on an X-Cart site. Looking through the pages, any page with an apostrophe in the content is being loaded as an � instead. The sites' char set is UTF-8. Changing it to ISO then creates an issue in itself with bulleted lists. Just wondering if anyone has had the problem in the past and if they have solved it? Any help appreciated. Cheers i'm having problems with apostrophes causing an error on my contact form. I've tried stripslash and also str_replace but i can't get it to work. what am i doing wrong? thanks Code: [Select] <?php if(isset($_POST['email'])) { // EDIT THE 2 LINES BELOW AS REQUIRED $email_to = "test@test.com"; $email_subject = "test"; function died($error) { // your error code can go here echo "We are very sorry, but there were error(s) found with the form you submitted. "; echo "These errors appear below.<br /><br />"; echo $error."<br /><br />"; echo "Please go back and fix these errors.<br /><br />"; die(); } // validation expected data exists if(!isset($_POST['contact_name']) || !isset($_POST['last_name']) || !isset($_POST['email']) || !isset($_POST['telephone']) || !isset($_POST['comments'])) { died('We are sorry, but there appears to be a problem with the form you submitted.'); } foreach($_POST['check'] as $value) { $check_msg .= "Checked: $value\n"; } $contact_name = str_replace("'", "&#039;", $contact_name); $contact_name = $_POST['contact_name']; // required $last_name = $_POST['last_name']; // required $email_from = $_POST['email']; // required $telephone = $_POST['telephone']; // not required $comments = $_POST['comments']; // required $error_message = ""; $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; if(!preg_match($email_exp,$email_from)) { $error_message .= 'The Email Address you entered does not appear to be valid.<br />'; } $string_exp = "/^[A-Za-z .'-]+$/"; if(!preg_match($string_exp,$contact_name)) { $error_message .= 'The First Name you entered does not appear to be valid.<br />'; } if(!preg_match($string_exp,$last_name)) { $error_message .= 'The Last Name you entered does not appear to be valid.<br />'; } if(strlen($comments) < 2) { $error_message .= 'The Comments you entered do not appear to be valid.<br />'; } if(strlen($error_message) > 0) { died($error_message); } $email_message = "Form details below.\n\n"; function clean_string($string) { $bad = array("content-type","bcc:","to:","cc:","href"); return str_replace($bad,"",$string); } $email_message .= "Contact Name: ".clean_string($contact_name)."\n"; $email_message .= "Agency/Company Name: ".clean_string($last_name)."\n"; $email_message .= "Email Address: ".clean_string($email_from)."\n"; $email_message .= "Dates Required: ".clean_string($telephone)."\n"; $email_message .= "Type Required: ".clean_string($check_msg)."\n"; $email_message .= "Any other info: ".clean_string($comments)."\n"; // create email headers $headers = 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); ?> thanks <?php } ?> Hello, im trying to update my database with a paragraph of text in a texbox. The thing is my paragraph has apostrophes Look: Code: [Select] In the run up to the return of the Wilderness, we've released a new wallpaper depicting a green dragon, plus a couple of 'getting started' guides about the Wilderness and free trade. It doesn't want to update my table and it shows the old paragraph. Here is how my update database looks like. <?php if (isset($_POST['Submit'])) { for($i=0;$i<$count;$i++){ $month = $_POST['month']; $date = $_POST['date']; $message = $_POST['message']; $title = $_POST['title']; $monthday = $month[$i]."<br>".$date[$i]; $sql1="UPDATE $tbl_name SET monthday='$monthday', month='$month[$i]', date='$date[$i]', message='$message[$i]', title='$title[$i]' WHERE id='$id[$i]'"; $result1 = mysql_query($sql1); } header("location:update2.php"); } ?> Can someone show me to to make it add the strip slashes to the $message variable. Thanks Alot! Hi there,
I am getting this in a PHP generated email:
ACWA Member/Subscriber: Melody’s Children’s Service
The line of code in the php is:
$subject = "ACWA Member/Subscriber: $membername";
I have tried htmlentitiies, html_entity_decode, htmlspecialchars but nothing seems to work.
I haven't used htmlentities anywhere else in the code for this variable.
Any suggestions?
All advice gratefully received.
onlinegamekey. com/MTGT-Auction.php is the page I'm working on. The problem I'm having is cards with an apostrophe in the name breaks the operation. I am populating the Select Box with the Card Names and those are coming in fine, its not until I try to use the select value to get that specific card data do I have an issue. This query specifically Code: [Select] $quer2=mysql_query("SELECT * FROM auctions WHERE Card_Name ='$cards' Order By Price_Per") or die; I've tried $quer2=mysql_query("SELECT * FROM auctions WHERE Card_Name =" . htmlspecialchars($cards) . " Order By Price_Per") or die; but then I get no data for any card. Here is the page code I'm working with. Code: [Select] <?php $cards = $_POST['cards']; //SELECTING DATA FOR THE DROPDOWN $sql = "Select Card_Name From auctions Group BY Card_Name ASC" or die; $result = mysql_query($sql); ?> <script type="text/javascript"> <!-- var optList; var optsValue = new Array(); var optsText = new Array(); //when the page loads get the original options values and text and store them in arrays window.onload = function() { optList = document.getElementsByTagName("option"); for(var i=0; i<optList.length; i++) { optsValue[i] = optList[i].value; optsText[i] = optList[i].text.toLowerCase(); } } function searchSel(txtSearch) { //clear all the current options document.getElementById("items").options.length = 0; var count = 0; for(var i=0; i < optsValue.length; i=i+1) { if(optsText[i].indexOf(txtSearch.toLowerCase()) == 0) { //match found //add this option to the select list options var newOpt = new Option(optsValue[i],optsText[i],false,false); document.getElementById("items").options[count] = newOpt; count = count+1; } } } function reload(form) { var f1 = document.forms['f1'] var val=f1.cards.options[f1.cards.options.selectedIndex].value; self.location='MTGT-Auction.php?card=' + val ; } //--> </script> <style type="text/css"> body { background-color:#000000; } .row-one { background-color: #666666; font-family: Arial, Helvetica, sans-serif; font-size:12px; font-weight: bold; line-height: 17px; color:#CCFF33; } .row-two { background-color: #333333; font-family: Arial, Helvetica, sans-serif; font-size:12px; font-weight: bold; line-height: 17px; color: #FF0; } .th { background-color:#000000; font-family:Arial, Helvetica, sans-serif; font-size:14px; font-weight:bold; color:#CC0000; padding: 2; } </style> <!-- CREATE FORM & SELECT BOX --> <form method="post" name="f1" action="MTGT-Auction.php"> <select name="cards" id="items"> <option value='0'>Select...</option> <?php while ($row=mysql_fetch_array($result)) { if ($row['Card_Name']==@$cards) { echo "<option selected value='$row[Card_Name]'>$row[Card_Name]</option>"; } else { echo "<option value='$row[Card_Name]'>$row[Card_Name]</option>"; } } ?> </select> <br /> <input type="text" id="txt" value="Card Name?" onfocus="this.value==this.defaultValue?this.value='' :null" onkeyup="searchSel(this.value);" style="color:#000000; font:Arial; font-size:12px; background-color:#e1e1e1;" /> <BR /> <input type="submit" value="Submit" name="submit" /> <input type=button onClick="location.href='MTGT-Auction.php'" value='Reset' /> </form> <!-- CREATE TABLE WHERE DATA GOES --> <table border="1" bordercolor="#000000"> <tr align="center"> <th class="th">Auction ID</th> <th class="th">Card Name</th> <th class="th">Cards Per Auction</th> <th class="th">Auction Price</th> <th class="th">Cost Per Card</th> <th class="th">Date Listed</th> <th class="th">Seller Name</th> </tr> <?php //GET DATA FOR TABLE BASED ON SELECTED CARD & LOOP THROUGH $quer2=mysql_query("SELECT * FROM auctions WHERE Card_Name ='$cards' Order By Price_Per") or die; $i =1; WHILE($row = mysql_fetch_array($quer2)) { if ($i%2 !=0) $rowColor = "class='row-one'"; else $rowColor = "class='row-two'"; echo "<tr $rowColor>" . "<td>" . $row[Auction_ID] . "</td><td>" . $row[Card_Name] . "</td><td>" . $row[Qty_Listed] . "</td><td>" . $row[Price] . "</td><td>" . $row[Price_Per] . "</td><td>" . $row[Date] . "</td><td>" . $row[Seller] . "</td></tr>"; $i++; } //} ?> <?php //QUICK CHECK IS OUR VARIABLE SET??? echo "<font color=\"#FFFFFF\">". $cards . "</font>"; ?> </table> I image this is probably a very common problem & easy fix that has been answered many times, but I haven't found any thing that worked for me so any help.. or links to similar issues would really be appreciated. Thank you, I'm trying to develop a website file manager. I want to allow SSI, and would like to handle it specifically.. Code: [Select] $regexp = "<!--#include\s[^>]*virtual=(\"??)([^\" >]*?)\\1[^>]*\/-->"; if(preg_match_all("/$regexp/siU", $body, $matches, PREG_SET_ORDER)) { foreach($matches as $match) { $includeFile = $match[2]; } } This snippet shows how you would get the included file path in the SSI code of the website body [ the $body tag ], but I don't need to just find it- I want to replace the SSI code with a simpler code in the HTML that appears in the editor for easy management.. Then switch back from my easier code to the actual SSI code.. Example: Replace Code: [Select] <!--#include virtual="/newsManager/output.php"--> With Code: [Select] {INCLUDE=/newsManager/output.php} THEN when the user saves the page, Replace Code: [Select] {INCLUDE=/newsManager/output.php} With Code: [Select] <!--#include virtual="/newsManager/output.php"--> Is there an easy fix or should I just switch to a full blown template engine.. even though this is the only required feature? This doesn't work. Based off what I have seen online, it is suppose to. Basically, this is what I tried, and the quote is what was returned. I have no idea how to get this to work. It should have been pretty standard based off of the PHP documentation. The Xpath idea I got from someone else. Either way if I try to use find element by id or tag name it still returns an empty array, no matter what. Any advice on what I am doing wrong is appreciated. It doesn't matter what URL I try, none of them seem to work. Code: [Select] <?php $school_data = file_get_contents('http://www.infotechnologist.biz'); $doc = new DOMDocument(); $doc->validateOnParse = true; $doc->loadHTML($school_data); $xpath = new DOMXPath($doc); $tags = $xpath->query('div'); echo '<pre>'; print_r($tags); echo '</pre>'; ?> Quote DOMNodeList Object ( ) A form needs to get answers of math quiz, returning numbers, up to 2 digits after the point. In all form examples I noticed the usage of: Code: [Select] ...<input type="text" name="name" /... Cant it be a number? floating or integer? why "text" ? Also, can I limit the form to accept numerical input only or would I need to learn Ajax for that? Once I have the answer, I need to compare it to the correct answer. The method I have in mind is to multiply the answer and the correct one by 100 and compare the integer part. Is there a pre-made function that can do the same? Hi, I have an HTML form created using Dreamweaver and now I need a script to handle the form processing. Basically what I need is for the form data received from the webpage to be organized in an email and then sent to me. I would also like to display a thank you message in the browser so the user knows it was received. I was planning to do this using CGI but a colleague suggested that CGI is old school and nowadays a developer would use PHP for this task. Is PHP the right solution for this project? The examples I have found so far always include the HTML for the form and the script needed to handle it in one file. In my case, I have an HTML form already in place and need it to work with a script to perform the email function. I know I need to set "Action=" on my webpage to point to the PHP script but what would the code look like if no HTML is needed? I hope this makes sense... Thanks for your help! Rob I have a prepared statement that returns an Article from my database. It then binds the results-set to variables. Most of the fields in the query are "required", so I *assume* that I am guaranteed to always get values back for those fields... Is that presumptuous? Here is a snippet of my code... // Execute query. mysqli_stmt_execute($stmt); // Store results. mysqli_stmt_store_result($stmt); // Check # of Records Returned. if (mysqli_stmt_num_rows($stmt)==1){ // Article was Found. $articleExists = TRUE; // Bind result-set to variables. mysqli_stmt_bind_result($stmt, $articleID, $title, $description, $keywords, $heading, $subHeading, $publishedOn, $author, $body, $referenceListing, $endnoteListing); // Fetch record. mysqli_stmt_fetch($stmt); // Close prepared statement. mysqli_stmt_close($stmt); // ???? Is it sufficient to have code like this... Code: [Select] <title><?php echo $title; ?></title> ...or do I need more error-handling?? Hope that makes sense?! Thanks, Debbie Whats the best way to handle database errors. I been using ob_start() stuff to run the code and if a database connection error occurs an variable $error turns to 1 and it displays the error code instead of the normal page that should be displayed when no errors occur. It works but I want to know if there is any better way to manage a db connection error while running a script. Also, how do you manage a problem when like 3 queries are ran to setup a new user account and the last one fails because the db connection drops or something, how would you go about handling a 2/3 query successful? I'm really stuck on how to manage errors if a db connection fails after the first connection is successful. Hey Guys,
Been coding PHP for a while but I always wonder about the right way of doing things. I am building an online community which I want to display to members and non-members. With this each screen will have options that are available for members only. I have set up session variables once a user logged in but its getting really old having to nest if statements on ISSET then again to check the values in the variables if it is set. See example below.
Question 1. Is it ok to session_start(); for all site visitors?
Question 2. If Q.1 is ok then is it ok to set all the session variables upfront with blank values as placeholders. This would eliminate the need for ISSET.
if (ISSET($_SESSION['On'])) { if (in_array($GroupID, $_SESSION['Groups'])) { $IsMember = 1; } else {$IsMember = 0;} } else {$IsMember = 0;}Just wanted to get your thoughts on this. Thank you, Jeremy Hi, I'm a beginner in PHP OOP and I'm with some doubts about the correct way of handling errors in PHP. Look at this function for example: public function deleteFileFromDisk($fileNameToBeDeleted) { $handle = unlink($fileNameToBeDeleted); if (!$handle) { $result = "(this->deleteFileFromDisk) - Error, " . $fileNameToBeDeleted . " not deleted."; } else { $result = "(this->deleteFileFromDisk) - Success, " . $fileNameToBeDeleted . " deleted."; } return $result; } Is this the correct way of doing it, or I can do better than this? Let me add some details of what I'm achieving... I'm running class methods, and I need to control errors in the process. If any call to the object throw an error I need to catch, stop all the process and send an e-mail with the error. Here are the object interactions: $testar_classe = new geoIpImportCSV('geolitecity', 'http://geolite.maxmind.com/download/geoip/database/GeoLiteCity_CSV/'); $testar_classe->downloadAndSaveFile('./', $testar_classe->obtainDownloadFileName()); $testar_classe->uncompressZipFile($testar_classe->obtainDownloadFileName(), '.'); $testar_classe->deleteLine(1, 'GeoLiteCity-Location.csv'); $testar_classe->deleteLine(1, 'GeoLiteCity-Blocks.csv'); $testar_classe->deleteDataFromTable('tabela1'); $testar_classe->deleteDataFromTable('tabela2'); $testar_classe->insertLinesToDb('GeoLiteCity-Location.csv', 'tabela1'); $testar_classe->insertLinesToDb('GeoLiteCity-Blocks.csv', 'tabela2'); $testar_classe->deleteFileFromDisk($testar_classe->obtainDownloadFileName()); $testar_classe->deleteFileFromDisk('GeoLiteCity-Blocks.csv'); $testar_classe->deleteFileFromDisk('GeoLiteCity-Location.csv'); Which is the best way of handle this? Create a new method to take care of the exceptions? There are any examples on how to do this? Best Regards. Hi I'm completely new to error handling in PHP and wanted to ask whether I'm doing it right and, if not, what the right way would look like class DBConnection { public function execute($sql) { $query = @pg_query($this->dbconn, $this->prepare($sql)); try { if (!$query) { throw new DBException(); } } catch (DBException $e) { echo "Query execution failed"; exit; } } } Hello there, I'm having a problem displaying money correctly with php. I have a field called "balance" with the type float(10,2), in this field I have a number store as "34.55" which I can go in and look at within phpmyadmin but when I echo this value on the front-end of the site it is displayed as "34.549999237061" Can someone please help? Regards. Hello, Am writing a script that involves user input. Take an example: a user fills in a wrong username or password at the page login.php, my login processor (processor.php) detects it, how is the error "WRONG USERNAME OR PASSWORD" supposed to be transferred back to login.php. So far I have been using a session variable to transfer the error but am sure there is a better way to do this without displaying the error on processor.php itself. Thanx in advance |