Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
I'm no security expert, but I think you may be taking the wrong approach. Several of the things you are doing have no value from my perspective. Each security measure you implement should have a purpose. Can you elaborate on what each of those methods is supposed to guard against? You say that users are trying to access user accounts. How are they doing this? Are they randomly attempting different username/password combinations? Have they actually gotten in? If these malicious users have already gained a user's credentials the processes you have will do nothing. Here are my observations on those processes: If you want your site to be secure then you should not store any sensitive information in a cookie. Even if it is encrypted you are sending the information over the wire where someone could capture it and attempt to decrypt it. And, why do you need to validate their login credentials on each page load. If the credentials passed once wouldn't they pass again (unless the user was disabled/deleted). Instead just store a user ID in a session variable upon successful login. Then on each page load check that that value is set - if so the user was successfully authenticated, no need to reauthenticate. but, if you need to check for disabled/deleted you could use that value to do that check. Storing the IP is fine, but decide what you are using this for. I don't see a need to check it on each page load since you can track the user via sessions. One possible use of the IP address is to prevent concurrent logins and/or provide a higher level of scrutiny at long. For example: 1) If you are tracking a user's activity on the site you could prevent someone from logging into the same user account while that account is logged in. Now, with a web app you can't really know if the user has closed their browser so you could just implement a time period. So, if the user was last active within the last 20-30 minutes don't allow them to log in again. 2) You could also use the IP address at the time of login to track the IPs that the user has used. So, if a user attempts to log in from a different IP address than they have used before you could require the user to go through an additional level of security. Then once authenticated store that IP. I know it used to be common for users to always have different IPs from their ISP, but I'm not sure that is the case anymore. If so, it could be a burden for some users. I see no problem in keeping track of the user's activity since you can use that for other purposes (see #2). Also, 60 minutes seems like a long time to be inactive. But, I don't know what your application is used for. But, I suspect that if users are getting logged out before the 60 minutes it may have something to do with this implementation. I don't understand what the purpose of this would be. You can already track the user through session data. Personally, I would not email the user every time there is a failed attempt. It could look bad on you, the provider. Notifying them after the account is locked makes sense though. however, I would log each failed login and perhaps send an email to yourself (or whoever should be monitoring security) when certain criteria are met. What that criteria is would be up to you. But one example would be attempts to log into multiple accounts from the same IP within a certain time period.
-
Yeah, there's no PHP code in that content at all. I'm guessing that you happened to find that the data in that file matched the data used for your application and that you modified that file with the expectation that it would change the corresponding information in the application. But, without knowing how the particular data in the application is actually determined there is no way to know how to change it. It could be that the file was used to generate other content that is actually used for displaying content on the site. For example, since this is a shopping site (based upon the titles cart, checkout and paypal) I have to assume that there is a database involved. It could be that the .conf file is used to set the initial values in the database. If that's the case there should be a way to rerun the setup script after making changes to the .conf file. I would also assume you are using some pre-built shopping cart script. I suggest you look for help on the site that supports that application as they would be of much more help.
-
That is the expected behavior for PHP. There are four different methods of defining strings in PHP: single quoted, double quoted, heredoc syntax & nowdoc syntax. Only in the double quoted and heredoc methods are variables parsed. Also, special escape sequences for things such as tabs (\t) and new lines (\n) will be parsed. See the documentation here: php.net/manual/en/language.types.string.php
-
The problem looks pretty obvious to me. Here is where you define your variables from the POST data $first_nameField = $_POST['first_name']; $last_nameField = $_POST['last_name']; $email_fromField = $_POST['email_from']; $telephoneField = $_POST['telephone']; $commentsField = $_POST['comments']; Here is where you define the body of the email $body = <<<EOD <br><hr><br> First Name: $first_name <br> Last Name: $last_name <br> Email: $email_from <br> Phone: $telephone <br> Comments: $comments <br> EOD; The variables you set from the POST data ($first_nameField, $last_nameField, $email_fromField, etc.) are not the variables you are using in the body of the email ($first_name, $last_name, $email_from, etc.) Try removing 'Field' at the end of all the variables you are setting from the POST data
-
I just noticed that in my sample code I used $row in the while loop but didn't change the variable in the while loop. They need to be the same. Anyway, if you are still not getting any data after fixing that, then the query is not getting any results. Add some debugging info to validate what is actually happening. Also, do a better job of structuring your code. That last bit you posted is - sorry to say - awful. $id = intval($_GET['id']); $query = "SELECT location FROM cities WHERE id = '$id'"; $result = mysql_query($query) or die(mysql_error()); //Debugging info echo "The GET value for id is {$_GET['id']}<br>\n"; echo "The value for the id variable is {$id}<br>\n"; echo "The query is: {$query}<br>\n"; echo "The query generated " . mysql_num_rows($result) . " results<br>\n"; while($row = mysql_fetch_assoc($result)) { echo "{$row['location']}<br>\n"; }
-
I'm not sure I follow you completely. Before I try to answer your question I'd like to point out that the first block of code you posted is running the query twice! And, if you only need one column from the query use that in the SELECT statement instead of '*': $query = "SELECT permissions FROM users WHERE `username`='$username_from_cookie'"; $result = mysql_query($query) or die("Couldn't execute query"); if(mysql_num_rows($numresults)) { $permissions = mysql_result($result, 0); echo "Permission level: $permissions"; } else { echo "No records returned."; } Now, as to your problem. It seems you have some functions that should be enabled based upon several permission levels. I would suggest you redo your permission levels and functions in one of two ways. 1. Design the permission levels such that someone with permission level 2 has all the functions for permission level 2 and permission level 1. Likewise, someone with permission level 5 has all functions for permissions 5-1. So, then your permission checking becomes simple: if($permissions >= 5) { //Show feature that is available for permissions 1-5 } Or, you can utilize a bitwise operator. In this model your permissions are set based upon the "bits" in a binary number (however they are stored an regular 10 base numbers). In the binary number 00101 there are two bits in the ON/True positions: the first and the third - they work backwards. In this model each bit is a different permission. Perhaps one for managing users, another for managing products, or whatever. The decimal equivalent of that number would be 5. You could then build a function that passes the user's permission value along with a number that represents what bits are required for a particular feature and have that function return true or false. PHP has many functions for dealing with bitwise operators so you don't have to do the math. But, it is beyond the scope of a forum post to explain them or how this would be built. There are probably tutorials available if you care to search.
-
Well, I have one additional year on you so don't try using your age as an excuse. I have no idea what you mean by A while loop has nothing to do about numbers. A while loop continues as long as the condition is true. So, when getting a result from a database query you simply need to create a condition to get the next record in the result set (typically using one of the mysql_fetch_ functions). Then the loop will get a new record on each iteration of the while() loop and will exit the loop once there are no more records to retrieve. So, you just need to move the $info = mysql_fetch_array( $data ); to be your condition for the while loop. Also, don't use mysql_real_escape_string() for variables that are supposed to be numeric. It won't prevent errors from non-numeric input. $id = intval($_GET['id']); $query = "SELECT location FROM cities WHERE id = '$id'"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { echo "{$info['location']}<br>\n"; }
-
yeah, but his original post showed that there were more fields in the record than he was saving to the database. That code would try and add all the field to the values. Plus, adding a comma at the end of each value record and having to remove the last one is kinda hokey in my opinion. The code I provide could be much more compact without creating the temp variables. But, that can be helpful to keep the values strait when you review the code and if you need to do validations on them. Otherwise it could simply have been: $insertValues = array(); //Temp array to store values foreach($array as $id => $record) { $insertValues[] = "('{$record[0]}', '{$record[1]}', '{$record[2]}', '{$record[3]}', '{$record[4]}')"; } //Create/run insert query $query = "INSERT INTO table_name (`name`, `age`, `address`, `weight`, `height`) VALUES " . implode(', ', $insertValues); $result = mysql_query($query); Much simpler.
-
You should "save up" all the data and do one INSERT into the database. Where is the array of data coming from: a form POST, a file import or what? It appears that each 'record' in the array contains more data than you actually want to save to the database. Ideally, each element in the sub-array would have named keys (e.g. 'name', 'age, etc.) If not, you would need a process to translate what field is what Here is a general solution: $insertValues = array(); //Temp array to store values foreach($array as $id => $record) { $name = $record[0]; $age = $record[1]; $addr = $record[2]; $weight = $record[3]; $height = $record[4]; $insertValues[] = "('{$name}', '{$age}', '{$addr}', '{$weight}', '{$height}')"; } //Create/run insert quer $query = "INSERT INTO table_name (`name`, `age`, `address`, `weight`, `height`) VALUES " . implode(', ', $insertValues); $result = mysql_query($query);
-
Well, there's no reason you can't implement something to work with what you currently have. On all of your web accessible pages, load a single file to define variable for the absolute paths to the folders that you need to access. You would have to provide the relative path to that one file. Then all of your pages can simply include the appropriate variables. So, in your 'contact.php' page, you would have something like this at the top of the page: include('../../folder_paths.php); That file would define the variables for the absolute paths to the content folders you need. Then, later in the 'contact.php' page you could include the appropriate content file using something like include("{$includes_folder}/contact_content.php");
-
You have some other problems in your code. 1. I'd advise against using a false check for the $mail/$password variables. If a user created the password such as '000000' it would resolve to false. Instead use empty(). 2. Why are you using htmlentities() on the password? You should never be displaying it. Also, I would not use htmlentities() on the stored username. It can create problems with validations and you have to make your DB field larger than what you set as a max length for the username. Personally, I store data as the user entered it and then make any transformations based upon the respective output. Also, you don't need to trim() the password as a user may want to actually use spaces before/after other content. It won't fail your script, but it makes their password less secure since a password entered as "___password___" would become just "password" 3. You should only be displaying database errors in a development environment - never in a production environment. Just implement some logic to display different errors based upon the environment. 4. Try to avoid using '*' in your select queries. It creates unnecessary overhead (i.e. performance). Just select the fields you are going to use. 5. I would also not use a separate check for the username and one for password. That gives a malicious user too much information. Simply check both the username and password for a match. If neither matches tell the user that theri information could not be authenticated. As an example, let's say someone wanted to crack into bob@domain.com's accounts on any sites he uses. If the user types that username into your page above, the user would know that bob does have an account on your page. He then only needs to try and hack the password. If you simply stated that there was no match on the username/password combination the malicious user wouldn't even know if bob has an account on your site or if he used a different email address. 6. You have a while() loop to check the DB results. If these are user account's wouldn't you only have one matching record? 7. Lastly, use indentations to give your code a logical structure to make it easier to "see" the logic flow. Here is a revision of your code above to use as you see fit if (isset($_POST['login'])) { //Pre-process post data $email = isset($_POST['email']) ? trim($_POST['email']) : ''; $password = isset($_POST['password']) ? $_POST['password'] : ''; if (empty($email) || empty($password)) { echo"<div class='msgerror'>Please enter both Username and Password</div>"; } else { $query = sprintf("SELECT myemail FROM users WHERE myemail='%s' AND mypassword='%s' LIMIT 1", mysql_real_escape_string($email), md5($password)); $result = mysql_query($query) or die('Query failed: ' . mysql_error() . "<br />Query: $query\n"); if (!mysql_num_rows($myselect)) { echo"<div class='msgerror'>Wrong username/password. Please try again.</div>"; } else { $_SESSION['email']=$myemail; //header('Location: ../admin/admin.php'); } } }
-
The general structure you are alluding to is a very good practice. Any file 'above' the web root cannot be accessed directly from a browser. If you have files that are only meant to be included by other files and you put those in a web-accessible location then you have to take more time when developing those include files to ensure that if someone did access the file directly that no sensitive information would be compromised - such as if if the generated an error that leaked DB connection info. I've built sites where the web-accessible files only have a few lines of code to set some variables, to set the action the user wants to perform, and then call the 'logic' files that are not web-accessible. However, as you've found, having to set the paths to the files can be cumbersome. I ran across an article a couple years back (can't find it at the moment) that showed an easy solution. I'll try to summarize it here: 1. Have a default page for your site (e.g. index.php) that sits in the web root of the site. Instead of using it for the home page you will use it to set the root path to the files that do the actual work. Then load the default 'logic' file. Here is the complete index.php file at the web root of one of my projects: error_reporting(E_ALL | E_STRICT); // Set include path to logic files $ROOT_PATH = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR; include ("{$ROOT_PATH}main.php"); exit(); The code for setting $ROOT_PATH will set the directory one level up from the web root. Then in the main.php file you can define additional path locations as needed. Examples: $_PATHS['includes'] = $_PATHS['root'] . 'includes' . $_DS_; $_PATHS['modules'] = $_PATHS['root'] . 'modules' . $_DS_; $_PATHS['classes'] = $_PATHS['root'] . 'classes' . $_DS_; $_PATHS['templates'] = $_PATHS['root'] . 'templates' . $_DS_; You can now use those variables throughout your pages as needed. Now, you may be asking yourself how does main.php 'know' what pages to load if it is called on every page load. Here is the process I followed. Let's say I have a web-accessible page to display a list of products (e.g. mysite.com/show_products.php). In that page I would only need the following code: $action = "show_products"; include("../index.php"); So, when a user types the URL into their browser for that web page, the action variable is set. The page then loads index.php (which set the root path to the logic files outside the web root) which then loads the core logic file (main.php). In the main.php file I would create a switch() to determine what content pages to load based upon the actino: if(!isset($action)) { $action = "home"; } switch($module) { case 'show_products': $actionFile = 'products/show.php'; break; case 'home': default: $module = "home"; $actionFile = 'home/home.php'; break; } That is just a very simplistic example, however. For many pages there may be several sub-actions. For example, the show_products.php fiel may be used for pagination or searching of products. If the data to make that determination will be global (e.g. POST/GET) then I can access those after the logic file for show_products is loaded. However, I may have several web-accessible pages that load the same core logic file. Let's say I have one core logic file to manager products (manage_products.php). That file is loaded when I add, edit or delete products for which I have three different web-accessible page. Then in those pages I can have an $action and a $sub_action that I set. Then the manage_products.php page is loaded from main.php based upon the $action variable. And in the manage_products.php page I would have another switch() to determine the sub-module to load using $sub_action. All of this is just one approach. I'll see if I can find the article and post a link here.
-
How to not display picture icon if no picture in mysql database
Psycho replied to frank_solo's topic in PHP Coding Help
isset() will not work, because the field will be set for every record returned from the database. The value may be null or an empty string - but it will be set! The question is, do you want to show NO image or do you want to show a default image? Either way, the logic will be the same, but the implementation slightly different. To display NO image do this while($row = mysql_fetch_array($result)) { $image = (!empty($row['imageurl1'])) ? "<img src=\"user/{$row['imageurl1']}\" width='50'>" : ''; echo "<tr> <td bgcolor='#FFFFFF' style='color: #000' align='center'> <a href='classified/places/index.php?id={$row['id']}'>{$row['title']}</a></td> <td bgcolor='#FFFFFF' style='color: #000' align='center'>$row['county']}</td> <td bgcolor='#FFFFFF' style='color: #000' align='center'>{$row['town']}</td> <td bgcolor='#FFFFFF' style='color: #000' align='center'>{$row['phone']}</td> <td bgcolor='#FFFFFF' style='color: #000' align='center'>{$row['rooms']}</td> <td bgcolor='#FFFFFF' style='color: #000' align='center'>{$row['bath']}</td> <td bgcolor='#FFFFFF' style='color: #000' align='center'>{$row['feeornofee']}</td> <td bgcolor='#FFFFFF' style='color: #000' align='center'>{$row['rent']}</td> <td bgcolor='#FFFFFF' style='color: #000' align='center'>{$image}</td> </tr>"; } For a default image do this (replace with the appropriate value while($row = mysql_fetch_array($result)) { $imageSrc = (!empty($row['imageurl1'])) ? $row['imageurl1'] : 'default.jpg'; echo "<tr> <td bgcolor='#FFFFFF' style='color: #000' align='center'> <a href='classified/places/index.php?id={$row['id']}'>{$row['title']}</a></td> <td bgcolor='#FFFFFF' style='color: #000' align='center'>$row['county']}</td> <td bgcolor='#FFFFFF' style='color: #000' align='center'>{$row['town']}</td> <td bgcolor='#FFFFFF' style='color: #000' align='center'>{$row['phone']}</td> <td bgcolor='#FFFFFF' style='color: #000' align='center'>{$row['rooms']}</td> <td bgcolor='#FFFFFF' style='color: #000' align='center'>{$row['bath']}</td> <td bgcolor='#FFFFFF' style='color: #000' align='center'>{$row['feeornofee']}</td> <td bgcolor='#FFFFFF' style='color: #000' align='center'>{$row['rent']}</td> <td bgcolor='#FFFFFF' style='color: #000' align='center'><img src=\"user/{$imageSrc}\" width='50'></td> </tr>"; } Also, if you want a default image, you could also change your query to return the default image when the field is empty and not have to change the output code at all. But, since you are using '*' in your query I'm not going to bother going to the trouble of editing it like it should be. As a general rule you should not use '*' for your SELECT parameters. Instead indicate the fields that you want. SELECTing more fields than you need is a waste of resources. -
What do you mean exactly by it is "redirecting" you. Are you saying that is it initially loading the development admin site and then there's a page refresh that then loads the live admin page? Or, do you see that the dev URL is initially displayed int he URL address bar and then changes to the live URL when the page is loaded? How are you trying to access the admin site? Are you entering the URL directly or are you clicking a link in the app? If you are clicking a link check that the link is pointing to the correct URL. It could be that the URL is static or there is a problem in how it is dynamically generated.
-
Um, no. mysql_real_escape_string() will add slashes to certain characters to prevent them from being interpreted as non-data characters. but, the actual content that is stored in the database is the content as it existed before mysql_real_escape_string().
-
Use mysql_real_escape_string() which you should ALWAYS use on any user submitted values that you are going to run in queries. Also, do not do a single INSERT query for each record. That will cause a performance issue. Instead, combine all the INSERTs into one query. Lastly, no need to have a value that you increment on each iteration of the loop just to skip the first line. That's not efficient. I've made some other changes in the interest of cleaner/more efficient code if(isset($_POST['submit'])) { if(strtolower(strrchr($_FILES['sel_file']['name'], '.')) != ".csv") { echo "Invalid File"; } else { $filename = $_FILES['sel_file']['tmp_name']; //Process the data file $firstLine = true; $valuesAry = array(); //Temp array to hold insert records $handle = fopen($filename, "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { if($firstLine) { $firstLine = false; continue; } //Prepare values $id = intval($data[0]); $name = mysql_real_escape_string(trim($data[1])); $desc = mysql_real_escape_string(trim($data[9])); $cat = intval($data[14]); $subcat = intval($data[15]); $tax = floatval($data[19]); $price = floatval($data[35]); $active = intval($data[65]); //Add INSERT record to temp array $valuesAry[] = "('$id', '$name', '$desc', '$cat', '$subcat', '$tax', '$price', '$active')"; } fclose($handle); mysql_query("TRUNCATE TABLE products"); //Create ONE INSERT query for all records $sql = "INSERT into products (prod_id, prod_name, prod_description, prod_cat, prod_sub_cat, tax, prod_price, active) VALUES " . implode(', ', $valuesAry); mysql_query($sql) or die(mysql_error()); echo "Successfully Imported<br>"; } }
-
As wolfcry alluded to you can put the file into a directory that is not web accessible - i.e. it cannot be accessed via an http request. But,when you say it can only be accessed via the web app I think you mean something different than we thought. To most developers that would mean that the file would be include()d from the web app. But, you state that the web app is an HTML file, not a PHP file. I think what you mean is that you want users to always go to the main page before accessing the script in question. The only way I can think to do that would require changing the main page "webapp.html" to a PHP page. Then, on that page, create a timestamp value and use that value to set a session value and append to the URL to the secured script. In this example, I'll hash the timestamp //Start session session_start(); //Create timestamp value and set in session $timestamp = time(); $_SESSION['myscript'] = $timestamp; //Create the link to 'myscript' with an additional parameter for the timestamp echo "<a href='http://mysite.com/php/myscript.php?action=1&code={$timestamp}'>Secured Script</a>"; Lastly, you would need to modify the myscript.php page to check the value passed in the query sting to see if it matches the value in the session var. If they match, show the page. Else, don't show the page. you can show an error message or redirect the user back to the main page. session_start(); if(!isset($_SESSION['mypage']) || $_SESSION['mypage'] != $_GET['code']) { die('Access denied'); } //Rest of script follows
-
The problem you are facing is probably due to the fact that they email is being sent as plain text. You have two options that come to mind: 1. Just add the url in the output (i.e. not an anchor tag). The email readers (Outlook, gmail, etc.) *may* actually convert the URLs to clickable links on their own. This would be very easy to test. 2. To make your own clickable hyperlinks using an anchor tag you will want to send the emails as HTML emails. There are a lot of things you need to do when doing this. I suggest either looking up some tutorials or find a good class to handle this.
-
As Muddy_Funster stated you should create the form fields as arrays with the IDs as the indexes for the array. However, what you are doing for the id parameter of the fields is fine since you don't access those on the PHP receiving page. Also, no need to assign the database fields to a temporary variable if you are not going to use it later - just use the array value in the output. Example format: While($myrow = $result ->fetch_assoc()){ $emp_name = $myrow['name']; $display .= <<<EOF_ <input type="hidden" name="monday[{$myrow['id']}]" id=" monday_$emp_id" value="$monday" /> <input type="hidden" name="tuesday[{$myrow['id']}] " id="tuesday_$emp_id" value="$tuesday " /> EOF_; } Now you can access all the "monday" values using a foreach loop such as foreach($_POST['monday'] as $empID => $mondayValue) { // }
-
I really think you are biting off more than you can chew at the moment. If you don't even know where to start then I assume that you don't have the skills/experience to tackle this right now. But, I will be happy to provide some "general" ideas. First off you should determine the workflow before you start writing the code. Yes, you would start with the user entering in their request first. But, then how are the taxi companies going to "know" there is a quote waiting? Are you going to send them an email, do you expect them to constantly monitor a web page, or what? You could create an AJAX enabled page that will auto-update ever n minutes but it still requires someone to be there monitoring it. For someone needing a taxi it seems that the time to wait for the taxi companies to see that there is a request and respond - and then for the user to see that there are responses - would be too much trouble. If it were me I'd just call a taxi company and request a cab. The couple of dollars I could save by shopping around wouldn't be worth my trouble (but maybe that's just me). Anyway, once you've worked out the process for the workflow you could then design the database structure. If you have no experience in this area I highly suggest you do some research. Building the wrong DB structure will limit what you can do and can have sever performance consequences. Once you have both the workflow and the database design you cant then start developing. Here is a rough draft of a potential workflow. 1. User signs-up on the site. You can make this optional, but this all depends on what you want the user to be able to do after they submit their request. If the user needs to get back to the site to review the quotes, having them associated with a user account is the preferred approach. If you make it anonymous, then you would want to get an email during the quote request process to send the user an email. That email can contain a link with the quote request ID for the user to access the quote. 2. Once the user submits their quote request you would store the appropriate record(s) for the quote and notify the taxi companies. Again, you need to determine how you will accomplish this: email, web-page, etc. You could do both. 3. Allow the taxi companies to submit their estimates. These would go into a separate table with a foreign key reference back to the quote request. 4. Notify the user that there are estimates submitted. I would suspect you would want to alert the user as soon as each estimate is submitted. From the user's standpoint I would hate to get 5 different emails, but you can't wait until all the taxi companies respond because there will be times when one or more do not. You also have decide how you will alert the user: email, text, web page, etc. Again, you can go with more than one, but you don't want to create a lot of "noise" for the user (IMHO). 5. Then, what happens when the user reviews the estimates. When the user selects one of the estimates you would again update the database. In this case you could probably update the main quote request to include a foreign key reference back to the estimate that was accepted. You then, again, need to alert the taxi company that their estimate was accepted. You may also want to alert the other companies that their estimates were rejected. 6. Lastly, you would want to send a confirmation back to the user. This may include a confirmation number or other info that the taxi company added when they confirmed the request. This is just a very high-level analysis. You need to do your homework to identify what specific information is needed by both the users and the taxi companies and be sure you account for that in this process.
-
It would be helpful for you to show your current code for us to implement something into it. But, generically speaking you would just check the first letter of each title as you process the records. If the letter is different from the last letter then display a new letter header. Although, one thing you would need to decide is if you want to show the header if there are no titles for that letter. If so, that makes the process a little more difficult, but not terribly so. EDIT: Rough example $query = "SELECT title FROM movies ORDER BY title"; $result = mysql_query($query); $current_letter = ''; while($row = mysql_fetch_assoc($result)) { $this_letter = strtoupper(substr($row['title'])); if($current_letter != $this_letter) { $current_letter = $this_letter; echo "<h1>{$current_letter}</h1>\n"; } echo "{$title}<br>\n"; }
-
You only need to do it one. If you do it multiple times you will introduce extraneous characters into the stored results. In your sampel code above there are some inefficiencies. No need to set the POST value to a variable. Then set the variable to itself with the mysql_real_escape_string(). Plus, you should almost always trim() user submitted data - else a 'space' would be interpreted as a valid value. Also, try to avoid 'flag' variables using text such as yes/no or OK/NOTOK. Use the Boolean true/false values. if(isset($submit)) { $email = mysql_real_escape_string(trim($_POST['email'])); $response = mysql_real_escape_string(trim($_POST['response'])); $id_number = mysql_real_escape_string(trim($_POST['id_number'])); $valid = true; $msg = ''; if(empty($response)) { $msg .= "You did not enter any data<br />"; $valid = false; } if($valid) { $query = "SELECT response, userName, email FROM myuser WHERE response = '{$response }'"; $result = mysql_query($query);
-
OK, then you don't need to do a query beforehand. Simple add a WHERE cause to the DELETE query so only his records will be deleted. Then you can provide a message if some of them were not deleted because he was not the owner of the messages. if (isset($_POST["submit2"]) && $_POST["submit2"] == "DELETE SELECTED") { //Force POST values to be INTs $deleteIDs_ary = array_map('intval', $_POST['chkColor']); //Remove any 'false' value $deleteIDs_ary = array_filter($delete_ids); //Check that there was at least one valid value if(count($deleteIDs_ary)) { //Create comma separated string of the IDs $deleteIDs_str = implode(',', $deleteIDs_ary); $name = mysql_real_escape_string($_SESSION['name']); //Create and run one query to perform all the deletes (of the user) $query = "DELETE FROM crew_messages WHERE id IN ($deleteIDs_str) AND to_name = '$name'"; if(mysql_query($query)) { $selectedCount = count($deleteIDs_ary); $deletedCount = mysql_affected_rows(); echo "{$deletedCount} of {$selectedCount} record(s) were successfully deleted."; if($deletedCount != $selectedCount) { echo " You do not have rights to the others."; } } else { echo "There was a problem running the query.<br>" . mysql_error(); } } else { echo "Invalid ID data passed."; } }
-
Again, no need to create a bunch of OR conditions (which I assume you are doing because it looks like you are using the code scootstah posted. Also, stop using '*' in your SELECTs if you don't need all the fields. It just wastes server resources. Anyway, there is a slight problem with what you want to do here. What if some of the messages belong to the user and some do not? Do, you want to allow the ones that do to be deleted or do you want to prevent the delete operation entirely? Both have a fairly simple soluttion - but would be implemented differently.
-
Well, for starters, I would suggest not using '*' in your select statement. Just include the fields you need. In this case it looks like you want the email and cost fields. Secondly, why are you using "ORDER BY user" if you are not using that for any purpose? Seems like you would have wanted to ORDER BY email. Anyway, if you do not need the granular data (i.e. each email and cost record) then you don't need to add up the values in the array. Instead, change your query to get the summed values for you: SELECT email, SUM(cost) as total_cost FROM cashdepo WHERE cause='$causename' AND status='2' GROUP BY email