Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
You need to change the collation type of the field(s) that need to be accent insensitive. I'm no expert by any means of all the collation possibilities, but my tests show that using 'utf8_general_ci' collation in my local dev environment works. Most of my fields are set up with 'latin1_general_ci' which is case insensitive but not accent insensitive. When I changed to 'utf8_general_ci' and did a search for '%jose%' I was able to get the following records to display Jose josè Jóse
-
Can you provide more information? Are all the strings going to have the exact same pattern "[<<]"? Or can they use different patterns, e.g. "[<>][<>][<>][<>]" If the paterns will always be "[<<]" then you can simply use preg_match(). If the patterns can vary, but will be in a fixed "list" of patterns then you can use the same logic. However, if the patterns will vary with no known list to compare against it will be much more difficult as you will probably need to build a looping function to try and determin the pattern.
-
There's not enough information there to really provide an answer. You should probably try some simple debugging approaches to try and isolate various parts of the functionality to try and determine the cause. My first thought would be to take just the code above for actually sending the email and put it into a page all by itself (just hard code the variables). Then call the page through your browser. Do you get two emails? If so, then the problem sounds as if it might be server related and not PHP. If the above works correctly (one email) then I would probably set up a test taking the AJAX component out of the equation. And so on. The idea is to try and remove all variable but one or remove only one variable at a time. And, validate, validate, validate: in addition to using the JavaScript alert, have it alert some useful information and add thers as needed so you can see the values of variables as they are set or changed. And do the same thing in the PHP code to echo values to the page. Hmmm... after looking closer at the code I'm not understanding the line that sends the email. Where is $qryGetEmail defined and where are you actually running the query? I would suggest running the query and saving the result to a string variable - THEN run the mail() function. You can then verify that the address is correct by echoing it to the page.
-
PHP Store - Products in multiple categories?
Psycho replied to tonymcquaid's topic in PHP Coding Help
Here's an example of what an existing query might look like and how it would be modified: Example existing query to get details for a single product (including the category) SELECT * FROM products JOIN category on products.cat_id = categories.cat_id WHERE prod_id = '$id' New query where categories are in an associative table SELECT * FROM products JOIN prod_cat ON products.prod_id = prod_cat.prod_id JOIN categories ON prod_cat.cat_id = categories.cat_id WHERE prod_id = '$id' Note this will return multiple records based upon how many categories the product is associated with. Use the first record to get the product details and all the records to get all the category names -
PHP Store - Products in multiple categories?
Psycho replied to tonymcquaid's topic in PHP Coding Help
According to that tutorial you have a category table (to describe the categories) and a product table which includes a field to specify the category id. SO, you are left with a 1-to-1 relationship where a product can be assigned to one, and only one, category. But, you want a one to many relationship. The solution is to create an intermediary table (e.g. prod_cat) and remove the category id field from the product table. The new table would only need two fields: the category id and the product id. You can then associate a product to as many categories as you wish. Howevever, you will have to review all your existing queries that pull data from the product table and modify them as needed to JOIN the new table. -
Both 'day' and 'days' work for me. 'days' would probably read better to someone looking at the code.
-
Not sure about the first problem, but the second problem seems pretty obvious to me. On this line are you meaning to assign a value to $queryString or are you wanting to do a comparison? = vs. == if($queryString = $_SERVER['QUERY_STRING'])
-
Ok, here's a more compact version: //Check Detail Date //grab year from stored date $Detail_Sheet = substr($Detail_Sheet, 0, stripos($Detail_Sheet, "-") ); //Check it against current year $d_class = ($Detail_Sheet >= date(Y, strtotime("-14 day"))) ? 'complete': 'notcomplete'; Creating the variable $d_icon is a waste. Just use the variable $d_class when you need the icon. echo "<img src=\"images/{$d_class}.png\">";
-
Here's simpler solution. Just change the following line in your original script $y = date(Y, strtotime("-14 day")); On the first 14 days of the year $y will still be set to last year's value. If it will be possible for people to fill out the form for the current year during the first two weeks of the yesr, then change the comparison from == to >=
-
What exactly isn't working? Are you getting any errors? What have you validated and what haven't you validated? Don't expect us to do all the work for you. You should be able to validate what parts of the code are working properly and at least narrow down what part is not working correctly. Then you can provide the section of code that is in error and describe what it is doing differently than you expect. For example: When the form is submitted, is the data saved to the database correctly? Is the email sent? Etc.
-
Here's a decent tutorial on regular expressions should you wish to learn more. It is one of the more abstract concepts in programming in my opinion. So be prepared to invest some time if you want to master it: http://www.regular-expressions.info/tutorial.html
-
advise on planning multi lingual website interface
Psycho replied to dflow's topic in PHP Coding Help
Here is a function (with example usage) I have used in the past to determine the correct language to show a user on page load. You need to give the user a method of choosing their language (or you can try and dynamically determine it through browser settings via JS or PHP). The script will assign the users "selected language" if chosen, if not selection was made it will chack if there is a selected language for the session, if not it will check if a cookie is set, if not the default language is used. <?php // Function: getLanguage($languageList [, $selectedLang] [, $defaultLang]) // // Parameters: // - $languageList: (Required) An array of all available languages for the user // - $selectedLang: (Optional) The language the user has selected (GET or POST) // - $defaultLang: (Optional) the default language to use if unable to determine // user's language from seleted or saved values. function getLanguage($languageList, $selectedLang=null, $defaultLang=null) { //Set the default value (or first option in $languageList) $userLanguage = (!in_array($defaultLang, $languageList)) ? $languageList[0] : $defaultLang; //Detemine selected/saved user language if (!is_null($selectedLang) && in_array($selectedLang, $languageList)) { //Request was made to change the language $userLanguage = $selectedLang; setcookie('language', $userLanguage, time()+3600*24*365); //Expires in 1 year $_SESSION['language'] = $userLanguage; } else if (isset($_SESSION['language']) && in_array($_SESSION['language'], $languageList)) { //There is a saved language value in the SESSION data $userLanguage = $_SESSION['language']; } else if (isset($_COOKIE['language']) && in_array($_COOKIE['language'], $languageListAry)) { //There is a saved language value in the COOKIE data $userLanguage = $_COOKIE['language']; $_SESSION['language'] = $userLanguage; } //return the user's language return $userLanguage; } //Example usage // //Create list of available languages $languages = array ('Spanish'=>'sp', 'French'=>'fr', 'English'=>'en'); //Get the language to show the user $currentLanguage = getLanguage($languages, $_GET['lang'], 'en'); //Create vars for illustrative purposes $sessionLang = (isset($_SESSION['language'])) ? $_SESSION['language'] : 'Not set' ; $cookieLang = (isset($_COOKIE['language'])) ? $_COOKIE['language'] : 'Not set' ; ?> <html> <body> Current language: <?php echo array_search($currentLanguage, $languages) . " ($currentLanguage)"; ?> <br /><br /> $_GET['lang']: <?php echo $_GET['lang']; ?><br /> Session language: <?php echo $sessionLang; ?><br /> Cookie language: <?php echo $cookieLang; ?><br /><br /> Change Language <?php foreach ($languages as $name => $value) { echo "<a href=\"?lang={$value}\">{$name}</a> "; } ?> </body> </html> -
advise on planning multi lingual website interface
Psycho replied to dflow's topic in PHP Coding Help
Not sure what you mean by that. But, I'll throw out some ideas. In my opinion there is no one right way to do this. The best solution will depend on factors such as how big is the website, how many pages are there, how many languages will there be, and how often you will add languages or modify the site. To begin, you should create all your pages with placeholders where the text will be. Example: echo "$__SALUTATION__, $username"; where $__SALUTATION__ is a placeholder which will come from the language data. The next step is to determine how you will store the language content. You can store the language content in separate files for each module. Just create a directory structure where the folders are named according to the language (en, de, sp, fr, etc) and create the PHP code to pull the right file for the appropriate language. Each file has the value for each placeholder used in that module for the language. This is probably the easiest solution as it is easy to maintain. Alternatively, you can store the language data in the database. I would probably do something similar as above by storing the language data in a single table with columsn such as "module", "language", "placeholder", "text". Because you don't need ALL the text on any given page, you can query just the language data for the module that you are in. Then insert the values in place of the placeholder. A database has the advatage that you can add/remove languages easily (assuming you already have the translations). One note of caution: creating a site in multiple languages isn't as straitforward as doing a literal translation. If you have sentences that are dynamic (uses a person's or product's name, includes dates, etc) the placement and gender of words can be quite different from one language to another. And, something as simple as a link to the home page can't be literally translated. For example, in English you might just have a link that says "Home". But, home in English really has multiple meanings: it can be a physical structure or a place/concept. The literal translation to Spanish would be "Casa", a physical structure. And, that would make no sense as a home page for a website. Instead, Spanish uses something like "página inicial" or "Inicio". So, try to think critically of any text content you create to try and avoid these pitfalls. Also, be sure to plan the "layout" to accomodate different lengths of text. What may be a short word in one language may be quite long in another. If the layout isn't dynamic enough a long translation can screw up the layout. For example, for forms it is best to put the label above the field instead of to the left of the field. -
Retrieving Query Results -- Not connecting to database
Psycho replied to BrentonHale's topic in PHP Coding Help
Add an or die() to the mysql_query() line to see what errors may be occuring. Are you getting any errors currently? -
No need to create a foreach loop to count all the values when you can do it with a single function call (although I would still recommend fixing the session data). I also noticed that the query is outside the IF procedure, so if no cart data exists in the session, the query is still run. This should do the same thing as above, but a little more efficiently: <?php //INSERT ORDER DETAIL RECORDS if (isset($_SESSION['cart'])) { $cart = array_count_values($_SESSION['cart']); foreach ($cart as $id=>$var) { $vals[] = "('{$id}', '{$var['count']}', '{$OrderID}'"; } $sql = "INSERT INTO `cart_table` (ProductID, QtyOrdered,OrderID) VALUES " . implode(',', $vals); mysql_query($sql); } ?>
-
Your session data does not contain all the information needed per your original request. The session data only seems to contain the product IDs, the total cart price and the total cart quantity. It does not contain the price of each product. I suspect you could get the price per product from the database using the product IDs. In which case you do not need to add that to the cart information unless you are adding it for historical reasons (i.e. the price changes after the order was submitted and you need to know how much it sold for in that order) But the manner in which you are storing the cart information requires additional processing to determine the quantity of each product. I would suggest changing how you are storing the session data. Do not store all the product IDs as a single string value separated by commas. Instead, I would store the cart data using the ID as the key and the quantity as the value. Something like this: array( ["cart"]=> array ( [3] => 4, [2] => 2, [4] => 1, ) ["ORDER_TOTAL"]=> 60.15, ["TOTAL_PROD"]=> 7 ) Also, why do you want to add each product individually to the database when you can add them all in one query. Example: INSERT INTO table (cartID, productID, productQty, productCost) VALUES (99, 3, 4, 3.33), (99, 2, 2, 2.22), (99, 4, 1, 4.44)
-
Retrieving Query Results -- Not connecting to database
Psycho replied to BrentonHale's topic in PHP Coding Help
I just noticed that you do a mysql_close() right after connecting to the database - so none of the queries would actually run anyway. Although I suspect you're not even getting a connection due to the server failing. Here is a complete rewrite (may be some minor syntax typos): <?php # Script 7.4 - view_users.php // This script retrieves all the records from the users table. // Connect to the db require_once ('mysql_connect.php'); $link = mysql_connect('localhost', 'username', 'password'); if (!$link) { die('Could not connect to db server: ' . mysql_error()); } // make sitename the current db mysql_select_db("sitename") or die(mysql_error()); $query = "SELECT * FROM users"; $result = mysql_query($query) or die(mysql_error()); // Make the query. $query = "SELECT CONCAT(last_name, ',', first_name) AS name, DATE_FORMAT (registration_date, '%M %d, %Y') AS dr FROM users ORDER BY registration_date ASC"; $result = @mysql_query ($query); // Run the query. if (!$result) { //Query did not run successfully. $output = "<p class=\"error\">The current users could not be retrieved. We apologize.</p>"; // Public message. $output .= "<p>" . mysql_error() . "<br /><br />Query:{$query}</p>"; // Debugging message. } else { //Query ran OK, create the output of records. // Table header. $output = "<table align=\"center\" cellspacing=\"0\" cellpadding=\"5\">\n"; $output .= "<tr><td align=\"left\"><b>Name</b></td><td align=\"left\"><b>Date Registered</b></td></tr>\n"; // Fetch and print all the records. while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) { $output .= "<tr><td align=\"left\">{$row['name']}</td><td align=\"left\">{$row['dr']}</td></tr>\n'; } //Close output table $output .= "</table>\n"; // Free up the resources. mysql_free_result ($result); } // Close the database connection. mysql_close(); //Create the page output $page_title = 'View the Current Users'; include ('./header.html'); // Page header. echo "<h1 id=\"mainhead\">Registered Users</h1>"; // Page output echo $output; // Page footer include ('./footer.html'); // Include the HTML footer. ?> However, the problem probably does lie in the 'mysql_connect.php' file, which is why scvinodkumar stated we need to see that code. -
Add this to your delete page after the include mysql_connect('localhost',$username,$password); @mysql_select_db($database) or die( "Unable to select database");
-
There are a few different issues. 1. That code is way more complex than it needs to be. There is a lot of "logic" in there to extract and display the records that is not needed. A simple while loop with mysql_fetch_assoc(), or similar function will provide all the logic for stepping through the records and providing variables to display. 2. You are putting a button withing anchor tags. That doesn't work. You would either need to a) create a standard text link or b) create mini forms with the buttons as submit buttons. I'll provide an example with just text links. There is a third option of using JavaScript onthe buttons, but that again introduces unneeded complexity. 3. That code is using short tags (i.e. <?). That's not good programming standard as not all servers will support that. 4. There are problems with the HTML. For instance, each loop is opening a new DIV but never closing them. <?php ini_set("display_errors", "1"); error_reporting(E_ALL); include("dbinfo.php"); mysql_connect('localhost',$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $query = "SELECT `stitle`, `sdescription`, `sbody`, `sid` FROM simple_search ORDER BY sid"; $result = mysql_query($query); if (!$result) { //Temporary error handling echo "There was a problem:<br />".mysql_error(); } while($record = mysql_fetch_assoc($result)) { echo "<br /><br />"; echo "{$record['sid']} {$record['stitle']} {$record['sdescription']} {$record['sbody']} "; echo "<a href=\"deletePage.php?sid={{$record['sid']}}\">Delete</a>\n"; } ?>
-
This is a hack solution, but it does work (assuming you don't have two LI items with the same text <html> <head> <script> function getIndex(obj) { var liText = obj.innerHTML; var ulObj = obj.parentNode; var liLength = ulObj.childNodes.length; for(var i=0; i<liLength; i++) { if (ulObj.childNodes[i].innerHTML==liText) { return i; } } return false; } function alertIndex(obj) { alert(getIndex(obj)); } </script> </head> <body> <ul id="ul_obj"> <li onclick="alertIndex(this);">Zero</li> <li onclick="alertIndex(this);">One</li> <li onclick="alertIndex(this);">Two</li> </ul> </body> </html>
-
Retrieving Query Results -- Not connecting to database
Psycho replied to BrentonHale's topic in PHP Coding Help
The error checking on the database connection is wrong. Should be a "!" in the IF condition. See if that helps. $link = mysql_connect('localhost', 'username', 'password'); if (!$link) { die('Could not connect: ' . mysql_error()); } -
No errors in the code? Did you check it like I showed? If there is an error int he query you will not see an error unless you check for it. If the query is valid then there is no reason why it won't update correctly. So, the likely problem IS the query. So, echo the query to the page regardless if it fails or not. If the query isn't failing then the problem should be the session value doesn't match the records you are wanting to update.
-
If your query is failing then verify the query (Note: "or die()" should only be used for ad hoc debugging and should never be in your final code. Better to implement real error handling for final code). $query = "UPDATE members SET locations = '{$loc_leader}' WHERE leader='{$_SESSION['SESS_LEADER_NAME']}'"); mysql_query($query) or die (mysql_error()."<br />{$query}");
-
How do I call a function which is set in another page?
Psycho replied to c-o-d-e's topic in PHP Coding Help
Yes it is just that simple. When you "include" a php file in another it is almost exactly the same as if the code from the included file was written in-line to where it was included. -
No need to do a second query to get the perm value, just grab it with the first query. Try this <?php // Connects to your Database ... //checks cookies to make sure they are logged in if(!isset($_COOKIE['ID_staples_clubs']) || !isset($_COOKIE['Key_staples_clubs'])) { //Cookie values not set, redirect to login header("Location: login.php"); } //Cookie values are set, run query $username = mysql_real_escape_string($_COOKIE['ID_staples_clubs']); $pass = mysql_real_escape_string($_COOKIE['Key_staples_clubs']); $query = "SELECT `perm` FROM `members` WHERE `username`='$username' AND `password`='{$pass}'"; $result = mysql_query($query)or die(mysql_error()); if (mysql_num_rows($result)!=1) { //No match for Username/password, redirect to login header("Location: login.php"); exit(); } //Check for admin $userInfo = mysql_fetch_assoc($result); if ($userInfo['perm']==1) { //Redirect to admin header("Location: admin.php"); exit(); } //Not an admin, show member page echo "{$userInfo['name']} <br />\n"; echo "Welcome, "; echo "{$userInfo['adv']} <br />\n"; echo "<a href=\"edititem.php?id={$userInfo['club']}\">Edit Club</a>"; echo "<br />\n"; echo "<a href=\"changepass.php\">Change password</a><br />\n"; echo "<a href=\"logout.php\">Logout</a>\n"; ?>