Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
How do I modify this code to include date range?
Psycho replied to sonnieboy's topic in PHP Coding Help
I'm not sure what is not understood by my post. Your query is currently using something such as $where[] = "".$field['field']." <= '" . ms_escape_string($_POST[$fieldPost]) . "'"; Well, a date in MySQL is stored in the format of YYYY-MM-DD. I provided sample code on how to format a date from mm/dd/yyyy into the format needed for a DB query. You now need to add logic to your code to determine which user submitted values are dates and then format them appropriately. Personally, I think trying to create automated processes to dynamically create a query such as the above are not worth the effort. You have to keep adding logic to handle differences in field types (such as dates) and in the end it becomes more code. -
How do I modify this code to include date range?
Psycho replied to sonnieboy's topic in PHP Coding Help
You'll need to format the dates into the format the the database recognizes: YYYY-MM-DD $sqlDate = date('Y-m-d', strtotime($inputDate)); -
Is there a way to format the date output of a function?
Psycho replied to OGBugsy's topic in PHP Coding Help
Yes, that's why I use PDO with named placeholder instead of '?'. Having code that assumes fields/variables are in a specific order is dangerous, IMO. I've seen examples where bugs were introduced because of this. One was where a new field was added to a table and the developer was using "SELECT *" (which is bad in and of itself). But, why create the potential for such a silly mistake to cause problems in the first place. -
Give this a try SELECT c.* FROM condo c JOIN test_log tl ON c.location LIKE tl.keyword AND c.sale_rent LIKE tl.sale_rent AND c.e_num LIKE tl.e_num WHERE (c.date >= '$sendate') AND TRIM(IFNULL(c.phone_1,'')) <> '' ORDER BY c.sale_rent, c.location
-
Is there a way to format the date output of a function?
Psycho replied to OGBugsy's topic in PHP Coding Help
Some suggestions (my opinioin): 1. Try not to push too much logic into a single line of code - it makes it difficult to debug errors and make modifications later. You have a single line to pull a record from the DB results and use list() to put into variables. I would simply put the results into $row - then perform any additional logic. 2. Also, I would not create code where variables/data is set based upon an assumed order. Why use list() when the results from a single DB record will already be a variable with an appropriate key to identify it. If you were to ever change your query you would have to ensure the order of the variables in list match. 3. The values for your options make no sense. The value of the options should only be the ID of the record. The only reason you would be putting all the variables into the value parameter would be if you are parsing that value on the recieving page - and that would be the wrong way to do it. By passing the ID you can get any values you need through a subsequent DB call. Here is a modification that adds the change for date you need while ($row = $res->fetch_row()) { $dateDisplay = date("jS F h:i A", strtotime($row['date'])); $label = "{$row['id']}, {$row['customer']}, {$row['salesman']}, {$row['status']}, {$row['location_address']}, {$dateDisplay}" $opts .= "<option value='{$row['id']}>{$label}</option>\n"; } -
Why do you "think" they match? Are there any white-space characters (e.g. spaces, tabs, etc.) in the file you are reading? You need to verify EXACTLY what those variables contain - echoing to the page isn't going to work Run this and you will see why PHP doesn't consider those values the same $string = file_get_contents('/path/to/file'); $found = 'found'; if($string == $found) { echo "string match"; } else { echo "string does not match found"; } echo "<br><br>String var: "; var_dump($string); echo "<br><br>Found var: "; var_dump($found);
-
What I posted will work with what you have currenlty
-
I see a lot of people running queries in loops - those are sure to kill performance. Here is what I would suggest: Create an array of values to measure the load time at specific points in the page creation. Then output the results so you can see how long each step in the process takes. Here is a quick example <?php $timings = array(); $timings['start'] = microtime(true); //Code to load include files goes here $timings['load_includes'] = microtime(true); //Code to run some DB operations $timings['run_db'] = microtime(true); //Code to build the page $timings['build_page'] = microtime(true); //Page execution done, create output to show times to complete each step $last = false; foreach($timings as $processDesc => $timing) { if($last != false) { $processTime = $timing - $last; echo "{$desc}: {$processDesc}<br>\n"; } $last = $timing; }
-
Nothing stands out as me as being wrong. The odd characters make it a little hard to read, but everything seems to be there that should be. A few thoughts: 1. A checkbox that is not checked will not be sent in the POST/GET data. I assume you are checking at least one value in the groups of checkboxes - else the array errors you are receiving would be correct. 2. It's possible that the character encoding is causing a problem. You could always try just using normal ASCII character isntead of Russian to verify if that is the problem 3. Why not just do a print_r($_POST) to verify exactly what IS sent in the form submission.
-
Typically, you shouldn't have calculated values in your tables (e.g. gross & net). you should calculate in your queries. Lots of reasons why that I won't go into. Plus, the "shots" would make more sense in a separate table with an individual record for each shot - instead of separate columns. I don't see a value for division in the table, so I didn't add any logic for that. The following query will do what you want. If first sorts on the 'net' score, then it sorts on h1, h2, etc. SELECT sc_id, playid, ppoints, net, h1, h2, h3, h4, h5, h6, h7, h8, h9 -- This line can be removed if not needed FROM scorecards ORDER BY net, h1, h2, h3, h4, h5, h6, h7, h8, h9
-
Isn't this data in a database? If so, you should be sorting the data when you retrieve it from the database (i.e. the SELECT query). This can be done via an array, but I don't want to waste time on a solution to sort the array if this is, in fact, derived from a database.
-
import csv file into mysql with file path in a textbox
Psycho replied to iojbr's topic in PHP Coding Help
Here's a simple tutorial: http://www.tizag.com/phpT/fileupload.php -
Having a condition that returns TRUE/FALSE is a waste of bytes. Simply return the results of the condition (which would be TRUE or FALSE). public function is_set($name, $type = 'post') { return (isset($this->{$type}[$name])); } public function is_empty($name, $type = 'post') { return (empty($this->{$type}[$name])); }
-
$urls = array( 'it.groups.yahoo.com/group/batmaras/links/', 'it.groups.yahoo.com/group/batmaras/links', 'it.groups.yahoo.com/group/batmaras/', 'it.groups.yahoo.com/group/batmaras' ); foreach($urls as $url) { echo "<br><b>INPUT:</b> {$url}<br>\n"; if(preg_match("#it\.groups\.yahoo.com/group/([^\/]*)#is", $url, $groupMatch)) { $groupName = $groupMatch[1]; echo "<b>GROUP NAME:</b> {$groupName}<br>\n"; $groupURL = "it.groups.yahoo.com/group/{$groupName}"; echo "<b>GROUP URL:</b> {$groupURL}<br>\n"; } else { //Did not match group name echo "<b>No Group Name found</b><br>\n"; } } Results INPUT: it.groups.yahoo.com/group/batmaras/links/ GROUP NAME: batmaras GROUP URL: it.groups.yahoo.com/group/batmaras INPUT: it.groups.yahoo.com/group/batmaras/links GROUP NAME: batmaras GROUP URL: it.groups.yahoo.com/group/batmaras INPUT: it.groups.yahoo.com/group/batmaras/ GROUP NAME: batmaras GROUP URL: it.groups.yahoo.com/group/batmaras INPUT: it.groups.yahoo.com/group/batmaras GROUP NAME: batmaras GROUP URL: it.groups.yahoo.com/group/batmaras
-
You should definitely NOT use RegEx for this. All you need is to use the existing function htmlspecialchars() whenever outputting user defined content to the page. You should also use the ENT_QUOTES flag when using it.
- 1 reply
-
- 1
-
Based on what I see, you are loading the "about us" content into an element on the page (e.g. a div). Is it a full HTML page with a head section? If so, that won't work. You already have a valid HTML page and are just loading content into it. You will probably want to have one CSS file that contains all the styles for all your pages. Same goes with the JS. But, I would think about what is being gained by not just opening the pages as normal links. It seems you are replacing most of the content anyway aside from the navigation and possibly a header/footer. What are you gaining by using AJAX to load the page? You are adding more complexity and possible errors to occur.
-
Just because something is not required does not mean it isn't "needed". I always put braces around my variables within double quoted text as a standard. That way I never have to worry about the times that not bracing the variable would cause a problem. EDIT: After reviewing the OPs code, I think the challenge he has is that he is using a function to create the select lists. Assuming that function is used for more than just this one specific list, he may not want the "id" included in the label for all the select lists. In that case, you can get the desired results by ensuring the input array for the function has the data you want before you call the function. Then there is no need to modify the function if it is working as you need it for other select lists. $WeekNos = array(); while($WkNo_info = mysqli_fetch_array($WkNoList_res)) { $WeekNos [$WkNo_info['WNo']] = "{$WkNo_info['WNo']} - {$WkNo_info['WCom']}"; } $WNo_Options = buildSelectOptions($WeekNos);
-
I'm not sure where you come to the conclusion that a properly normalized database is not easy or flexible. I really don't understand what you are working with or what you are trying to achieve. I've already invested a lot of time in this thread and don't seem to be getting closer to a resolution. I'll bow out now and hopefully someone else can provide the assistance you need.
-
I did not test the code as I don't have your DB (or enough information) to properly test it. But, the logic was sound based upon what I understood at the time. I expect the person using the code to find/fix any minor typos. As to your explanation, what you are doing doesn't make sense to me. You were running a loop as follows for($i=0; $i<$totalviewColors; $i++){ But, then were defining the color string value using $product_view_color[$i] But, in your example above, you stated that $totalviewColors for Product B would be 3 (with Black being used as a spacer). But, that product doesn't use the first color: Blue. Based on your original code, the first iteration of the loop would be using Blue, then with Red & Green. It woudl be completely out of sync with the actual colors you should be using. I think the whole logic here is problematic. There should be no reason to use Black as a NULL value anyway. Where is $totalviewColors even defined? And, you shouldn't be doing lookups based on a description value (such as color name) when those values have an ID. Based on your explanation, I *think* what you are really trying to accomplish is to pull the data specific to a product. So, you SHOULD have a table that defines the applicable colors for a product. Therefore, you should be able to create a single query that pulls the data you need by only providing the product ID as the variable data. Again, without a full understanding of the DB structure (which may be faulty) and the intended result I can't provide the right solution. Based on your explanation above, I would expect to have three tables similar to this color_charts_colors ----------------------------- ColorID | color_name | color_code 1 | Blue | #0000FE 2 | Red | #9E2337 3 | Green | #008A59 4 | Gray | #56595C 5 | White | #FFFFFF products ----------------------------- ProductID | Product_name 1 | Product A 2 | Product B products_color ----------------------------- ID | ProductID | ColorID 1 | 1 | 1 2 | 1 | 2 3 | 1 | 3 4 | 1 | 4 5 | 2 | 2 6 | 2 | 3 Then you can get all the color data related to a product using a query such as this SELECT ColorID, color_name, color_code FROM color_charts_colors ccc JOIN products_color pc ON ccc.ColorID = pc.ColorID WHERE pc.ProductID = $productID
-
You have an if/else condition at the beginning of the loop. That will run on each iteration of the loop. That is the cause of your problem. The logic will need to be rewritten, but I see other problems as well. For example, you are storing a calculated value for the total hours, that should be calculated in the query - not stored. Plus, I see there are two date values in the DB date & c_date. I think c_date is a formatted date - again you can format the date at run time - don't store duplicate data. Lastly, if you are only going to run this for a week, then you only need to define the start date. This code may have some minor errors as I did not create a DB or test data to ensure it was 100% accurate. But, the general logic is sound. <?php //This code assumes: // date is a date field type // start & end are datetime field types $start = "2015-3-30"; //March 30th $query = "SELECT date, start, end, TIMESTAMPDIFF(SECOND, start, end) as day_total FROM `timesheet` WHERE `date` >= CAST('$start' AS DATE) AND `date` <= DATE_ADD(CAST('$start' AS DATE), INTERVAL 6 DAY)"; $result = mysqli_query($db, $query); //Dump results into an array $records = array(); while($row = mysqli_fetch_assoc($result)) { $records[$row['date']] = $row; } //Create a loop from first to last date //for each day, check if there is a matching records //in the records array. If so, use that data //Else, there was no data for that date for($day=0; $day<7; $day++) { $timeStamp = strtotime("{$start} +{$day} day"); $dateStamp = date("Y-m-d", $timeStamp); $DOW = date("D", $timeStamp); $dateStr = date("m/d/Y", $timeStamp); //Set default values $startTime = '' $endTime = ''; $totalHours = ''; if(isset($records[$dateStamp])) { $startTime = $records[$dateStamp]['start']; $endTime = $records[$dateStamp]['end']; $totalTime = $records[$dateStamp]['day_total']; } //Output results echo "<tr>\n"; echo "<td class='tg-031e'>{$DOW} {$dateStr}</td>\n"; echo "<td class='tg-031e'>{$startTime}</td>\n"; echo "<td class='tg-031e'>{$endTime}</td>\n"; echo "<td class='tg-031e'>{$totalTime}</td>\n"; echo "<td class='tg-031e'></td>\n"; echo "<td class='tg-031e'></td>"; echo "</tr>\n"; } ?>
-
First, never run queries in loops. There are very few reasons why you would need to do that. And, unless you know those reasons, always assume a loop is not the answer and ask for help if you don't know how to get the data you need without a loop. Second, dealing with NULL and an empty string are two very different things when talking about database values. Without knowing if one or both are possible in the DB I can't provide the optimal code. But, what I have below should work. Third, not sure what the intended use of the data is here. If you really only want to create a string to output to the page, then what I provided below will work. Fourth, stop using the mysql_ functions. They are deprecated and will be removed in a future version of PHP. I suggest moving to PDO. I'm not sure of the real objective is of your code. You are creating a string from the IDs, but what for? Are you using them somewhere else? plus, you are pulling three values in the query, so what are the other two used for? I expect there is a better way to rewrite the code, but I would have to know what the end objective is to provide a better solution. But, I'm more concerned with why you have records without an ID to begin with. Typically, the ID field is a required field. I'm also not understanding the relationship between $totalviewColors and $product_view_color. Something definitely seems out of whack here. Here is my attempt at rewriting the code based on what was provided <?php //Trim the values in the product_view_color array $product_view_color = array_map("trim", $product_view_color); //Run ONE query to get all the results $query = "SELECT id, color_name AS name, color_code AS code, COUNT(*) FROM color_charts_colors WHERE color_name IN (" . implode(',', $product_view_color) . ") AND id <> "" AND id NOT NULL GROUP BY color_name ORDER BY color_chart_id DESC"; $result = mysql_query($query); //Populate results into an array, use ID as the index $item_colorsCODE = array(); while ($row = mysql_fetch_assoc($result9)) { $item_colorsCODE[$row['id']] = $row; } //Create a string to list the IDs (e.g. the array keys) $ItemString = "'" . implode("', '", array_keys($item_colorsCODE)) . "'"; //Calculate the count of returned values $countColors = count($item_colorsCODE); ?>
-
1. First, fix the closing NAV tag - it is currently an open tag <nav> Change to a closing tag </nav> 2. Put ".nav_main " at the beginning of all style elements that apply to the navigation controls. E.g. .nav_main ul {
-
My guess is that the string is likely generated from an array or DB query. If that is the case, then the empty values should be removed before it is converted to a string.
-
There's nothing wrong with that. It is perfectly acceptable to close a MySQL query with a semi-colon (although not required). But, you must have a semi-colon to close a PHP statement. So this is perfectly fine $query = "SELECT * FROM table_name;"; @timmah1, Follow ginerjm's advice and echo out the queries when there are errors. Change the "or die()" commands to something like this $custres = mysql_query($custsql) or die("Query: {$custsql}<br>Error: " . mysql_error()); NOTE: You should NEVER use "or die()" for error handling in production code, nor should you ever echo actual system errors to the page for the user to see. This gives away information about your application that a hacker could use to compromise your application and data. You should instead add appropriate error handling logic that gives the user a friendly, non-specific error message while logging the actual system error where only you can view it.
-
Perhaps you should provide some example strings that are not providing the results you expect. The code I provided works exactly as expected based upon the requirements you provided $line = "This is <div>some text</div> with a <div>div tag</div> in it."; $pattern = '/<div>(.*?)<\/div>/'; $matches = preg_match_all($pattern, $line, $found); echo "<pre>" . print_r($found, 1) . "</pre>"; Output: Array ( [0] => Array ( [0] => <div>some text</div> [1] => <div>div tag</div> ) [1] => Array ( [0] => some text [1] => div tag ) )