PHP - How To Style Twitter Search Query Within The Returned Results
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/ Similar TutorialsGreetings! This n00b has a "search engine" dedicated to extracting relevant information from log files. It works by parsing preset fields in the log filename. I'd like to have some notification when the search returns no rows as I am planning to add more search options. Here's my code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head> <title>LogFile Search</title> <style type="text/css"> <<irrelevant stuff removed>> </style> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" language="javascript" src="js/UI.js"></script> </head> <body> <h3 id="myh3">Log File Search</h3><h5>Version 1.0.1</h5> <h4 id="myh4"><ul><li> <<irrelevant stuff removed>> </li></ul></h4> <form method="post" name="LogFile_Search" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <table id="mytable"> <tbody> <tr> <td id="mytd">Result(P|F|N): <input type="text" id="Result_PFN" name="Result_PFN" size="31"/></td> <td id="mytd">Script Version: <input type="text" id="ScriptVersion" name="ScriptVersion" size="31"/></td> </tr> </tbody> </table> <br> <input type="submit" value="Search" onclick="doForm();"> <input type="button" value="Reset" onclick="resetForm();"> </form> <div id="searchResult"> <?php /* Where the logs files are dropped by external process. */ $mydir = $_SERVER['DOCUMENT_ROOT'] . "/LogFile_Search/LogFiles"; /* Handle to directory. */ $dir = opendir($mydir); /* Form variables. */ $Result_PFN = $_POST['Result_PFN']; $ScriptVersion = $_POST['ScriptVersion']; /* Test each field -- triggers JS alert if all are empty. */ if (!empty($Result_PFN)) { doResult_PFN(); } elseif (!empty($ScriptVersion)) { doScriptVersion(); } /* Function for Search on Script version in logfile contents. */ function doScriptVersion() { global $dir; global $mydir; global $ScriptVersion; echo '<table id=\'mytable\'><tbody><tr><td id=\'mytd\'>Log File Name.</td></tr>'; //grabs all log files matching the script version number that's input in the form. $cmd = "find " . $mydir . " -type f -print0 | xargs -0 grep -e 'Test_Version=" . $ScriptVersion . "'"; exec($cmd, $output); //Sort the array using a case insensitive "natural order" algorithm. natcasesort($output); if (count($output) > 0) { foreach ($output as $v) { //Display file name without full path as URL. echo '<tr><td><a href="' . basename($mydir) . '/' . array_pop(explode("/", array_shift(explode(":", $v)))) . '" target="_blank">' . array_pop(explode("/", array_shift(explode(":", $v)))) . '</a></td></tr>'; } } else { echo "<html><body style=\"background-color:#0080c0\"> <script type=\"text/javascript\" language=\"javascript\">alert( 'Nothing found' + '.');</script> </body></html>"; } closedir($dir); echo "</table></body>"; } /* Function for Search on Result marker in file name. */ function doResult_PFN() { global $dir; global $mydir; global $Result_PFN; echo '<table id=\'mytable\'><tbody><tr><td id=\'mytd\'>Log File Name.</td></tr>'; if ($dir) { //List files in directory while (($file = readdir($dir)) !== false) //Ignores OS stuff. if ($file != "." && $file != "..") { //Pattern match for result. if (preg_match("/~(P|F|N)*" . $Result_PFN . "~/i", $file)) { //Sort the array using a case insensitive "natural order" algorithm. natcasesort($file); echo '<tr><td><a href="' . basename($mydir) . '/' . $file . '" target="_blank">' . $file . '</a></td></tr>'; } } else { echo "<html><body style=\"background-color:#0080c0\"> <script type=\"text/javascript\" language=\"javascript\">alert( 'Nothing found' + '.');</script> </body></html>"; } closedir($dir); } echo "</table></body>"; } ?> </div> </body> </html> When doResult_PFN() returns no result, the ELSE portion is never evaluated and no notification is sent to the user. However, I have no problem with doScriptVersion(): it returns an alert. What am I missing? Thanks, Al. Search not functioning. The drop down box to search on Club_Name and Email is blank, clicking search results unchanged ... all suggestions appreciated ... newbie at php. Thanks. <!-- Code below is not functional, trying to query search results, search box with drop down box for two fields--> <table width="50%"> <tr> <td height="30" align="left" bgcolor="#FFFFFF" class="form1" > {$letter_links} </td> <td height="30" align="right" bgcolor="#FFFFFF" class="form1" > <input type=hidden name="sorter" value="{$sorter}"> <table><tr> <form name="search_form" action="{$form.action}" method="post"> <td class="form1" ><input type="text" name="search" value="{$search}"></td> <td class="form1" ><select name="s_type" style=""> {section name=s loop=$types} <option value="{$smarty.section.s.index_next}" {if $types .sel}selected{/if}>{$types .value}</option> {/section} </select></td> <td class="form1"><input type="button" value="{$button.search}" class="button" onclick="javascript: document.search_form.submit();" name="search_submit"></td> </form> </tr></table> </td> </tr> </table> <!-- Code below successfully displays query results --> <form method="post" action="{$file_name}?sel=approve" enctype="multipart/form-data" name="form1" onsubmit="foo(); return false;"> <table cellspacing="2" cellpadding="10" border="1"> <tr align="center"><td>Num</td><td>Club Name</td><td>Login</td><td>Country</td><td>Region</td><td>City</td><td>Address</td><td>Web site</td><td>Email</td><td>Contact Name</td><td>Contact Phone</td><td>Swinging</td><td>Alcohol</td><td>Food</td><td>Entertainment</td><td>Fees</td><td>Approved/<br/>Rejected</td><td>Actions</td></tr> {foreach item=item from=$contest key=key name=foo} <tr align="center"><td><input type="hidden" name="all_approves[{$item.id}]" value="{$item.id}"/>{$key+1}</td><td>{$item.name}</td><td>{$item.login}</td><td>{$item.country_name}</td><td>{$item.region_name}</td><td>{$item.city_name}</td><td>{$item.address}</td><td>{$item.web_site}</td><td>{$item.email}</td><td>{$item.contact_name}</td><td>{$item.contact_phone}</td> <td> {math equation="x - 1" x=$item.swinging assign=index_pos} {$xml_swing[$index_pos].value}</td> <td>{math equation="x - 1" x=$item.alcohol assign=index_pos}{$xml_alco[$index_pos].value}</td> <td>{math equation="x - 1" x=$item.foot assign=index_pos}{$xml_foot[$index_pos].value}</td> <td>{math equation="x - 1" x=$item.entertainment assign=index_pos}{$xml_entertainment[$index_pos].value}</td> <td>{math equation="x - 1" x=$item.fees assign=index_pos}{$xml_fees[$index_pos].value}</td><td> <span> {if $item.is_approved eq '1'} Approved {else} Rejected {/if}</span></td><td align="center"><a href="{$file_name}?sel=edit&id_content={$item.id}">[ Edit ]</a><br/><a href="{$file_name}?sel=delete&id_content={$item.id}">[ Delete ]</a><br/><a href="{$file_name}?sel=approve&id_content={$item.id}">[ Approve ]</a><br/><a href="{$file_name}?sel=reject&id_content={$item.id}">[ Reject ]</a></tr> {/foreach} </table> </form> here is my code... please help <form method="get" action="shit3.php"> <input maxlength="50" size="50" type="text" name="q"> <input type="submit" value="SEARCH"> </form> <?php if (@$_GET['q']) { $var = $_GET['q'] ; $trimmed = trim($var); $limit=1; if ($trimmed == "") { echo "Please enter a search..."; exit; } if (!isset($var)) { echo "Container not found!"; exit; } mysql_connect("localhost", "xxx", "yyy") or die(mysql_error()); mysql_query("SET NAMES 'cp1251'"); mysql_select_db("agaexpor_container") or die("Unable to select database"); //select which database we're using $query = "select * from containertracking where vin like \"%$trimmed%\" order by vin"; $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); if (empty($s)) { $s=0; } $query .= " limit $s,$limit"; $result = mysql_query($query) or die("Couldn't execute query"); $count = 1 + $s ; while ($row= mysql_fetch_array($result)) { $vin = $row["vin"]; $container = $row["container"]; echo "$count.) VIN: $vin <br />"; echo "container is: $container <br />"; $count++ ; } } ?> 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 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 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> Hi guys, I am working with an old script at the moment, there is one page which just will not populate the table results. I have tried running multiple debugging commands but the only one it flags is the line displaying Quote last; saying it's not a used function. If I comment out this line, no errors are produced but the results do not enter the table. Can anyone shed some light on this please, I've spent hours and hours and banging my head against a brick wall would probably be more constructive right now. Many thanks indeed for any help or advice. <?php mysql_connect("localhost", "$db_user","$db_upwd") or die ("Error - Could not connect: " . mysql_error()); mysql_select_db("$database"); $query="select host,count(*) from badc_mis_prog group by host"; $result = mysql_query($query) or die ("Error - Query: $query" . mysql_error()); $count=0; $hosts=array(); while ($row = mysql_fetch_array($result, MYSQL_NUM)) { $html_hlname=$row[0]; $html_hlname=preg_replace("/</","<",$html_hlname); $html_hlname=preg_replace("/>/",">",$html_hlname); array_push($hosts, $html_hlname,$row[1],0); $count++; } $query="select host,count(*) from badc_mis_prog where reported=1 group by host"; $result = mysql_query($query) or die ("Error - Query: $query" . mysql_error()); while ($row = mysql_fetch_array($result, MYSQL_NUM)) { $html_hlname=$row[0]; $html_hlname=preg_replace("/</","<",$html_hlname); $html_hlname=preg_replace("/>/",">",$html_hlname); for ($i=0; $i<($count*3); $i+=3) { if ($hosts[$i] == $html_hlname) { $hosts[($i+2)]=$row[1]; last; } } } for ($i=0 ; $i<(($count-1)*3); $i+=3){ for ($j=$i+3 ; $j<($count*3); $j+=3){ if ($hosts[($i+1)] < $hosts[($j+1)]){ $temp=array(); $temp[0]=$hosts[$i]; $temp[1]=$hosts[($i+1)]; $temp[2]=$hosts[($i+2)]; $hosts[$i]=$hosts[$j]; $hosts[($i+1)]=$hosts[($j+1)]; $hosts[($i+2)]=$hosts[($j+2)]; $hosts[$j]=$temp[0]; $hosts[($j+1)]=$temp[1]; $hosts[($j+2)]=$temp[2]; } } } print "<br><br><br><center><table border=\"1\">\n"; print "<tr><td>Host Name</td><td>Hosted</td><td>Reported</td><td>Ratio H/R</td></tr>\n"; for ($i=0; $i<($count*3); $i+=3) { if ($hosts[($i+1)]<15){ break;} printf ("<tr><td> %s </td><td> %d </td><td> %d </td><td>%.1f %%</td></tr>\n",$hosts[$i],$hosts[($i+1)],$hosts[($i+2)],(($hosts[($i+2)]/$hosts[($i+1)])*100)); } print "</table></center>\n"; ?> Hello. I am interested in taking a result returned from a database and having it displayed in a certain way/style on the user's screen; For example, the user enters text into a field and hits "submit" - the data is saved in the database then displayed to the user (This part I have working just fine so far due to help I received here.) My question is if I would like to, for example, have said text not simply dumped to the top of the screen, inline, but nicely formatted in a boxed, text area, I assume I will use HTML/CSS, and I was wondering if anyone had any good links/tutorials regarding this topic so I may look further into it (my search thus far has not turned up the correct topic or results). Thank-you in advance for any assistance. ~Matty I've had a bit of a search around to see if this is possible but have yet to find something. I'm looking to be able to offset the results from opendir or similar function without returning all the files/folders. In other words i'd like to display the file/folder results over multiple pages when there are a lot of files/folders to display. Is this at all possible? I am looking to accomplish the following but have been hitting a brick wall: * User enters a single keyword into a text field, and conducts a search keyword search. * The results are pulled from the campusbooks.com API(API docs attached) * result are then output in <div> class and includes all the book details and its corresponding url./img etc I'm trying to simplify this process but I continue to receive syntax errors. A step by step practical explanation would do me justice! Am currently using this code, and actually thinking about it should split the query to an include in order to allow for other database drivers, on the chance we may decide to ditch the old MySQL. But I digress from the question. Code: [Select] include($lib."dbconfig.php"); $q = 'SELECT * FROM file WHERE this = "'.$that'"; $result = mysql_query($q); if (mysql_num_rows($result) > 0) If the query doesn't pick up a row I'm getting this error yo, Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in D:\webpages\*\*\admin.php on line 553 So what would be a better way of testing if the query was successful? Have a web page that displays a number of update forms depending on the amout of records that get returned from a mysql query, if query returns 4 records then the page will display 4 identical forms, the trouble i'm having is getting the each of the 4 forms to display a different record as at the moment they all show just first record of query. I have played around with loops but not getting anywhere which may be due to my limited knowledge code for page is below Code: [Select] <?php $numberofrow =mysql_num_rows($Recordset1); for($counter = 1;$counter<=$numberofrow;$counter++){ ?> <label for="hometeam2"></label> <form id="form1" name="form1" method="POST" action="<?php echo $editFormAction; ?>"> <label for="hometeam"></label> <input name="fixid" type="text" id="fixid" value="<?php echo $row_Recordset1['FixtureID']; ?>" /> <input name="hometeam" type="text" id="hometeam2" value="<?php echo $row_Recordset1['hometeamname']; ?>" /> <label for="homescore"></label> <input name="homescore" type="text" id="homescore" value="<?php echo $row_Recordset1['homescore']; ?>" /> <label for="awayscore"></label> <label for="fixid"></label> <input name="awayscore" type="text" id="awayscore" value="<?php echo $row_Recordset1['awayscore']; ?>" /> <label for="awayteam"></label> <input name="awayteam" type="text" id="awayteam" value="<?php echo $row_Recordset1['awayteamname']; ?>" /> <input type="submit" name="update" id="update" value="Submit" /> <input type="hidden" name="MM_update" value="form1" /> Say I do a query from a database that only asks for one field in return (which always has a number in it). How do you write the PHP to take the first number returned and add it to the next number returned (NOTE: There may be more than two numbers returned, but for now, I'm always dealing with two) For example, say I do a query that returns the number 27 first and then the number 10 second. FYI, these numbers will be available in the variable $diff['result']. So the code after the query would look something like this, but obviously i'm struggling with the part in comments... Code: [Select] if (!$numbers) { die("Database query failed: " . mysql_error()); } else { while ($diff = mysql_fetch_array($numbers)) { //this would bring back 27 first, in the variable $diff['result'] and then on the 2nd loop through, it would bring back 10 in the $diff['result'] variable //ultimately, i just want the difference between the numbers (which in the case would be 17). It's just a simple addition, so Im obviously an idiot because I can't figure out the syntax for adding the first returned number to the next returned number:) } } I'm trying to develop some php that will execute a MySQL query and move the results into XML. In this particular instance, only one record is expected to be returned, and that one row will contain all the customer data, such as last name, first name, address1, etc. While I can get my code to work and create the xml if I hard-code in all the keys (MySQL column names), I would like it to dynamically step through all the keys/MySQL column names so that if the db changes later (add more columns, for instance) the code generating the XML won't need to be altered. It should take the MySQL column name, create an element based on the column name, then create a text node and insert the value. Currently I'm just at the spot of testing by echoing the appropriate key/value pairs. The code is stopping after the first key/value without going through the rest of the columns. What do I need to do in order to get it to dynamically step through each column and get the key/value? Here's the relevant code: if($_POST['buscode']) {echo "buscode is: ".$_POST['buscode']."<HR>";} else {echo "ERROR WITH RETRIEVING BUSCODE<HR>";} $buscode = $_POST['buscode']; $query = "SELECT * " ."FROM customers " ."WHERE buscode = '$buscode'"; echo "Query will be: ".$query."<HR>"; $result = mysql_query($query); if($result){echo "Success retrieving data from ats_ajax.<HR>";} else{echo "Error retrieving data from ats_ajax\; MySQL error is:".mysql_error($result)."<HR>";} //////////////////////////////////////// // Let's test getting the keys and values from the array.... /////////////////////////////////////// while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "This is step ".$i."<BR>"; $key = key($row); echo "Key is: ".$key."<BR>"; echo "Value is: ".$row[$key]."<BR>"; $i++; }//close of while Hello folks,
In trying to improve the user experience for my first WebApp I have decided to create two new tables - one a master file to contain a list of all stores, and the second a master file to contain a list of all products that are normally purchased - and I would like to use the values from these two tables as lookup values in dropdown listboxes, to which the user can also add new entries.
As it turns out, I'm stuck on the very first objective i.e. to lookup/pull-in the distinct values from the master tables.
The problem I'm having is that the query seems to return no rows at all...in spite of the fact that there a records in the table, and the exact same query (when run within the MySQL environment) returns all the rows correctly.
Is there something wrong with my code, or how can I debug to see whether or not the query is being executed?
Objective # 2, which is to allow new values to be entered into the dropdown listbox, and then inserted into the respective table is certainly waaay beyond my beginner skills, and I'll most certainly need to some help with that as well..so if I can get some code/directions in that regard it will be most appreciated.
Thank you.
<?php $sql = "SELECT DISTINCT store_name FROM store_master ORDER BY store_name ASC"; $statement = $conn->prepare($sql); $statement->execute(); $count = $statement->rowCount(); echo $count; // fetch ALL results pertaining to the query $result = $statement->fetchAll(); echo "<select name=\"store_name\">"; echo '<option value="">Please select...</option>'; foreach($result as $row) { echo "<option value='" . $row['store_name'] . "'></option>"; } echo "</select>"; ?> 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 Im trying to make a php program that will grab all the user's tweets they have ever done.. I'm using curl to request the twitter page and scrape the html. It looks as though the maximum amount of tweets I can get is 20, which is the amount on the initial first page. There is some script that loads another 20 tweets once I scroll to the bottom of the page... Does anyone know how to make the page automatically load a certain amount so I can scrape more than the first 20 at once. What would be the correct way to close a mysql query? At current the second query below returns results from the 1st query AND the 2nd query The 3rd query returns results from the 1st, 2nd and 3rd query. etc etc. At the moment I get somthing returned along the lines of... QUERY 1 RESULTS Accommodation 1 Accommodation 2 Accommodation 3 QUERY 2 RESULTS Restaurant 1 Restaurant 2 Restaurant 3 Accommodation 1 Accommodation 2 Accommodation 3 QUERY 3 RESULTS Takeaways 1 Takeaways 2 Takeaways 3 Restaurant 1 Restaurant 2 Restaurant 3 Accommodation 1 Accommodation 2 Accommodation 3 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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <?php include($_SERVER['DOCUMENT_ROOT'].'/include/db.php'); ?> <title>Untitled Document</title> <style type="text/css"> <!-- --> </style> <link href="a.css" rel="stylesheet" type="text/css" /> </head><body> <div id="listhold"> <!------------------------------------------------------------------------------------------------------------------------------------------------------> <div class="list"><a href="Placestostay.html">Places To Stay</a><br /> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Accommodation' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> <!------------------------------------------------------------------------------------------------------------------------------------------------------> <div class="list"><a href="Eatingout.html">Eating Out</a><br /> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Restaurant' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> <!------------------------------------------------------------------------------------------------------------------------------------------------------> <div class="list"><a href="Eatingin.html">Eating In</a><br /> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Takeaways' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> <!------------------------------------------------------------------------------SKILLED TRADES BELOW---------------------------------------------------> <div class="list"><a href="Skilledtrades.html">Skilled Trades</a><br/> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Skilled Trades' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> |