PHP - Remove Commas From Search String And Pass Results To A Query
I have some data in a table and some of it is Artist names stored as "Last, First"
I need to be able to have the script search weather or not someone types "last, first" or "first last". Any ideas? Here's my code: <html> <head> <title>search script</title> </head> <body> <form name="form" action="search.php" method="get"> <input type="text" name="q" /> <input type="submit" name="Submit" value="Search" /> </form> <?php // Get the search variable from URL $var = @$_GET['q'] ; $trimmed = trim($var); //trim whitespace from the stored variable // rows to return $limit=100; // check for an empty string and display a message. if ($trimmed == "") { echo "<p>Please enter a search...</p>"; exit; } // check for a search parameter if (!isset($var)) { echo "<p>We dont seem to have a search parameter!</p>"; exit; } //connect to your database ** EDIT REQUIRED HERE ** mysql_connect("localhost","username","password"); //(host, username, password) //specify database mysql_select_db("mydb") or die("Unable to select database"); //select which database we're using // Build SQL Query $query = "select * from songs where Title like \"%$trimmed%\" or Artist like \"%$trimmed%\" order by Title"; // EDIT HERE and specify your table and field names for the SQL query $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); // If we have no results, offer a google search as an alternative if ($numrows == 0) { echo "<h4>Results</h4>"; echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>"; } // next determine if s has been passed to script, if not use 0 if (empty($s)) { $s=0; } // get results $query .= " limit $s,$limit"; $result = mysql_query($query) or die("Couldn't execute query"); // display what the person searched for echo "<p>You searched for: "" . $var . ""</p>"; // begin to show results set echo "Results"; $count = 1 + $s ; // now you can display the results returned echo "<table border=1>"; while ($row= mysql_fetch_array($result)) { $title = $row["Title"]; $artist = $row["Artist"]; $number = $row["Number"]; echo "<tr><td>$count.)</td><td>$title</td><td>$artist</td><td>$number</td></tr>" ; $count++ ; } echo "</table>"; $currPage = (($s/$limit) + 1); //break before paging echo "<br />"; // next we need to do the links to other results if ($s>=1) { // bypass PREV link if s is 0 $prevs=($s-$limit); print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><< Prev 10</a>  "; } // calculate number of pages needing links $pages=intval($numrows/$limit); // $pages now contains int of pages needed unless there is a remainder from division if ($numrows%$limit) { // has remainder so add one page $pages++; } // check to see if last page if (!((($s+$limit)/$limit)==$pages) && $pages!=1) { // not last page so give NEXT link $news=$s+$limit; echo " <a href=\"$PHP_SELF?s=$news&q=$var\">Next 20 >></a>"; } $a = $s + ($limit) ; if ($a > $numrows) { $a = $numrows ; } $b = $s + 1 ; echo "<p>Showing results $b to $a of $numrows</p>"; ?> </body> </html> Similar TutorialsHi, i have a query string id=5&start=0 that i want to remove from the url and return the url without it. I am searching a cleaner way for doing it. Here is an example :
Before : http://www.example.com/?a=3&id=5&start=0 After : http://www.example.com/?a=3 Before : http://www.example.com/?id=5&start=0 After : http://www.example.com/ Before : http://www.example.com/?alpha=1&id=5&start=0&beta=2 After : http://www.example.com/?alpha=1&beta=2Thank you Edited by Dareros, 11 August 2014 - 04:06 PM. I have the following function, which takes a string with commas in it and attempts remove those commas. The way I have it here is that I use explode to take out the commas, which makes an array, and then iterate through that array to put a string back together without the commas. function tags_to_sort_by( $sortMeta ) { $sortByArray = explode(",", $sortMeta); $sortByCount = count($sortByArray); for ($i = 0; $i < $sortByCount; $i++) { $sortByString += $sortByArray[$i]; } return $sortByString; } What does not work is the following line: $sortByString += $sortByArray[$i]; Somehow that outputs a 0, which I don't understand. It should output something like: arrayItem1 arrayItem2 array3 etc. My question is if there either is an easier way to remove the commas from the original string or what I am doing wrong in this line: $sortByString += $sortByArray[$i]; // I am trying to concatenate each part of the array back into the string. Thanks a lot for help with this! Hello, I have a search engine on my website that uses the following code: Code: [Select] //SQL FOR *SEARCH.PHP $table = "videos"; $search = $_GET['q']; // explode search words into an array $arraySearch = explode(" ", $_GET['q']); // table fields to search $arrayFields = array(0 => "title", 1 => "titletext", 2 => "tags", 3 => "originaltitle", 4 => "url"); $countSearch = count($arraySearch); $a = 0; $b = 0; $sql = "SELECT * FROM ".$table." WHERE status ='1' AND ("; $countFields = count($arrayFields); while ($a < $countFields) { while ($b < $countSearch) { $sql = $sql."$arrayFields[$a] LIKE '%$arraySearch[$b]%'"; $b++; if ($b < $countSearch) { $sql = $sql." AND "; } } $b = 0; $a++; if ($a < $countFields) { $sql = $sql.") OR ("; } } $sql = $sql.") ORDER BY (videos.up-videos.down) DESC LIMIT $start, $limit"; $result = mysql_query($sql); My problem is that the SQL Query includes even videos that have STATUS='0' .. I only want the STATUS='1' to be shown.. How come? Thanks for help I'm hoping this is a simple question. When I use the code below, my twitter search query appears in BOLD within the returned results. I would like to style the search term differently. I can use CSS to style the avatar, author, and other information within the returned results etc, but I can't figure out how to style the search term ($q) within the returned twitter information. Any help would be much appreciated. <?php class twitter_class { function twitter_class() { $this->realNamePattern = '/\((.*?)\)/'; $this->searchURL = 'http://search.twitter.com/search.atom?lang=en&q='; $this->intervalNames = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year'); $this->intervalSeconds = array( 1, 60, 3600, 86400, 604800, 2630880, 31570560); $this->badWords = array('somebadword', 'anotherbadword'); } function getTweets($q, $limit=15) { $output = ''; // get the search result $ch= curl_init($this->searchURL . urlencode($q)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); $response = curl_exec($ch); if ($response !== FALSE) { $xml = simplexml_load_string($response); $output = ''; $tweets = 0; for($i=0; $i<count($xml->entry); $i++) { $crtEntry = $xml->entry[$i]; $account = $crtEntry->author->uri; $image = $crtEntry->link[1]->attributes()->href; $tweet = $crtEntry->content; // skip tweets containing banned words $foundBadWord = false; foreach ($this->badWords as $badWord) { if(stristr($tweet, $badWord) !== FALSE) { $foundBadWord = true; break; } } $tweet = str_replace('<a href=', '<a target="_blank" href=', $tweet); // skip this tweet containing a banned word if ($foundBadWord) continue; // don't process any more tweets if at the limit if ($tweets==$limit) break; $tweets++; // name is in this format "acountname (Real Name)" preg_match($this->realNamePattern, $crtEntry->author->name, $matches); $name = $matches[1]; // get the time passed between now and the time of tweet, don't allow for negative // (future) values that may have occured if server time is wrong $time = 'just now'; $secondsPassed = time() - strtotime($crtEntry->published); if ($secondsPassed>0) { // see what interval are we in for($j = count($this->intervalSeconds)-1; ($j >= 0); $j--) { $crtIntervalName = $this->intervalNames[$j]; $crtInterval = $this->intervalSeconds[$j]; if ($secondsPassed >= $crtInterval) { $value = floor($secondsPassed / $crtInterval); if ($value > 1) $crtIntervalName .= 's'; $time = $value . ' ' . $crtIntervalName . ' ago'; break; } } } $output .= ' <div class="tweet"> <div class="avatar"> <a href="' . $account . '" target="_blank"><img src="' . $image .'"></a> </div> <div class="message"> <span class="author"><a href="' . $account . '" target="_blank">' . $name . '</a></span>: ' . $tweet . '<span class="time"> - ' . $time . '</span> </div> </div>'; } } else $output = '<div class="tweet"><span class="error">' . curl_error($ch) . '</span></div>'; curl_close($ch); return $output; } } ?> The HTML I have been using with this code is here Code: [Select] <!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> <title>Twitter</title> </head> <body> <?php require('twitter.class.php'); $twitter = new twitter_class(); echo $twitter->getTweets('example search term', 10); ?> </body> </html> This is not my code. It is from a tutorial that can be accessed from here >> http://www.richnetapps.com/php-twitter-search-parser/ Say a user puts in a support request, and for every request it generates a unqiue string, and enters it into the database. Ok, now say there is a text field, when the user enters their unique string and it finds a match, it displays the data along with it. How can I accomplish this? Im kind of new to mysql, but I know basic SQL. Would be great if somebody could point me in the right direction! Thanks Hi! So what I'm trying to do is split a multi dimensional array of strings ( each containing 3 strings inside of 1 array ) so I can write the results to a file. So say I had a bunch of strings inside 1 array : class File { function WriteFile ( $filename, $content ) { $list = [ $content ]; $delimiters = File :: checkDelimiter ( $content, true, false ); $fp = fopen ( $filename, 'w' ); foreach ( $list as $fields ) { $fields = File :: SplitFileByDelimiter ( $fields, ",", 3 ); file_put_contents ( $filename, $fields ); } fclose ( $fp ); } } $file-> File :: WriteFile ( $filepath . $filename, "TEST!, TEST!, TEST!, " . "TEST!, TEST!, TEST!, " . "TEST!, TEST!, TEST!" ); Instead of writing : TEST!, TEST!, TEST!, TEST!, TEST!, TEST!, TEST! ,TEST!, TEST!, TEST! to the file in a straight line, it should write it like this : TEST!, TEST!, TEST!, TEST!, TEST!, TEST!, TEST!, TEST!, TEST! Any help is ABSOLUTELY appreciated! Edited May 22 by AquariaXI Hi, I am trying to find a way that will allow me to convert information passed via POST into array so I can run foreach on the array. For example if information in $_POST[ids] is 1000, 1001, 1002, 1003 I would like to get it into an array $array = array("1000", "1001", "1002", "1003") Thanks Hello, I'm developing a website that asks the user to submit a keyword for a search. The results should display matches for this keyword, but also show matches for related keywords (in order of relevenace!). I'm planning on building up a library of which search terms users use in the same sessions (e.g. if someone searches for "it jobs" and "php jobs", I'll know the terms are correlated), and I'll also measure the click-through rates of the items on the results list. I've been spending all weekend trying to map out the design for this but it's proving incredibly complicated and I think the solution is likely to be on the internet somewhere already?! Please could someone point me in the right direction if you've come accross this problem before? Thanks a million, Stu Hello all,
Based on the suggestion of you wonderful folks here, I went away for a few days (to learn about PDO and Prepared Statements) in order to replace the MySQLi commands in my code. That's gone pretty well thus far...with me having learnt and successfully replaced most of my "bad" code with elegant, SQL-Injection-proof code (or so I hope).
The one-and-only problem I'm having (for now at least) is that I'm having trouble understanding how to execute an UPDATE query within the resultset of a SELECT query (using PDO and prepared statements, of course).
Let me explain (my scenario), and since a picture speaks a thousand words I've also inlcuded a screenshot to show you guys my setup:
In my table I have two columns (which are essentially flags i.e. Y/N), one for "items alreay purchased" and the other for "items to be purchased later". The first flag, if/when set ON (Y) will highlight row(s) in red...and the second flag will highlight row(s) in blue (when set ON).
I initially had four buttons, two each for setting the flags/columns to "Y", and another two to reverse the columns/flags to "N". That was when I had my delete functionality as a separate operation on a separate tab/list item, and that was fine.
Now that I've realized I can include both operations (update and delete) on just the one tab, I've also figured it would be better to pare down those four buttons (into just two), and set them up as a toggle feature i.e. if the value is currently "Y" then the button will set it to "N", and vice versa.
So, looking at my attached picture, if a person selects (using the checkboxes) the first four rows and clicks the first button (labeled "Toggle selected items as Purchased/Not Purchased") then the following must happen:
1. The purchased_flag for rows # 2 and 4 must be switched OFF (set to N)...so they will no longer be highlighted in red.
2. The purchased_flag for row # 3 must be switched ON (set to Y)...so that row will now be highlighted in red.
3. Nothing must be done to rows # 1 and 5 since: a) row 5 was not selected/checked to begin with, and b) row # 1 has its purchase_later_flag set ON (to Y), so it must be skipped over.
Looking at my code below, I'm guessing (and here's where I need the help) that there's something wrong in the code within the section that says "/*** loop through the results/collection of checked items ***/". I've probably made it more complex than it should be, and that's due to the fact that I have no idea what I'm doing (or rather, how I should be doing it), and this has driven me insane for the last 2 days...which prompted me to "throw in the towel" and seek the help of you very helpful and intellegent folks. BTW, I am a newbie at this, so if I could be provided the exact code, that would be most wonderful, and much highly appreciated.
Thanks to you folks, I'm feeling real good (with a great sense of achievement) after having come here and got the great advice to learn PDO and prepared statements.
Just this one nasty little hurdle is stopping me from getting to "end-of-job" on my very first WebApp. BTW, sorry about the long post...this is the best/only way I could clearly explaing my situation.
Cheers guys!
case "update-delete": if(isset($_POST['highlight-purchased'])) { // ****** Setup customized query to obtain only items that are checked ****** $sql = "SELECT * FROM shoplist WHERE"; for($i=0; $i < count($_POST['checkboxes']); $i++) { $sql=$sql . " idnumber=" . $_POST['checkboxes'][$i] . " or"; } $sql= rtrim($sql, "or"); $statement = $conn->prepare($sql); $statement->execute(); // *** fetch results for all checked items (1st query) *** // $result = $statement->fetchAll(); $statement->closeCursor(); // Setup query that will change the purchased flag to "N", if it's currently set to "Y" $sqlSetToN = "UPDATE shoplist SET purchased = 'N' WHERE purchased = 'Y'"; // Setup query that will change the purchased flag to "Y", if it's currently set to "N", "", or NULL $sqlSetToY = "UPDATE shoplist SET purchased = 'Y' WHERE purchased = 'N' OR purchased = '' OR purchased IS NULL"; $statementSetToN = $conn->prepare($sqlSetToN); $statementSetToY = $conn->prepare($sqlSetToY); /*** loop through the results/collection of checked items ***/ foreach($result as $row) { if ($row["purchased"] != "Y") { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToY = $statementSetToY->fetch(); foreach($resultSetToY as $row) { $statementSetToY->execute(); } } else { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToN = $statementSetToN->fetch(); foreach($resultSetToN as $row) { $statementSetToN->execute(); } } } break; }CRUD Queston.png 20.68KB 0 downloads Please can someone advise how I remove the | characters from a string? I tried the following but get errors that... Warning: preg_replace() [function.preg-replace]: No ending delimiter '|' Code: [Select] $value = preg_replace("|", "", $value); This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=353002.0 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 Hi, How would i strip out both the " and ' characters from a php string? Thanks Fraser Is there a way/function to not only remove <script>, <embed> tags etc but also remove the content within the tags so this: " some text <script> functionhere(); </script> some more text " to this: " some text some more text " In effect remove the whole tag and content within the tags? Havent been able to find anything online that works Many thanks in advance. Simon 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." Am looking forward to removing all the numeric characters upto and including the leading "/" in 90/_featuredarticles/2011/12 Regards I am working on a room availability calendar that has links for each day. When you click on a link it passes the day month and year in the URL to another page like this: echo "<td class=\"today\"> <a href=\"status.php?month=$month&day=$day_num&year=$year\">$day_num</a> </td>\n"; I can see that the correct information is being passed through the URL like this: Code: [Select] .../status.php?month=12&day=9&year=2010 Then the information is supposed to be passed to the MySQL query, but here is my question: How do I do this? I have a DB table set up, but the query is currently returning a blank page. Here is my current query: // connects to server and selects database. include ("../includes/dbconnect.inc.php"); // table name $table_name = "availability"; // query database for events $result = mysql_query ("SELECT id FROM $table_name WHERE month=$month AND year=$year AND day=$day_num LIMIT 1") or die(); if (mysql_num_rows($result) > 0 ) { while($row = mysql_fetch_array($result)) { extract($row); echo "<h1>Current availability for ".$row['month'] . "/" . $row['day'] . "/" . $row['year'] . "</h1>"; echo " <ul>"; echo " <li>Earth Room: " . $row['earth_room'] . "</li>"; echo " <li>Air Room: " . $row['air_room'] . "</li>"; echo " <li>Fire Room: " . $row['fire_room'] . "</li>"; echo " <li>Water Room: " . $row['water_room'] . "</li>"; echo " </ul>"; } } else { echo " <ul>"; echo " <li>Currently no reservations.</li>"; echo " </ul>"; } Any help is appreciated. Thanks, kaiman I need to pass captured data, basically, a list of email addresses that are being read from a CSV file and (1st) saved to an local database, then sent over to an external source via URL string. I have everything working except - script opens the file, read and validates all emails in the specified column, and saves to local db. ISSUE: after validating then INSERTING the data into local mySQL db, I need to then pass each piece of data to an external source via URL string. Example: www.domain.com?email={$new_email} I was initially think to just add the URL in a header function but, I'm not sure if the HEADER() function the right method to pass all of the data - during the loop - via the URL string. For example, if the CSV file contain 500 emails: Q: how can I continue that loop until the last email read, passing each up to the external source via the URL string? I'm not sure if using the HEADER() function at the end of the script - but within the loop - will interate and send each capture email via that URL string. Can anyone advise a possible solution to this? thanks Hi, Im looking at using a statement like this to remove all text characters from a string. $outgoing = substr_replace($incoming,"",-1); The string is a currency that has a currency symbol in the beginning of the string, like "R500.00" I would like to remove the R, so it is just a numeric value... Please can you help me with any ideas on how to get this going? Been reading so much and its all confused me too badly. Regards, Chris |