PHP - Better Way To Determine If A Query Has Returned At Least One Row
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? Similar TutorialsHi, I'm making an attempt to build a small cms based site. I have read in a lot of places it is best to use the id of a table row to fetch contents, but being as I am using url rewrite in frontend, it won't be showing query strings, so I thought I would ask if anyone saw any potential problems if I did the following. Page table looks like this: Pages - id - name - content In backend, the user has a form to name the page and use ckeditor to add rich content. I will use php to ensure that the name is alphanumeric and use strtolower & str_replace to ensure that My First HTML Page is sent to mysql as my-first-html-page and also check that a row with this name does not already exist. So on front end this page url will be mywebsite.com/my-first-html-page So to output the content I strip out the domain & / so I'm left with the name as entered in the db. $url = $_SERVER['REQUEST_URI']; $url = str_replace ('/','',$url); Then in my function to output content I will use WHERE name = $url 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" /> 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>"; ?> 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> 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 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/ 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++ ; } } ?> All, I have a zip code and for example the zip code is 01101. How can I determine if the first character in this is a zero? Thanks in advance. My uploader allows the following file formats: jpg gif png I tested that if someone was to name a file configure.php.jpg, my uploader allows it to upload I want to do a check to see if the user has 2 extensions, and if so it will not allow them to upload. I was thinking of just checking if the file name has two "." (dots) in the name. What function could I use to do this? Or .. is there a better way? This may sound funny, but I'm not sure what I was trying to get this code to do... Code: [Select] <!-- Find Current Page Name --> <?php $page = basename($_SERVER['REQUEST_URI']); echo '<p>$page = ' . $page . '</p>'; // if ($page == '') { if (($page == '/')||($page == '')||($page == 'index.php')){ $page = "index.php"; echo '<p>You are on the Home Page.</p>'; }else{ echo '<p>You are on Some Other Page.</p>'; } What I mean by that is I'm not understanding why I chose... Code: [Select] if ($page == '') { and then... Code: [Select] if (($page == '/')||($page == '')){ and then... Code: [Select] if (($page == '/')||($page == '')||($page == 'index.php')){ Why would I get those different results from basename($_SERVER['REQUEST_URI'])?? And what should I expect locally on my Laptop with a Virtual Host set up (e.g. "http://local.debbie/index.php") versus using a Test Site (e.g. "http://www.doubledee.byethost2.com/") versus a real site (e.g. "www.debbie.com")?! Hope I'm making some sense here... Debbie I have a table that I must be populated based on a check box selection. The maximum selection is 5, however, there are more then 10 choices. For example: Here is a choice of 10 different (checkbox) options that the user can select from: 1. Coke 2. Root Beer 3. Pepsi 4. Dr. Pepper 5. Sprite 6. 7up 7. Cream Soda 8. Club Soda 9. Water 10. Milk I've already managed to limit the users selection to only 5. My issue is determining which of the checkboxese were actually selected so that I can correctly place them in my database. The first thing to do is create variables from all the checkboxes: $coke = $_POST['coke']; $rootbeer = $_POST['rootbeer']; $pepsi = $_POST['pepsi']; $drpepper = $_POST['drpepper']; etc. etc. Now that I have all 10 selections as variables from a submitted form how can I determine which ones are empty (or which ones have values) so that I can then save them to the database respectively? I have a Unique Constraint setup on (emailAddress and pin) to allow multiple email addresses be the same and multiple pins but not the same emailAddress and pin value together (unique(emailAddress, pin)) Anyway, I am trying to generate a pin through a random seed, but I can't get my code to work properly to test if the combination already exists. Here is the chunk that does not work: Code: [Select] $tries = 0; $foundRows=0; do { $pin=null; $tries++; $pin = str_pad(rand(0,9), 4, "0", STR_PAD_LEFT); $stmt = $dbh->prepare("SELECT COUNT(*) FROM ajax WHERE emailAddress=:email AND pin=:pin LIMIT 1"); if ($stmt->bindParam(':email', $email, PDO::PARAM_STR) && $stmt->bindParam(':pin', $pin, PDO::PARAM_INT)) { $stmt->execute(); $foundRows = $dbh->query("SELECT FOUND_ROWS()")->fetchColumn(); echo "<br />$foundRows<br />"; } else { die ("<p>Could not bind to data verification</p>"); } } while ($foundRows > 0); This is always returning $foundRows=0 so always exiting the loop, and giving me a constraint error. Any ideas? Maybe a better way to do this? I am pulling records from a mysql db. Example Output: Team A= Our Team Team b = An opponent team Team A score = 7 Team B score = 8 Team A = Our Team Team b = Another Opponent Team A score = 3 Team B score = 1 What I need now is to add ONE more output, which is whether this is a "WIN" or a "LOSS". Should I add a field into the table that calc's this? If so, how? Please be specific. Or, should I use php to compare Team A score vs Team B score PER every record and then insert this new variable into the output. If so, how do I create a new variable value for every single output in the table? I know ultimately that this is a IF THEN type of calc, but can't quite figure out how specifically. Please be specific. Thanks Hi, Competitors vs. against each other and are recorded in a database. Each participant equally has 4 matches each, as you can see in the attatchment following the points gained in their played matches. I want to be able to determine the qualified participants according to either their "points" or "wins/losses". If two competitors have the same points, then I have already made a solution that another match must be generated for the two participants with the same points and draws can not be submitted which means the points will always be different for each team. I want to pick out half of participants 8/16 (screenshot below) with highest points which will be the qualifiers, or pick out half participants 8/16 with best match stats according to wins/losses. Any help I would be very grateful, thanks. I can determine which radio button is selected for each file upload prompt because I have a name and a value. So the array name=image can have one of three values for each file upload prompt. Is there a way to determine which of the three file upload prompts was loaded (clicking browse & select image) with an image and which was not? There doesn't seem to be a value like there is with radio buttons. I want to be able to replace an already uploaded image with another. Thanks. <input type='radio' name='image[image0]' value='keep' checked='checked'/> <input type='radio' name='image[image0]' value='delete' /> <input type='radio' name='image[image0]' value='replace' /> <input type="file" name="image[]" /> <input type='radio' name='image[image1]' value='keep' checked='checked'/> <input type='radio' name='image[image1]' value='delete' /> <input type='radio' name='image[image1]' value='replace' /> <input type="file" name="image[]" /> <input type='radio' name='image[image2]' value='keep' checked='checked'/> <input type='radio' name='image[image2]' value='delete' /> <input type='radio' name='image[image2]' value='replace' /> <input type="file" name="image[]" /> if (isset($_POST['submitted']) && ($image = $_POST['image'])) { foreach($image as $imageKey => $imageValue) { if ($imageValue == 'keep') { do this } } } When I upload new files, their file name is stored into my database. I have been told that a couple of the file downloads weren't working. Upon further investigation I figured out that the file the person wanted to download was nowhere to be seen in my downloads directory. How can I determine if a file exists in my directory? I assume I can somehow use the location that is stored inside my database (ex: myfile.pdf) and compare that with what's in the folder. How to reliably determine if server is Apache using PHP? For example isApache() function? I have this function, but it doesnt work. Basically the list outputs a list of news features, and puts a line under neath each article to seperate them. However once the last article has been reached, I don't want the break to be shown. this is my code, any help would be appreciated as i am really struggling on this. Just need to determine the last item in the array, and stop the <hr split> from being output. function newsFeature(){ $event = "SELECT imgname, title, content, pkID from news ORDER BY date, time DESC LIMIT 5"; $event_page = query($event); $count = numRows($event_page); while ($row = mysql_fetch_assoc($event_page)) { $rowcount = $count; $para = substr($row['content'] , 0,100); $result .= '<article>'; $result .= '<a href="news-article.php?pkID=' . $row['pkID'] . '"><img src="uploads/thumbs/' . $row['imgname'] . '" alt="" width=116 height=83/ ></a>'; $result .= '<h2><a href="news-article.php?pkID=' . $row['pkID'] . '">' . $row['title'] . '</a></h2>'; $result .= '<p>' . $para . '...</p>'; $result .= '<p><a class="read-more" href="news-article.php?pkID=' . $row['pkID'] . '">Read more<span></span></a></p>'; $result .= '</article>'; if($row != end($row[])){ $result .= '<hr class="split">'; } } return $result; } Hey all, I would like to know the best way to determine whether a value has been changed in a multi select transfer. For example, I have two select fields. User clicks on button to add an item to the right select element with id of select2 from the left select element with an id of select1. When they click update, it posts to a php method. This is where I am uncertain what to do. How can I check that they indeed added or removed items from the right select element and if they did, determine which ones were removed or added to make the reflected changes in the database? This is what I have, but it's bad solution because it deletes all related records before it adds the ones it finds to the right select element: Code: [Select] public function update(){ $subcategory = new Category(); $subcategory->where('id',$this->uri->segment(4))->get(); $subcategory->delete($subcategory->related_category->get()->all); $new_parents = $this->input->post('catupload'); $parent_category = new Category(); $parent_category->where_in('controller',$new_parents)->get(); $subcategory->save($parent_category->all); } This is what the form elements look like: Code: [Select] echo "You can add or remove one or many parents associated with this category:"; echo "<div class='multiselect-transfer'>"; echo form_multiselect('catadd[]',$other_cats,'','id="select1"'); echo anchor('#','add >>','id="add"'); echo "</div>"; echo "<div class='multiselect-transfer'>"; echo form_multiselect('catupload[]',$default_cats,'','id="select2"'); echo anchor('#','<< remove','id="remove"'); echo "</div>"; echo form_submit('submit','Update'); echo form_close(); $other_cats variable holds array of categories that have not been asssociated with the current category being updated when this category was first created. The $default_cats variable holds an array of categories that have been associated with the current category being updated when this category was first created. And the javascript: Code: [Select] $().ready(function() { $('#add').click(function() { return !$('#select1 option:selected').remove().appendTo('#select2'); }); $('#remove').click(function() { return !$('#select2 option:selected').remove().appendTo('#select1'); }); }); Thanks for response. |