Psycho
Moderators-
Posts
12,159 -
Joined
-
Last visited
-
Days Won
130
Everything posted by Psycho
-
I see a few potential problems: $crewchk = mysql_query("SELECT crew FROM users WHERE username='$username'"); $crewboss = mysql_query("SELECT owner FROM crews WHERE owner='$owner'"); You run those two queries and assign the results to those two variable. THEN you try and use those two variable in an INSERT query. Those variables are not values, they are resource IDs to the result fo the queries. You need to extract the values. mysql_query("INSERT INTO `inbox` ( `id` , `to` , `from` , `message` , `date` , `read` , `saved` , `event_id` ) VALUES ( '', '$crewboss', '$username', 'You have a member ready to be promoted to $newrank! Let him rank?', '$date', '0', '0', '0' )"); Why include `id` in the INSERT if you are not going to provide a value? }elseif ($crewchk == "0"); mysql_query("UPDATE users SET rank='$newrank' WHERE username='$username'"); Not even sure what that is supposed to do. You have a semicolon after the elseif clause so the elseif ends there and all code after it will be run without regard to the else if. You should format your code with some structure and add error handling/checking to find errors easier. The example below uses an "or die()" on the queries. It is fine for quick validations but shoudl not be included in your final code. I prefer to build my own query error handler to prevent error messages going to the user with technical data. <?php if (!$done) { $done="0"; } if ($done == "1") { $query = "SELECT crew FROM users WHERE username='$username'"; $result = mysql_query($query) or die ("Error:<br>".mysql_error()."<br><br>Query:<br>$query"); $crewchk = mysql_result($result, 0, 'crew'); $query = "SELECT owner FROM crews WHERE owner='$owner'"; $result = mysql_query($query) or die ("Error:<br>".mysql_error()."<br><br>Query:<br>$query"); $crewboss = mysql_result($result, 0, 'crew'); $query = "INSERT INTO `inbox` (`to`, `from`, `message`, `date`, `read`, `saved`, `event_id`) VALUES ('$crewboss', '$username', 'You have a member ready to be promoted to $newrank! Let him rank?', '$date', '0', '0', '0')"; $result = mysql_query($query) or die ("Error:<br>".mysql_error()."<br><br>Query:<br>$query"); } elseif ($crewchk == "0") { $query = "UPDATE users SET rank='$newrank' WHERE username='$username'"; $result = mysql_query($query) or die ("Error:<br>".mysql_error()."<br><br>Query:<br>$query"); $query = "INSERT INTO `inbox` (`to`, `from`, `message`, `date`, `read`, `saved`, `event_id`) VALUES ('$username', '$username', 'You have been promoted to $newrank your doing well!', '$date', '0', '0', '0')"; $result = mysql_query($query) or die ("Error:<br>".mysql_error()."<br><br>Query:<br>$query"); } ?>
-
Hard to say without seeing the "actual" query and the error that is generated.
-
[SOLVED] To infinity: And beyond! (A question regarding loops)
Psycho replied to Szandor's topic in PHP Coding Help
OK, that really doesn't answer my question. I guess I shouldn't have defined such an edge condition. For the 2nd scenario (where there are no replacements that can be made when the max iterration is reached) an error can work. But, how the first scenario should be handled is still unclear. Let's say that on the 30th iterration a tag is replaced with two tags. Do both tags then start looking for a replacement starting at 31? As I stated previously, once you start splitting the possibilities it becomes much harder to control the count of iterrations. But, I'll give it a shot. -
[SOLVED] To infinity: And beyond! (A question regarding loops)
Psycho replied to Szandor's topic in PHP Coding Help
I started to modify my original script last night to work with your example input file, but the issue I raised at the end of my last post makes this problematic. Specifically, your data shows that you may replace a single tag with two tags. So, imagine the follwing situation: 1. You are replacing a tag and it is continually replaced with other tags (which is the reason for this post, right?). You have it set to only allow up to 50 replacements, but on iterration #49 the tag is then replaced with TWO tags. What should happen at that point? Does the first new tag count as the 50th iterration and the second new tag starts over again? If so, then there is still a potential for an infinite loop. To add to that, let's say the iterrations reach 50 and you want to ensure a new replacement is not a new tag. What if the last iteration is a tag that only contains sub-tags. What should happen in that situation? I was actually pretty close to completing the code to work against your example data file, but didn't want to spend time coding for a solution that was not intended. It would have been extremely helpful if you had provided the full example data file in your first post instead of just a modified sample. If you want to answer the questions above I may be able to put something together tonight. I don't have the code with me at the moment. -
[SOLVED] To infinity: And beyond! (A question regarding loops)
Psycho replied to Szandor's topic in PHP Coding Help
The code I provided DOES process every tag independantly and it DOES account for an infinite loop. If you run the code exactly as I posted it, it works fine. You did not provide an example of your template file so I had to improvise. The code would just need to be modified to work with your specific import file. Using the code I provided I ran the following input text with the same tag repeated several times and the duplicate tags are replaced indipendantly: Input: I like {NICE} but not {BAD}. I like {NICE} too. Output #1: I like badgers but not smelly socks. I like cartoons too. Output #2: I like dessert but not evil clowns. I like dessert too. Output #3: I like lego but not dogs. I like cartoons too. However, one thing that is not accounted for is when a single tag is replaced with multiple tags. That was not in the original details. That will be much more difficult to handle. I is easy enough to count the itterations on a single replacement, but if you replace a tag with two tags do the previous itterations count for both, do they start over, or what? It will be much more difficult to track. -
I was not referring to the looping process to extract the data from the result set. One mistake I see a lot is where people do not know how to do a JOIN and instead query the parent table and then loop through each record to do a subsequent query on a child table. These "looping queries" are incredibly inefficient and will generate much longer load times.
-
5000 records does not seem terribly large. I would suspect either the database server is not adequate or the query is not efficient. I surely hope you are not running queries in a loop.
-
[SOLVED] To infinity: And beyond! (A question regarding loops)
Psycho replied to Szandor's topic in PHP Coding Help
This should work for you (tested). Just change $maxItterations in the replaceTag() function to whatever value you think is appropriate. <?php function processInput($text) { return preg_replace_callback('/{([^}]*)}/', replaceTag, $text); } function replaceTag($match, $itterations=1, $maxReached=false) { $maxItterations = 3; global $tags; $match = (is_array($match)) ? $match[1] : $match; $newTag = $match; //Replace tag if( isset($tags[$match]) && count($tags[$match])>0 ) { $replacements = $tags[$match]; //Remove subtags from replacements if max itterations reached if($maxReached) { foreach($replacements as $key => $value) { if (preg_match('/^{.*}$/', $value)!==0) { unset($replacements[$key]); } } } //Set replacement tag $newTag = $replacements[array_rand($replacements)]; } //== Thi line for debugging/illustrative purposes only echo "Itteration: $itterations, Match: $match, New Tag: $newTag<br />\n"; //Replace again if subtag if (preg_match('/^{.*}$/', $newTag)!==0) { //Get new replacement $match = substr($newTag, 1, strlen($newTag)-2); $newTag = replaceTag($match, ++$itterations, ($itterations==$maxItterations)); } return $newTag; } //Read the tags file and process into an ordered array $tagList = file('tags.txt'); $tags = array(); $tagLabel = false; foreach($tagList as $tag) { $tag = trim($tag); if (preg_match('/^\[.*\]$/', $tag)) { $tagLabel = substr($tag, 1, strlen($tag)-2); } elseif ($tagLabel!==false && !empty($tag)) { $tags[$tagLabel][] = $tag; } } $input = "I like {NICE} but not {BAD}."; $output = processInput($input); echo "<br/><br />"; echo "Input: $input<br />\n"; echo "Output: $output"; ?> I used an exagerrated replacements file for testing purposes so I could ensure the code would stop allowing subtags after a certain itteration: tags.txt [NICE] dessert lego {ANIMALS} {ANIMALS} {ANIMALS} {ANIMALS} {ANIMALS} {ANIMALS} {ANIMALS} {ANIMALS} {ANIMALS} cartoons [bAD] tummyache evil clowns smelly socks dogs [ANIMALS] {NICE} {NICE} {NICE} {NICE} {NICE} {NICE} {NICE} {NICE} {NICE} cats cows ducks badgers -
[SOLVED] To infinity: And beyond! (A question regarding loops)
Psycho replied to Szandor's topic in PHP Coding Help
Then why didn't you STATE that you want to limit it to some arbitrary number? You need to be very precise in your needs to prevent us from wasting our time. Oh, another question that needs to be answered is what should happen if the same tag appears twice in the input. Should it have the same replacement or can it have different replacements. The solution will be different. -
[SOLVED] To infinity: And beyond! (A question regarding loops)
Psycho replied to Szandor's topic in PHP Coding Help
OK, I'm going to lay out some assumptions here. First, I *assume* that ther may be more lists with "sub tags" as in your example of the list above with {ANIMALS} appearing in the [NICE] list. I also assume that if {ANIMALS} is the randomly selected item under [NICE] that you would want it replaced with a legitimate value under [ANIMALS] - i.e. not another subtag if there are any. I'll put something together and post momentarily. -
[SOLVED] html entities converts pound (£) incorectly?
Psycho replied to Dragen's topic in PHP Coding Help
Works fine for me. May be a problem due to the region settings on the server or the client. Can you post example of the EXACT input and the EXACT output. For the output, I am referring to the raw HTML code, not what is displayed in the browser. -
My pleasure. I hope you noticed that you can easily change the number of columns to be used using that first variable.
-
Try this. There is no need to use GLOB_BRACE since you only have one parameter in the braces. Instead you should use GLOB_ONLYDIR to get only the directories. Then there is no need to check for the index.php file. <?php $max_columns = 3; $directories = glob('*', GLOB_ONLYDIR); //Create table output $current_column = 1; foreach ($directories as $folder) { if ( $current_column == 1) { $tableOutput .= "\t<tr>\n"; } $folder = str_replace('_', ' ', $folder); $tableOutput .= "\t\t<td>{$folder}</td>\n"; if ( $current_column++ == $max_columns) { $tableOutput .= "\t</tr>\n"; $current_column = 1; } } //Close last row if needed if ($current_column!=1) { for(; $current_column<=$max_columns; $current_column++) { $tableOutput .= "\t\t<td> </td>\n"; } $tableOutput .= "\t</tr>\n"; } ?> <html> <head></head> <body> <table border="1" cellpadding="0"> <?php echo $tableOutput; ?> </table> </body> </html>
-
Yeah, I'm not really sure what you are trying to accomplish as what you state above does not correlate witht he code you posted. You state that you want a list of directories. BUt the code you posted would get all the directories and files within a single folder and then looks like it would display a record in the table for each folder and file in the directory. Can you explain a little more exactly what you are trying to accomplish?
-
Can't seem to capture a variable in a chained select
Psycho replied to 86Stang's topic in PHP Coding Help
Then the query is failing. As my signature states I don't always test my code - especially when the code requires someone else's database. On the line above, change this $result = mysql_query($query); To this: $result = mysql_query($query) or die("$query <br><br>".mysql_error()); That should identify the problem. Also, to prevent sql injection, change this $selectedState = (isset($_POST['state'])) ? $_POST['state'] : false; To This $selectedState = (isset($_POST['state'])) ? mysql_real_escape_string($_POST['state']) : false; -
Can't seem to capture a variable in a chained select
Psycho replied to 86Stang's topic in PHP Coding Help
Keep your code organized and it is much easier to work with and debug. This is not tested <?php require ('inc/connection.php'); //Get selected state if set $selectedState = (isset($_POST['state'])) ? $_POST['state'] : false; //Create the State options $stateOptions = "<option value=\"\">State</option>\n"; $query = "SELECT id, name FROM state ORDER BY name ASC"; $result = mysql_query($query); while($row = mysql_fetch_array($result)) { $selected = ($selectedState && $row[0]==$selectedState) ? ' selected="selected"' : ''; $stateOptions .= "<option value=\"{$row[0]}\" onClick=\"this.form.submit();\"{$selected}>{$row[1]}</option>\n"; } //Create the City options if ($selectedState===false) { $cityOptions = "<option value=\"\">Select a state</option>\n"; } else { $cityOptions = "<option value=\"\">Select a state</option>\n"; $query = "SELECT * FROM city WHERE state_id = {$selectedState}"; $result = mysql_query($query); while($row = mysql_fetch_array($result)) { $stateOptions .= "<option value=\"{$row[0]}\" onClick=\"this.form.submit();\">{$row[1]}</option>\n"; } } ?> <form name="form" method="post" action=""> <select name="state" style="font-size:20px;"> <?php echo $stateOptions; ?> </select> </form> <form name="form2" action="" method="post"> <select name="city"> <?php echo $cityOptions; ?> </select> </form> -
[SOLVED] List all files in a folder and define their names as vars.
Psycho replied to Repgahroll's topic in PHP Coding Help
The $loop variable in that code has no purpose/functionality. Also, explode is a poor implementationof trying to ascertain the base file name since a file *may* inlcude additional periods in the file name. Also, that code does not handle situations where there is a 'dae' file but no corresponding 'jpg' file. But, that can serve as a means of identifying those gaps. Here is wha I would suggest. Create an image to be used where there is no corresponding image file for the dae file (e.g. 'missingImage.jpg'). Then use the code below. <?php foreach(glob('*.dae') as $modelFile) { $basename = basename($modelFile, '.dae'); $imageFile = (file_exists("{$basename}.jpg")) ? "{$basename}.jpg" : "missingImage.jpg"; echo "<a href=\"{$modelFile}\"><image src=\"{$imageFile}\"></a><br />\n"; } ?> -
[SOLVED] List all files in a folder and define their names as vars.
Psycho replied to Repgahroll's topic in PHP Coding Help
This should get you started (not tested): $filepath = 'images/'; //Get all respective files into arrays $images = glob($filepath.'*.jpg'); $models = glob($filepath.'*.dae'); foreach ($images as $imageName) { //Check that there is a corresponding model tot he image $baseName = basename($path, '.jpg'); if (in_array($baseName.'.dae', $models)) { echo "<a href=\"{$filepath}{$imageName}\"><image src=\"{$filepath}{$imageName}\"></a><br />\n"; } } -
number_format(): http://php.net/manual/en/function.number-format.php $number = 123456; echo number_format( ($number/100), 2); //Output: 1,234.56 echo number_format( ($number/100), 2, ',', ' '); //Output: 1 234,56 I showed the examples with a six digit number to show what happens with the thousands separator
-
When doing a JOIN without any criteria the code will join every record from the first table with every record from the second table. You need to proivde some 'logic' on which records you want joined to the others. Assuming the 'customers' table has an ID field aqnd the 'order_detail' table has a foreign key for the customer ID the query might look like this: SELECT * FROM customers INNER JOIN order_detail ON customers.id = order_detail.customer_id ORDER BY orderid DESC Not knowing your DB structure, that is only an example of how it should look like
-
As my sig states there will likely be syntax errors. I write the code with the logic in mind. Since I don't hae your database - and I'm too lazy to create one - I did not test the code. Try changing this $cat = (isset($_GET['cat']) ? $_GET['cat'] : false; To this $cat = (isset($_GET['cat'])) ? $_GET['cat'] : false; There's a good chance there are other syntax errors as well.
-
You don't define $cat (which you use to set the selected category option) until after you have created the category list! I went ahead and cleaned up the code <?php //Get selected category $cat = (isset($_GET['cat']) ? $_GET['cat'] : false; //Generate category options $catOptions = ''; $query = "SELECT CategoryName,CategoryID FROM category_list order by CategoryName"; $result = mysql_query($query); while($option = mysql_fetch_array($result)) { $selected = ($option['CategoryID']==$cat) ? ' selected="selected"': ''; $catOptions .= "<option value=\"{$option['CategoryID']}\"{$selected}>{$option['CategoryName']}</option>\n"; } //Generate subcategory options $subcatOptions = ''; $query = false; switch ($cat) { case 1: case 3: $query = "SELECT CountryID as value, CountryName as text FROM country_list ORDER BY CountryName"; break; case 2: $query = "SELECT CityID as value, CityName as text FROM city_list ORDER BY CityName"; break; } if ($query!==false) { $result = mysql_query($query); while($option = mysql_fetch_array($result)) { $subcatOptions .= "<option value=\"{$option['value']}\">{$option['text']}</option>\n"; } } ?> <html> <head> <SCRIPT language=JavaScript> function reload(form) { var val=form.cat.options[form.cat.options.selectedIndex].value; self.location='dd3.php?cat=' + val ; } function reload3(form) { var val=form.cat.options[form.cat.options.selectedIndex].value; var val2=form.subcat.options[form.subcat.options.selectedIndex].value; self.location='dd3.php?cat=' + val + '&cat3=' + val2 ; } </script> </head> <body> <form method="post" name="f1" action="dd3ck.php"> <select name="cat" onchange="reload(this.form);"> <option value="">Select one</option> <?php echo $catOptions; ?> </select> <select name="subcat" onchange="reload3(this.form);"> <option value=''>Select one</option> <?php echo $subcatOptions; ?> </select> <input type="submit" value="Submit the form data"> </form> </body> </html>
-
number_format() http://us3.php.net/manual/en/function.number-format.php
-
Your code is hard for me to follow, so i'm not going to try and decypher it. But, you never defined $currentPage as I stated needed to be done in my previous post. Or, you could have replaced it with $page looking at your code. I'm assuming that the include file is what shows the current records. Here is a rewite of that page. No guarantees it will work since I did not test it. <?php $thumbID = 3; $recordsPerPage = 1; //Get total records $query = "SELECT COUNT(*) as total FROM photos WHERE thumb_id = `{$thumbID}`"; $result = mysql_query($query) or die(mysql_error()); $totalRecords = mysql_result($result, 0, 'total'); //Determine total pages $totalPages = ceil($totalRecords/$recordsPerPage); //Determine current page $currentPage = (int) $_GET['pagenum']; if ($currentPage<1) { $currentPage = 1; } else if ($currentPage>$totalPages) { $currentPage = $totalPages; } //Get records for current page $start = ($currentPage-1)*$recordsPerPage; $query = "SELECT * FROM photos WHERE thumb_id = `{$thumbID}` LIMIT {$start}, {$recordsPerPage}"; $result = mysql_query($query) or die(mysql_error()); //Create page navigation section $pageList = array();; if ($currentPage>1) { $pageList[] = "<a href="?pagenum=1"><<</a>"; $pageList[] = "<a href="?pagenum=".($currentPage-1)."">< Previous Page</a>"; } for($page=1; $page<=$totalPages; $page++) { $pageList[] = ($currentPage==$page) ? "<b>[{$page}]</b>" : "<a href="?page={$page}">{$page}</a>"; } if ($currentPage<$totalPages) { $pageList[] = "<a href="?pagenum=".($currentPage+1)."">Next Page ></a>"; $pageList[] = "<a href="?pagenum={$totalPages}"><<</a>"; } $pageNav = implode(' ', $pageList); //Show current records include 'albumphotos.php'; ?> <div> <table width="100%"> <tr> <td> <?php echo $pageNav; ?> </td> </tr> </table> </div>