PHP - Help To Remove Duplicate Words After A Comma Explode Function- Select Lists
Hi, i got help earlier with the this code-- exploding a field and getting an array, then inserting the array into a multiselect box-- That part is easy and works fine.
Now the explode function gives an array of words with duplicate words in it: I tried several ways most either give a blank option/value, or the array word.. here is the code: $query = "SELECT DISTINCT property_functionsexperience FROM #__users_profiles WHERE published = '1' ORDER BY property_functionsexperience ASC"; $functionsexperiencelistgeneral=doSelectSql($query); foreach($functionsexperiencelistgeneral as $words) $property_funcexperilist=$words->property_functionsexperience; $wording = explode(', ', $property_funcexperilist); foreach($wording as $funciex) $funcexi=array_unique($funciex); $funcexpList .= "<option value=\"".$funcexi.','."\">".$funcexi."</option>"; $funcexpList .= "</optgroup>"; } $funcexpList.="</select>"; $output['FUNCEXPLIST']=$funcexpList; this code is adapted slightly from the working original that gives the double words-- this code gives a blank, but i think its on the correct track!? Similar TutorialsHey! I have a table and in that table I have a "name" field, and a "description" field. I'm trying to make a tag system for these rows. I'd like to use a denormalized approach because I can't wrap my head around a normalized approach. I don't have a problem adding, for instance, catid_1, catid_2, catid_3 columns and do a WHERE statement to fetch only rows with that particular column IE: $sql = mysql_query("SELECT * FROM tablename WHERE catid_1='categorynameortag' ORDER BY DESC") How would I make it so rather than having individual columns, I can put all that data into one field with comma's. Then also, how would I fetch and display only rows with one of the words in the field? Thank you for your help. hi, now i have something like this: $pizza = "piece1 piece2 piece3 piece4"; $one_word = explode(" ", $pizza); but i want to get 2 words together, like that: $two_words[0]='piece1 piece2'; $two_words[1]='piece3 piece4'; $two_words[2]='piece2 piece3'; $two_words[3]='piece1 piece4'; if it's impossible with explode, then it's fine if you use some other function, i don't care as long as it works. thank you, tastro Hi All, I'm sure there is an easy solution for this but I am unable to find it. I am new to PHP and after a little help... the via data is stored in a database in this format... |51.105166,-1.695971|51.011055,-2.1068|50.945233,-2.617664|||| I'm trying to find a way of loosing the last comma if there are 1 or more entries, any ideas guys. What I'm getting is : Code: [Select] var points = [{location: '51.105166,-1.695971'},{location: '51.105166,-1.695971'},]; What I'm after is: Code: [Select] var points = [{location: '51.105166,-1.695971'},{location: '51.105166,-1.695971'}]; Code: [Select] <?php if($via != null){ echo "var points = ["; foreach($via as $point){ if($point != ""){ echo "{location:"; echo " '".$point."'"; echo "},"; } } echo "];\n"; } ?> Hey, i got this code which takes info from mysql: while ($row= mysql_fetch_array($result)) { $title = $row["alertid"]; $title2 = $row["alerttext"]; $title3 = $row["alertdate"]; $bla = "{\"alertid\":\"$title\",\"alerttext\":\"$title2\",\"alertdate\":\"$title3\"},"; echo "$bla"; } it is displayed like this: [{"alertid":"1","alerttext":"text1","alertdate":"date1"},{"alertid":"2","alerttext":"text2","alertdate":"date2"},{"alertid":"3","alerttext":"text3","alertdate":"date3"},] I wanted to ask, how can I remove the last comma, after date3"}, but keep other commas..? Hi guys, Currently my result displayed a 'comma' at the end Lower Primary English, Math, Science, Chinese, How do I remove the comma which is bold in red? Thank you so much My code Code: [Select] while($row3 = mysqli_fetch_array($data3)) { if ($row3['level_id'] == 2) { echo ''.$row3['subject_name'].', '; } } I have the following script which outputs different results based on weather a result is odd or even, pretty simple. The prblem lies with the very last result ouputted, as you can see from the code it will have a comma trailing it, which causes IE to not display the gallery. Can Anyone advise me on how to remove this last comma/echo the last result differently. Thank you <?php include "config.inc.php"; $num = 1; function checkNum($num){ return ($num%2) ? TRUE : FALSE; } $result = mysql_query( "SELECT photo_id, photo_filename FROM gallery_photos WHERE photo_category= 6 AND promo= 1 "); $nr = mysql_num_rows( $result ); $NumOfRecords = mysql_num_rows($result); while($row = mysql_fetch_array($result)) { $id = $row['photo_id']; $img = $row['photo_filename']; if(checkNum($num) === TRUE){ echo " { src: 'admin/photos/".$img."', dir: 'left' },"; $num++; } elseif ($num == $NumOfRecords) { echo " { src: 'admin/photos/".$img."', dir: 'left' }"; } else{ echo " { src: 'admin/photos/".$img."', dir: 'right' },"; $num++; } } ?> hello all, i have a small problem. i have a bunch of prices in a database like 243.49 and 1,256.22 etc. the problem is that when i try to add multiple prices that one of the fields is over 1000, it is treating it as 1 (i believe because of the comma.) is there a way to remove the comma, but not the decimal if it exists and then add it back to the $total if it is over 1000? Code: [Select] $pamount=$row2['amount']; $total += $pamount; For some reason, this doesn't work:
<?php $string = 'You have a code CODE code of ethics'; while (preg_match("/code\s+code/",$string)) { $string = preg_replace("/code\s+code/","code",$string); } print $string; ?> I don't want to replace all instances of duplicated words, rather, only when the word "code" is duplicated. Throughout my 100mb text file, the word "code" appears duplicated (with varying whitespace between). For example: From this: You have a code CODE code code of ethics. Code code Code green means everything is okay. What is the CODE code code code for the lock. To this: You have a code of ethics. Code green means everything is okay. What is the code for the lock. But for some reason, I cannot get my preg_replace to work? hi folks, i have a variable in which some common words are stored and another variable in which a sentence is stored. I want to remove the common words from the sentence> Is there any way of doing this in PHP? Code: [Select] <?php $common_words = "to, this, all, the, from"; $sentence = "I want to remove all the common words from this sentence"; ?>the final output should be: "I remove common words sentence." Hello again to all I would like to ask if how can i removed the first 3 words on this string? Quote Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque hendrerit accumsan turpis, vitae rutrum quam cursus id. Sed quis pulvinar eros. Integer vel tellus turpis. Donec tortor dolor, convallis in mollis et, rhoncus eu lacus. Etiam quam risus, fringilla ac tempor in, congue vel felis. Mauris eu luctus augue. Fusce nisl neque, convallis a posuere a, ultricies et metus. thanks in advance Dear all, I want to remove all lines less than 3 words longs so I can stuff the rest into a db. Can somebody help me? Thank you in advance I have written code in php to connect and insert rows into a MSSQL database. i used odbc to connect database.user can enter his details through the form. after submitting the form the details are getting stored into a database. while inserting rows into a database am not trying to insert duplicate values . for this i have given if conditions.these conditions are able to notice the user cname and name exist in the database if the same name exist. but the else part after these conditions are not working i.e rows are not getting inserted. i put everything inside the while loop. how can i correct it? This is my php code. $connect = odbc_connect('ServerDB','sa', 'pwd'); //connects database $query2="select count(*) from company";//this is needer for loop through $result2=odbc_exec($connect,$query2); while(odbc_fetch_row($result2)); { $count=odbc_result($result2,1); echo "</br>","$count"; } $query1="select * from company"; $result1 = odbc_exec($connect, $query1); # fetch the data from the database while(odbc_fetch_row($result1)) { $compar[$count] = odbc_result($result1, 1); $namearray[$count] = odbc_result($result1, 2); if($compar[$count]==$_POST['cname']) { echo "<script> alert(\"cname Exists\") </script>"; } else if($namearray[$count]==$_POST['name']) { echo "<script> alert(\"Name Exists\") </script>"; } else { $query=("INSERT INTO company(cname,name) VALUES ('$_POST[cname]','$_POST[name]') "); $result = odbc_exec($connect, $query); echo "<script> alert(\"Row Inserted\") </script>"; } } is this possible? Hey guys, not sure what's gone wrong here, but this displays the select query twice on my page. Code: [Select] <?php $result = mysql_query("SELECT * FROM members WHERE Username='$_SESSION[Username]'") or die(mysql_error()); while($row = mysql_fetch_array( $result )) { echo '<b>Resources</b><br />'; echo 'Wood: ' . $row['res1'] . ' <br />'; echo 'Iron: ' . $row['res2'] . ' <br />'; } ?> Displays as: Resources Wood: 2000 Iron: 1000 Resources Wood: 0 Iron: 0 The first set of numbers are correct, but I'm not sure where the second lot are been called from? Thanks in advance. Ok so what I have is a list of 32,000 IDs in a separate file called 32kIDs.txt and it has a list of roughly 32,000 user IDs for facebook which look like 100000233850312;1521225383;100000282767638;1252335882;1804268242 They're all separated by a semi-colon. What I need this script to do is echo each and every ID on screen, echoing each ID on a new line. I have been using the explode function but having trouble with it since I'm very new to PHP and don't have much experience yet. Here is my current code: <?PHP $iFile = "32kIDs.txt"; $login = file($iFile, FILE_SKIP_EMPTY_LINES); if(!is_file($iFile)) echo "The 32k add list couldn't be found...".sleep(999999); foreach($login as $line_num => $line) { $login = explode(" ", htmlspecialchars(str_replace(";"," ",$line))); echo $login[0]."\n"; } sleep(20); ?> So I bet there are going to be things in there that I don't even need and thing's I'm missing, if anyone can help it would be much appreciated. And I'd like to keep the code short, I could just put in: echo $login[0]."\n"; echo $login[1]."\n"; echo $login[2]."\n"; echo $login[3]."\n"; all the way up to echo $login[32246]."\n"; but yeah I don't like the thought of a 32k+ line script. Anyways... Thanks in advance for any help that you may be able to provide. I'm a graphic designer with VERY limited knowledge of php, javascript, etc. I'm trying to create a form on my company's website that will allow customers to view specifications for particular products. I'm trying to use selection boxes to narrow the customer's search, with the selection from the second box dependent on the first, and the resulting information displayed dependent on the choice from the second list. So far, I've only been able to adapt some code I found in a tutorial to display the data in the first selection box. No matter what I've tried, I can't seem to get any information to display in the second box, let alone information that is dependent on the first selection. I am brand new to php and javascript, and I didn't even know AJAX, JSON, or JQuery even existed until only a few days ago. Below is the three php files I'm using to try and make this work. If someone could point out what is wrong with it, I would be eternally grateful. Here is the code from db.php, the file I'm using to connect to my database: Code: [Select] <?php /*changing "db_username" to "root", changing "db_password" to "xxXXXX", changing "database" to "trailers" */ mysql_connect("localhost", "root", "xxXXXX") or die(mysql_error()); mysql_select_db("trailers") or die(mysql_error()); ?> Here is the code from func.php, the file with all the functions and database queries: Code: [Select] <?php //************************************** // Page load dropdown results - changing tier_one to tnttrailer_brand, changing two_drops to trailerquote, changing 'tier_one' to 'tnttrailer_brand' // //************************************** function getTierOne() { $result = mysql_query("SELECT DISTINCT tnttrailer_brand FROM trailerquote") or die(mysql_error()); while($tier = mysql_fetch_array( $result )) { echo '<option value="'.$tier['tnttrailer_brand'].'">'.$tier['tnttrailer_brand'].'</option>'; } } //************************************** // First selection results - changing two_drops to trailerquote, changing tier_one to tnttrailer_brand, changing 'tier_two' to 'trailer_description', // //************************************** if($_GET['func'] == "drop_1" && isset($_GET['func'])) { drop_1($_GET['drop_var']); } function drop_1($drop_var) { include_once('db.php'); $result = mysql_query("SELECT trailer_description FROM trailerquote WHERE tnttrailer_brand='$drop_var'") or die(mysql_error()); echo '<select name="tier_two" id="tier_two"> <option value=" " disabled="disabled" selected="selected">Choose one</option>'; while($drop_2 = mysql_fetch_array( $result )) { echo '<option value="'.$drop_2['trailer_description'].'">'.$drop_2['trailer_description'].'</option>'; } echo '</select> '; echo '<input type="submit" name="submit" value="Submit" />'; } ?> Finally, this is the code from index.php, the file with the form, javascript and the AJAX: Code: [Select] <?php include('db.php'); include('func.php'); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Chained Select Boxes using PHP, MySQL and jQuery</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#wait_1').hide(); $('#drop_1').change(function(){ $('#wait_1').show(); $('#result_1').hide(); $.get("func.php", { func: "drop_1", drop_var: $('#drop_1').val() }, function(response){ $('#result_1').fadeOut(); setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400); }); return false; }); }); function finishAjax(id, response) { $('#wait_1').hide(); $('#'+id).html(unescape(response)); $('#'+id).fadeIn(); } </script> </head> <body> <p> <form action="" method="post"> <select name="drop_1" id="drop_1"> <option value="" selected="selected" disabled="disabled">Select a Category</option> <?php getTierOne(); ?> </select> <span id="wait_1" style="display: none;"> <img alt="Please Wait" src="ajax-loader.gif"/> </span> <span id="result_1" style="display: none;"></span> </form> </p> <p> <?php if(isset($_POST['submit'])){ $drop = $_POST['drop_1']; $tier_two = $_POST['trailer_description']; echo "You selected "; echo $drop." & ".$tier_two; } /* changed 'tier_two' to 'trailer_description' */ ?> </body> </html> Here's the page on my website. I'm using Joomla for my website, and the above php is loaded into a module at the bottom of the page: http://www.tnttrailer.com/index.php/dimensions.html I'm not getting any errors but its also not INSERTing into the database. Without an error I can figure out whats wrong. Code: [Select] $db_server = 'localhost'; $db_user = 'user_db'; $db_pass = 'password'; $dbc = mysql_connect ($db_server, $db_user, $db_pass); if (!$dbc) { die(mysql_error()); header ('Location: /form'); exit; } if (is_array($_POST)) { foreach ($_POST as $key => $value) { $_POST[$key] = mysql_real_escape_string(stripslashes($value)); } } $xRequestType = $_POST["xRequestType"]; $xConsumerBusiness = $_POST["xConsumerBusiness"]; $xGlobalLocation = $_POST["xGlobalLocation"]; $xFirstName = strtolower(str_replace("'","''",$_POST["xFirstName"])); $xFirstName = strtoupper(substr($xFirstName,0,1)).substr($xFirstName,1); $xLastName = strtolower(str_replace("'","''",$_POST["xLastName"])); $xLastName = strtoupper(substr($xLastName,0,1)).substr($xLastName,1); $xEmail = strtolower(str_replace("'","''",$_POST["xEmail"])); $xTitle = strtolower(str_replace("'","''",$_POST["xTitle"])); function dbSet($fields, $source = array()) { $set=''; if (!source) $source = &$_POST; foreach ($fields as $field) { if (isset($source[$field])) { $set.="`$field`='".mysql_real_escape_string($source[$field])."', "; } } return substr($set, 0, -2); } // INSERT INTO DATABASE mysql_select_db("new_contact",$dbc) or die("Could not select new_contact"); $fields = explode(" ", "xRequestType xConsumerBusiness xGlobalLocation xFirstName xLastName xEmail xTitle xCompany xAddress xCity xState xZip xPhone xFax xProductDesc xComment"); $query = "INSERT INTO new_contact SET ".dbSet($fields, $_POST); mysql_query($query); Hi I have tried the mysql forum but have had no joy with an answer to my problem so wondered if php would be better. I want my users to be able to select from 5 different drop down lists where they can chose any combination from 1 up to all 5, I have attached the front end. These lists are being populated from mysql tables. Code for the drop down lists is as follows Code: [Select] <form action="horse-events-devon.php?url_countyid=<?php echo urlencode ($url_countyid ['url_countyid']) ; ?>&go" method="POST"> <table id="searchtable"> <tr> <th>Find By Discipline</th> <th>Find By Venue</th> <th>Find By Championship</th> <th>Find By Organiser</th> <th>Equine Association</th> <th>Submit Your Selections</th> </tr> <tr> <td><select name="dis_id"> <?php $upcomingdis = upcomingdis($url_countyid); $upcoming_dis_bycounty = mysql_fetch_assoc ($upcomingdis); ?> <?php do { ?> <option value="<?php echo $upcoming_dis_bycounty ['dis_id']; ?>" > <?php echo $upcoming_dis_bycounty ['dis_description']; ?></option> <?php } while ($upcoming_dis_bycounty = mysql_fetch_assoc ($upcomingdis)); ?></select></td> <td><select name="ven_id"> <?php $upvenbycounty_set = upcoming_venevents_bycounty($url_countyid); $upcoming_ven_bycounty = mysql_fetch_assoc ($upvenbycounty_set); ?> <?php do { ?> <option value="<?php echo $upcoming_ven_bycounty ['ven_id']; ?>" > <?php echo $upcoming_ven_bycounty ['ven_name']; ?></option> <?php } while ($upcoming_ven_bycounty = mysql_fetch_assoc ($upvenbycounty_set)); ?></select></td> <td><select name="champ_id"> <?php $championship_set = findchampionships(); $champlist = mysql_fetch_assoc ($championship_set); ?> <?php do { ?> <option value="<?php echo $champlist ['champ_id']; ?>" > <?php echo $champlist ['champ_description']; ?></option> <?php } while ($champlist = mysql_fetch_assoc ($championship_set)); ?></select></td> <td> <select name="org_id"> <?php $uporgbycounty_set = upcoming_organevents_bycounty($url_countyid); $upcoming_org_bycounty = mysql_fetch_assoc ($uporgbycounty_set); ?> <?php do { ?> <option value="<?php echo $upcoming_org_bycounty ['org_id']; ?>" ><?php echo $upcoming_org_bycounty ['org_name']; ?></option> <?php } while ($upcoming_org_bycounty = mysql_fetch_assoc ($uporgbycounty_set)); ?></select> </td> <td><select name="ass_id"> <?php $upassbycounty_set = upcoming_assevents_bycounty($url_countyid); $upcoming_assbycounty = mysql_fetch_assoc ($upassbycounty_set); ?> <?php do { ?> <option value="<?php echo $upcoming_assbycounty ['ass_id']; ?>" > <?php echo $upcoming_assbycounty ['ass_description']; ?></option> <?php } while ($upcoming_assbycounty = mysql_fetch_assoc ($upassbycounty_set)); ?></select></td> <td><input name="submit" type="submit" /><input name="countyid" type="hidden" value="<?php echo $url_countyid ['url_countyid']; ?>" /></td> </tr> </table> </form> My search processing is as follows Code: [Select] <?php if (isset($_POST['submit'])){ if (isset($_GET['go'])){ $countyid = $_POST['countyid']; $ven_id = $_POST['ven_id']; $dis_id = $_POST['dis_id']; $champ_id = $_POST['champ_id']; $org_id = $_POST['org_id']; $event_id = $row['event_id']; $sql = "SELECT DATE_FORMAT (events.startdate, '%a, %d, %b') AS stdate, events.event_id, events.title, events.ven_id, events.org_id, venue.county_id, venue.ven_id, eventdisciplines.event_id, eventdisciplines.dis_id, county.county_id, discipline.dis_id \n" . "FROM events \n" . "LEFT OUTER JOIN eventdisciplines \n" . "ON events.event_id = eventdisciplines.event_id \n" . "LEFT OUTER JOIN discipline \n" . "ON eventdisciplines.dis_id = discipline.dis_id \n" . "LEFT OUTER JOIN venue \n" . "ON events.ven_id = venue.ven_id \n" . "LEFT OUTER JOIN county \n" . "ON venue.county_id = county.county_id \n" . "WHERE events.ven_id = ({$ven_id} OR events.org_id = {$org_id})\n" . "AND events.startdate > NOW()\n" . "AND venue.county_id = {$countyid} \n" . "ORDER BY startdate ASC"; $result = mysql_query ($sql, $connection); ?> How am I best to do this please? my OR within the mysql does not work, should I not be doing this with php in the search processing? someones help would really be appreciated, just to point me in the right direction. [attachment deleted by admin] Hi, In my mysql database i have a text input option, in the registration form and edit my details form i have a multiple select dropdown list, which user selects options to populate the text input box, which ultimately populates the text field in the mysql database. All works perfectly. The dropdownlist consists of 3 parts <optgroups> first is current selection (what is the usesr current selection)works fine, The second <optgroup> is existing words, what words we(the site) have given as options, and the third <optgroup> is the words that others have used. This is where im having a small problem. Because its a text field when i call the data from the database, it calls the entire text box as a single option in my select list.. I want to break the words in the text field (at the comma) and have them listed each one as an option in the select list. Example what i need: Words in text box:(my input allows the "comma") word1, word2, word3, word4, word5, word6, How i want them called/displayed: <option value=\"word1\">word1</option> <option value=\"word2\">word2</option> <option value=\"word3\">word3</option> <option value=\"word4\">word4</option> <option value=\"word5\">word5</option> <option value=\"word6\">word6</option> here's my code: $query = "SELECT allwords FROM #__functions_experience WHERE profile_id = '".(int)$profileId."' LIMIT 1"; $original_functionsexperience =doSelectSql($query,1); $query = "SELECT allwords FROM #__functions_experience WHERE profile_id = '".(int)$profileId."' LIMIT 1"; $functionsexperiencelist=doSelectSql($query); $funcexpList ="<select multiple=\"multiple\" onchange=\"setFunctionsexperience(this.options)\">"; foreach ($functionsexperiencelist as $functionsexperienceal) { $selected=""; if ($functionsexperienceals->allwords == $original_functionsexperience) $selected=' selected="selected"'; $allwords=$functionsexperienceal->allwords; $funcexpList .= "<optgroup label=\"Current selection\"> <option value=\"".$allwords."\" ".$selected." >".$allwords."</option> </optgroup> <optgroup label=\"Existing Words\"> <option value=\"existing1,\">existing1</option> <option value=\"existing2,\">existing2</option> <option value=\"existing3,\">existing3</option> <option value=\"existing4,\">existing4</option> <option value=\"existing5,\">existing5</option> <option value=\"existing6,\">existing6</option> </optgroup> <optgroup label=\"Others added\"> //heres problem <option value=\"".$allwordsgeneral."\">".$allwordsgeneral."</option> </optgroup>"; } $funcexpList.="</select>"; $output['FUNCEXPLIST']=$funcexpList; The result im getting for optgroup others added: word1, word2, word3, word4, word5, how can i get it like this: <option value=\"word1\">word1</option> <option value=\"word2\">word2</option> <option value=\"word3\">word3</option> <option value=\"word4\">word4</option> <option value=\"word5\">word5</option> <option value=\"word6\">word6</option> If I explode a string well using a substring when I implode that substring is now missing. for example. Code: [Select] $exploded = explode("[MAC]",$data); $data = implode($exploded); Now [MAC] would be missing in the $data string. any way to get around this? |