
Psycho
Moderators-
Posts
12,160 -
Joined
-
Last visited
-
Days Won
130
Everything posted by Psycho
-
@Barand, I don't think his question was clearly written. I think the key issue is this I think what he wants is that after the user selects a record to edit that the form is displayed with all the current values entered/selected. I had started to edit his code, but it was kind of a mess and I just didn't have time to invest in fixing it and explaining it.
-
Correct, I didn't consider race conditions in my response. But, you can put a write lock the table, do the SELECT, do the INSERT if no duplicate exists, then unlock the table. But, that seems like overkill when the real fix is probably to normalize the db schema.
-
Old Mysql? Syntax issue - Need advise Error "Unknown column in on clause"
Psycho replied to Looktrne's topic in MySQL Help
Tips: 1. Don't create your queries as a single line of text. Add some line breaks and spacing to make it readable. It will save you many, many hours in debugging. 2. No need to create aliases for all of your fields if you want them returned with the same name as the field? Just include the field in your select list and the server will return it using the field name (assuming you are using a fetch_assoc() function). 3. I see you have fields for filename_1, filename_2, etc. You should probably have those in a separate table with a foreign key back to the parent record. Using separate fields like that makes it difficult to change the number you allow and to do any type of queries based upon those values. Don't know if it would fix your issue, but I revised your query to use JOINs for all the tables instead of doing it through the WHERE clause. $query = "SELECT profile.id as profile_id, photos.filename_1, photos.filename_2, photos.filename_3, photos.filename_4, photos.filename_5 FROM dt_billing_history as billing_history JOIN dt_members as member ON member.id = billing_history.member_id JOIN dt_photos as photos ON photos.member_id = member.id JOIN dt_profile as profile ON profile.id = member.id LEFT JOIN dt_privacy as privacy ON privacy.member_id = member.id WHERE billing_history.gender = 'Female' AND (privacy.spotlight_yn <> 'Y' OR privacy.spotlight_yn IS NULL) AND profile.status = 1 ORDER BY billing_history.id DESC LIMIT 4"; That's so much easier to read and greatly improves the ability to debug. -
I forgot one point. If you will consider the same value in different columns to be a duplicate, then the solution will require you to perform a SELECT query first to detect if the value exists in either column before performing the INSERT. If that really is the case, then it would be interesting to know what these values are and why you have two columns to store the same type of data. This might be better solved by changing the database schema to be normalized.
-
Using drop down to delete from Database (mysql)
Psycho replied to ramforinkas's topic in PHP Coding Help
FYI: There are plenty of problems with your script that I didn't take time to address - especially since you didn't provide enough of the code. For example, you first query the list of values to create the options THEN you check if you should delete a record. You should perform the delete first. -
I was somewhat confused by your post as well. If, as Jacques proposed, the "1" would be considered a duplicate even though it appears in different columns, then INSERT IGNORE will not help with what you are trying to achieve. INSERT IGNORE is used to suppress errors that occur during an insert statement. While it will ignore any errors it can (and is) used for a specific purpose to prevent duplicate records. By adding UNIQUE constraints to your database tables it will automatically enforce the restriction of duplicate records. If you try to run a query that would cause a duplicate, it would generate an error. So, one process that is used is to add those unique constraints and then use INSERT IGNORE when doing the inserts. That way any records that would cause an error because of the unique constraint are ignored. But, you need to be very sure that is what you want - for two reasons. First: the IGNORE will ignore all errors that may occur for that query. You should be very sure that the code to produce your query is not subject to possible errors. For example, you should validate all values for the INSERT programatically before you try to even create the query. Otherwise, you may spend hours trying to debug problems because you are not getting any errors. Second, depending on your situation, the new record may have other additional information that you want updated. In this case, you may want to use INSERT REPLACE or ON DUPLICATE KEY UPDATE Going back to your original statement. If you want to prevent the same value in a single filed/column you can make that field unique in your database. You can also make combinations of fields unique. For example, in the example table above, you could make the combination of field a and field b unique. So, the values of (1, 2) and (3, 1) would be allowed. But, you could not add another record with the same values in the same field. So, you could not add another (1, 2) or (3, 1). But you could add the same values in different fields: (2, 1) and (1, 3) would be allowed.
-
Using drop down to delete from Database (mysql)
Psycho replied to ramforinkas's topic in PHP Coding Help
Look at the WHERE clause in the delete query. WHERE FullName='$FullName' Now, look at where $FullName is defined! while($row=mysql_fetch_array($result2)) { if (isset($_POST)) { $FullName=$row["FullName"]; $options2.= '<option value="'.$row['FullName'].'">'.$row['FullName'].'</option>'; } Try if (isset($_POST['NAME_OF_SELECT_FIELD'])) { $FullName = mysql_real_escape_string($_POST['NAME_OF_SELECT_FIELD']); mysql_query("DELETE FROM useraccess WHERE FullName='$FullName'") or die(mysql_error()); echo "Success!"; } else { echo "No value selected"; } -
<?php function displayData($fp) { $ratings = array(); while(!feof($fp)) { // as long as it is not the end of the file. //read one line at a time $line = fgets($fp, 256); //Split the data using explode() function if($line !="") { $info = explode(",", $line); $player_name = $info[0]; $c_value = ($info[2]*100/$info[3] - 30)/20; $y_value = ($info[4]/$info[3] - 3)/4; $t_value = $info[5]*20/$info[3]; $i_value = 2.375 - $info[6]*35/$info[3]; $pass_rating = ($c_value + $y_value + $t_value + $i_value)*100/6; $ratings[$player_name] = round($pass_rating, 2); } } arsort($ratings); echo "<h2>NFL Player Pass Ratings</h2><br/>\n"; echo"<table>\n"; echo "<tr><th>Name</th><th>Pass Rating</th></tr>\n"; foreach ($ratings as $player_name => $pass_rating) { echo "<tr><td>{$player_name}</td><td>{$pass_rating}</td></tr>\n"; } echo"</table>\n"; echo "<h2>NFL Player Pass Ratings: Great, Good, Mediocre</h2><br/>\n"; echo"<table>\n"; echo "<tr><th>Name</th><th>Pass Rating</th></tr>\n"; foreach ($ratings as $player_name => $pass_rating) { //Determine rating label if($pass_rating > 95) { $rating_label = "Great"; } elseif ($pass_rating > 90) { $rating_label = "Good"; } elseif($pass_rating > 85) { $rating_label = "Mediocre"; } else { $rating_label = "Terrible"; } echo "<tr>\n"; echo "<td>{$player_name}</td>\n"; echo "<td>{$pass_rating}<b> -- {$rating_label}</b></td>\n"; echo "</tr>\n"; } echo"</table>\n"; } ?>
-
First off, that is not how you manage session timeout. You should not need to include any code to manage the session timeout period - it is configured on the server. So, you would only need to check if the session value you set at login still exists. If yes, they are still within the session timeout period. If not, the session has expired and you can redirect to the login page. Looking at the two 'pages' I can't see anything that jumps out at me, but there are plenty of reasons why you may be getting those results that would be due to code outside of what you have posted (e.g. is the same style sheet being used). I say, make your life easier and instead of trying to put the code for the login message on all the pages, simply put a redirect to the page. Then you know that it will always display the same. In fact, I would simply redirect them to the login page and, optionally, display the error that the timed out. if(!isset($_SESSION['lnusers'])) { header("Location: http://mysite.com/login.php?error); exit(); } Then on the login page you already have you could have an error displayed if they were redirected there due to the session not existing if(isset($_GET['error'])) { echo "<h2>Sorry, you have not logged into the system</h2>\n"; }
-
The problem I was having was for Car records for which there were no current, corresponding Book records. I found my problem, which was I was doing a GROUP BY on the car_id column from the Books table. But, I think it is still odd. If a card does has no current Booking records, the value of car_id in the LEFT JOIN would be NULL. Likewise, if a car has existing booking records, but none match the JOIN conditions, the value of car_id would likewise be NULL> But, for some reason, when using GROUP BY car_id, a car matching that first scenario would be in the results, whereas one in the second does not.
-
@Barand, I tried the same thing - but it doesn't work. For some reason, when adding the additional parameters to the ON condition for the dates it is excluding those records from the "Car" table that do not meet those conditions from the results (where the car_id would be NULL) - even though it is using a LEFT JOIN. Not sure why. When just using the books ON books.car_id = car.id condition it includes all the car records and has a NULL value for car_id. Not sure if it is a bug in the version of MySQL I am using or what. @lasha One thing that some of us do not like is whenwe answer a question and then get a response along the lines of "that's great but what I really need is this". Many times, the thing the user needs requires a completely different solution and we've just wasted out time. In this case, you can use the query I provided and add the other excluding conditions to the WHERE condition. I think this will get you what you want. $query = "SELECT car.id, car.model, car.engine, car.passenger, car.liters, car.transmission, car.doors, car.engine_type, car.luggage, car.condintioner, car.stereo, car.gps, car.propulsion, car.price1, car.price2, car.price3, car.price4, car.img, car.thumb, car.owner, car.location FROM car WHERE car.id NOT IN ( SELECT car_id FROM Books WHERE books.start_date < '{$requestEnd}' AND books.end_date > '{$requestStart}' ) AND car.cat_id = $cat_id AND car.location = 'london' AND car.state = 'published'"
-
There's another problem with your logic aside from the multiple bookings issue. namely this: OR books.start_date NOT BETWEEN '" . $_POST['start'] . "' AND '" . $_POST['end'] . "' AND books.end_date NOT BETWEEN '" . $_POST['start'] . "' AND '" . $_POST['end'] . "' Let's say the car was booked from Jan 1 to Jan 31. If your POST dates were Jan 10 to Jan 20 then it would appear as if the car was available because neither the book start date nor the book end date are within the POST dates. Plus, when using OR along with other conditions, it is best to enclose conditions in parens both to ensure it is interpreted correctly and to ensure readability. So, based on your post, I believe you simply want a list of cars that are available within the given time period. If so, you do not need the booking information in the SELECT part of the clause since you don't want cars that are booked in the given date range anyway. A better way to approach this is to use a query to find where the cars are booked for the selected time period and use that as an exclusion. it may seem illogical, but the way to find those current booking that conflict with the request is where the booked start date is less than the request end date AND the booked end date is greater than the request start date $requestStart = date('Y-m-d', strtotime($_POST['start'])); $requestEnd = date('Y-m-d', strtotime($_POST['end'])); $query = "SELECT car.id, car.model FROM car WHERE car.id NOT IN ( SELECT car_id FROM Books WHERE books.start_date < '{$requestEnd}' AND books.end_date > '{$requestStart}' )"; EDIT: Also, Never use POST data directly in your query. The code above has some logic to prevent malicious input to cause SQL injections.
-
I think this thread has come off the rails a bit. Let me clarify a few things. Determining if a user is an 'admin' or not and storing that information in the session is perfectly acceptable. The whole point of session data is to store information that you will use throughout the session. The only potential problem with this is if you will need to immediately know if their admin status has changed during the session. That is a business decision. If the answer is absolutely yes, then you would have to do an admin check on each login. If the answer is 'sometimes' based on what the user is doing, thenyou could add a DB check for the specific functions where you need to reverify their admin status. Otherwise, you can use the data in the session to check their admin status. The discussion about using SSL is irrelevant to the discussion about using session data or not. If you are not using SSL, then ALL traffic between the client and host is in clear text - this includes the user's credentials when logging in. If the communication between the client and server is compromised, it wouldn't matter if you store the admin status in the session or not. Yes, a malicious user could potentially capture the session ID and then hijack the session. But, they could just as easily get the login credentials which is much more significant. So, I still stand by my earlier statements that determining if the user is an "admin" at login and then storing a value in the session to reference makes the most sense (assuming you don't have a business need pursuant to the requirements noted above). For the vast majority of general purpose sites, this is acceptable. As an additional comment to using SSL, my opinion is that if you are not storing sensitive information or are not a high-visibility site, it is probably not necessary. There will always be people at both extremes and I would typically err on the side of security. But, the reality is that it is not a significant of a problem (at present). Plus, if your site warrants SSL, then there are a whole lot of other things you need to be doing to secure your site other than SSL. Most website attacks are not done through the data transport. Also, SSL doesn't come without a cost both financially and with performance. So, as to using SSL, think about what would happen if your site was compromised. I.e. all the data exposed to a malicious user. Is there any confidential/financial data that would be obtained? If yes, use SSL, it probably isn't necessary. You should, of course, have regular backups in case you need to restore your site from any loss of data - whether it is malicious or not (e.g. failed hard drive). The chances of someone trying to use an unencrypted transmission (i.e. HTTP vs. HTTPS) to try and gain access as an admin is extremely unlikely. There are many much easier methods (e.g. social engineering) to gain such access.
-
What? Why would you do that? That's a waste. If you already pulled that info from the DB and saved it in the session, then pulling it again on each page load is not necessary. Nothing is 100% secure, but for all intents and purposes session data can only be accessed on the server. An SSL connection is used to encrypt data between the client and the server. Since the session data is never passed between the client and the server SSL has no impact on this. The only thing stored in the session cookie is the session ID which is the unique identifier for the user's session. When the user accesses a page, the server uses that cookie to associate them with the appropriate session data. But, the data exists only on the server.
-
I disagree. The whole point of session data is to store data that you will use repetitively throughout the user's session. If you need to know whether the user is an admin when loading many or all pages, then storing that information in the session is perfectly acceptable. However, Jacques1 does bring up a valid point about the fact that session values do persist for the entire session (obviously). So, if a user is logged in as an admin and you change their status to not be an admin, then that user will still be considered to be an admin until their session terminates. But, that is a business decision. That would likely be a very rare occurrence. Is the need to immediately remove the admin access important enough to incur the overhead of doing an additional DB request on each page load? If it s a very security critical site I would say yes. Otherwise, I'd say no. Also, there are other workarounds you could use. For example, you might rely upon the session value for most pages. But, there may be critically sensitive pages that you would want to always check the DB. This is no different than how most sites save your login status. I can browse most sites after I login and it is using a session status as I go from page to page. However, if I go to a page to modify my account information, I may be asked to again provide my credentials as an additional check.
-
echo "<h3>Use following form to change password:</h3>\n"; echo "<script>\n"; echo "function checkForm(formObj)\n"; echo "{\n"; echo " if(!formObj.elements['username'].value.length || !formObj.elements['passwd'].value.length)\n"; echo " {\n"; echo " alert('Please enter values for the \"User name\" and \"Password\" fields');\n"; echo " return false;\n"; echo " }\n"; echo " return true;\n"; echo "}\n"; echo "</script>\n"; echo " <div class='contactform'>\n"; echo "<form action='{$_SERVER[PHP_SELF]}' method='pos' onSubmit='return checkForm(this)' name='changepassword'>\n"; echo "<div class='passwdleft'><label for='lblusername'>User Name: </label></div>\n"; echo "<div class='passwdright'><input type='text' name='username' id='lblusername' size='30' maxlength='50' value='' /> (required)</div>\n"; echo "<div class='passwdleft'><label for='lblpasswd'>Password: </label></div>\n"; echo "<div class='passwdright'><input type='password' name='passwd' id='lblpasswd' size='30' maxlength='50' value='' /> (required)</div>\n"; echo "<div class='passwdright'><input type='submit' name='Submit' value='Change password' id='passwdsubmit' />\n"; echo "<input type='hidden' name='pwdchange' value='process' /></div>\n"; echo "</form>\n"; echo " </div>\n";
-
Just a typo. Change this echo "<form action='{$_SERVER[PHP_SELF]}' method='pos' onSubmit='return checkForm()' name='changepassword'>\n"; to This: echo "<form action='{$_SERVER[PHP_SELF]}' method='post' onSubmit='return checkForm()' name='changepassword'>\n"; Note: the method value should be 'post' not 'pos'
-
I don't think this is really a PHP problem, but more an HTML/CSS problem. Looking at your code above, I see that it is a tournament bracket - but there is no CSS code so I'm probably not seeing the intended output. I'm also not sure where you are wanting to display the winning team in the output. What you should do is build a static page (i.e. no PHP just HTML/CSS) to have the page display how you want it using sample data. Once you have the output you want - THEN you would modify your PHP code to output the variable data into the same format.
-
What makes you think the fields should retain their value when the page reloads? Web pages are stateless. They don't know anything about the previous page unless you code them to do so. When you build the page you need to take the POST value (if sent) to make the appropriate option selected when you build the list <?php //Get selected values $selectedCompany = isset($_POST['company']) ? $_POST['company'] : false; $selectedBranch = isset($_POST['branch']) ? $_POST['branch'] : false; //Connect to DB include "db_conexn.php"; //Create company options $query = "SELECT distinct(comp_name) from company"; $result = mysql_query($query); $companyOptions = "<option value=''>---Select Company Name---</option>"; while($row = mysql_fetch_assoc($result)) { $selected = ($row['comp_name']==$selectedCompany) ? ' selected="selected"' : '' ; $companyOptions .= "<option value='{$row['comp_name']}'{$selected}>{$row['comp_name']}</option>\n"; } //Create branch options $company = mysql_real_escape_string($selectedCompany); $query = "SELECT distinct(branch) from branch where comp_name='$company'"; $result = mysql_query($query); $branchyOptions = "<option value=''>---Select Company Name---</option>"; if(!mysql_num_rows($result)) { $branchyOptions .= "<option value=''>No Data</option>"; } while($row = mysql_fetch_assoc($result)) { $selected = ($row['branch']==$selectedBranch) ? ' selected="selected"' : '' ; $branchyOptions .= "<option value='{$row['branch']}'{$selected}>{$row['branch']}</option>\n"; } ?> <body> <?php ?> <form method="post" name="admin"> <select name="company" onChange="this.form.submit();"> <?php echo $companyOptions; ?> </select> <select name="branch"> //2nd Drop Down Menu Starts here <?php echo $branchyOptions; ?> </select> </form> </body>
-
Based upon how you asked the question, I'm not sure you understand what OOP really is or how it would be used. Yes, you could rewrite the pages to use OOP. But, why would you want to do that? Does the site work as it should? If so, leave it the hell alone. If you want to learn how to program in OOP you might find a tutorial here: http://lmgtfy.com/?q=PHP+OOP+tutorial
-
//Use whatever method you want for salting $combined_password = $password . $salt; $hash = hash('sha512' ,$combined_password)
-
How do you "know" the line with that query is even being run? There's no output associated with that line of code. So, what makes you think it should have executed? You state that the query isn't doing anything as if the query is not running on the MySQL side. I'm guessing it is not being executed within PHP. Instead of putting your query inside the actual query call, create the queries as string variables - makes it much easier to debug. Anyway, modify line 431 to look like this $query = "UPDATE users SET cash='".clean_string($info["cash"]-$_POST["bet"])."' WHERE login='".$info["login"]."'"; mysql_query($query) or die(mysql_error()); echo "Debug: The following query was executed:<br>{$query}"; If you do not see that debug statement, then it means the logic in the code (if/else and other branching logic) is such that it will not be executed. If it does display, then we you should run a similar SELECT query (before and after the UPDATE) to see what records match that criteria and see what the 'cash' value is before and after.
-
Here is a rewrite of your script that resolves many of the problems in the logic and security. It *may* also resolve the issue with the dollar signs. The function escapeshellarg() is a PHP function to escape a value for use as a sell argument. If not, you can try adding the quotes to the value before you send it to the Python script I didn't test this, so there may be a few syntax errors to resolve <?php /////////////////////////////////////////////////////////////// // PHP script to change Linux password // SEE following URL mor more info: // http://www.cyberciti.biz/tips/change-linux-or-unix-system-password-using-php-script.html // Written by nixCraft <http://www.cyberciti.biz/> // Distributed under GNU/GPL v2.0+ /////////////////////////////////////////////////////////////// $title = ''; $resultMessage = ''; $displayForm = false; // Make sure form is submitted by user if(!(isset($_POST['pwdchange']))) { // if not display them form $title = "Hash password"; $displayForm = true; } else { // try to change the password // get username and password $username = escapeshellarg(stripslashes(trim($_POST['username']))); $password = escapeshellarg(stripslashes(trim($_POST['passwd']))); // if user skip our javascript ... // make sure we can only change password if we have both username and password if (!empty($username) && !empty($password)) { // Define shell script $shellscript = "python /home/rconfig/www/test1.py"; // command to change password $cmd = "$shellscript {$username} {$password}"; // call command // $cmd - command, $output - output of $cmd, $status - useful to find if command failed or not exec($cmd, $output, $status); if ( $status == 0 ) { // Success - password Hash $title = "Password Hashed"); $resultMessage .= "<h3>Password Hashed</h3>Setup a <a href='{$_SERVER['PHP_SELF']}'>new password</a>\n"; } else { // Password failed $title = "Password hashing failed"; $resultMessage .= "<h3>Password hashing failed</h3>\n" $resultMessage .= "<p>System returned following information:</p>\n"; $resultMessage .= "<pre>" . print_r($output, 1) . "</pre>\n"; $resultMessage .= "<p><em> Please try again, if the the propblem still exist contact the concerned team for more info"; $resultMessage .= "<a href='{$_SERVER['PHP_SELF']}'>again</a></em></p>\n"; } } else { $title = "Something was wrong -- Please try again"; $resultMessage .= "Error - Please enter username and password\n"; $displayForm = true; } } // display html form function writeForm($display) { if(!$display) { return; } echo "<h3>Use following form to change password:</h3>\n"; echo "<script>\n"; echo "function checkForm() {\n"; echo " if (document.forms.changepassword.elements[\'username\'].value.length == 0) {\n"; echo " alert(\'Please enter a value for the \"User name\" field\');\n"; echo " return false;\n"; echo " }\n"; echo " if (document.forms.changepassword.elements[\'passwd\'].value.length == 0) {\n"; echo " alert(\'Please enter a value for the \"Password\" field\');\n"; echo " return false;\n"; echo " }\n"; echo " return true;\n"; echo "}\n"; echo "</script>\n"; echo " <div class=\"contactform\">\n"; echo "<form action='{$_SERVER[PHP_SELF]}' method='pos' onSubmit='return checkForm()' name='changepassword'>\n"; echo "<div class='passwdleft'><label for='lblusername'>User Name: </label></div>\n"; echo "<div class='passwdright'><input type='text' name='username' id='lblusername' size='30' maxlength='50' value=' /> (required)</div>\n"; echo "<div class='passwdleft'><label for='lblpasswd'>Password: </label></div>\n"; echo "<div class='passwdright'><input type='password' name='passwd' id='lblpasswd' size='30' maxlength='50' value='' /> (required)</div>\n"; echo "<div class='passwdright'><input type='submit' name='Submit' value='Change password' id='passwdsubmit' />\n"; echo "<input type='hidden' name='pwdchange' value='process' /></div>\n"; echo "</form>\n"; echo " </div>\n"; } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title><?php echo $title; ?></title> <style type="text/css" media="screen"> .passwdform { position: static; overflow: hidden; } .passwdleft { width: 25%; text-align: right; clear: both; float: left; display: inline; padding: 4px; margin: 5px 0; } .passwdright { width: 70%; text-align: left; float: right; display: inline; padding: 4px; margin: 5px 0; } .passwderror { border: 1px solid #ff0000; } .passwdsubmit { } </style> </head> <body> <?php echo $resultMessage; ?> <?php writeForm($displayForm); ?> </body> </html>
-
And, why would you ask the user to put the quotes? You should do it programatically. $_POST['passwd'] = "'" . stripslashes(trim($_POST['passwd'])) . "'"; Although I'm not real confident that will really work. You are trying to fix the problem in the wrong place and it would probably be best achieved within the Python script. Plus, to Jacques1 point, you state this is for 'private' purpose, but yet you state you have users that you don't want to have to dictate format. Rather than ignore the comments given you really need to take them into serious consideration. If you need help - then ask. But, I will ask the same question as before. Why are you using a Python script to hash the password when you can do that easier in PHP? EDIT: Never mind, I see you are changing a Linux password. I thought this was a password for the user in the DB. Although, I would look for a way to do it in PHP if possible. I really don't have knowledge of something like that.
-
How are you verifying "where" the dollar signs are getting modified? I can think of no reason why PHP would modify the value in that manner, so my guess is that the problem is with how the dollar sign is interpreted in Python. I don't know Python at all, but a quick Google search found several pages regarding special string interpretations for dollar signs within strings for Python. If having single quotes around the value works and does not change the value that Python interprets, you could add quotes around the value before you pass it. If not, then you really need to be looking for a Python solution. But, why are you using Python to hash the password when you can do it within PHP anyway. Seems like an over-complication.