Jump to content

Psycho

Moderators
  • Posts

    12,147
  • Joined

  • Last visited

  • Days Won

    127

Everything posted by Psycho

  1. @mac_gyver, maybe I am missing something but the query and error make perfect sense. @alphasil, You are using BETWEEN, but you are only providing one value for the between comparison. A BETWEEN is used like this WHERE foo BETWEEN 100 AND 200 Based on what you have, I think this is what you wanted SELECT `idsala`, `idtempoInicio`, `idTempoFim`, `data` FROM `req_material_reserva` WHERE `idsala` = 3 AND 12 BETWEEN `idtempoInicio` AND `idTempoFim` AND `data` = "2014-05-05"
  2. Why are you using a while() loop when there is only one record? It doesn't have a code block associated with it - but that shouldn't cause a problem in how you are using it. It just looks very odd since it isn't needed. Have you output the values from the query? Could be they are all empty. Also, the calculation will work only with that specific max value of 100. That is the wrong way to calculate the percentage. percent x totalvalue = percentvalue You have the totalvalue and the percent value so you need to calculate the percentage like this percent = percentvlaue / totalvalue i.e. percent = 100 / user points Try this <?php $query = "SELECT title, name, surname, identityno, gender FROM cic_candidates WHERE id='{$id}' LIMIT 1"; $result = mysql_query($query); if (!$result) { die("Could not successfully run query " . mysql_error()); } if (!mysql_num_rows($result)) { die("No rows found, nothing to print so am exiting"); } $maximumPoints = 100; $user = mysql_fetch_assoc($result)); $user_points = 0; $user_points += !empty($user['title']) ? 20 : 0; $user_points += !empty($user['name']) ? 20 : 0; $user_points += !empty($user['surname']) ? 20 : 0; $user_points += !empty($user['identityno']) ? 20 : 0; $user_points += !empty($user['gender']) ? 20 : 0; $percentage = $user_points / $maximumPoints * 100; echo "{$percentage}%"; //Debug echo "<br><pre>"; var_dump($user); echo "</pre>"; ?>
  3. You're doing this the wrong way. The only thing you should be posting is the ID of the selected value. The SELECT field on your form page should use the sender name as the displayed text for the options and the sender ID as the Value. Then on the receiving page you would use the passed ID to run a query to get the name and email address to use in the process of sending the email. What you are doing now would let a malicious user re-purpose your form to send SPAM.
  4. I don't think you understood what I was saying. There was a flaw in the logic you had. You had a step to increment the vote. If that passed, you had a step to send the email. If that failed you told the user that their vote wasn't registered. That would be incorrect, because the only way for the user to get to the step that sends the email would be if their vote had already been saved! As for the time, did you try incorporating it in the script? It should affect any functions that deal with time that come after where you use it (hint: put it at the top of your script).
  5. Yes, I understand that. But, as I said, what does sending you an email have to do with whether or not the vote was counted? Understanding the available functions and processes of the language only makes up part of the process of being able to program. A LARGE part of programming is just being able to think logically. That can be difficult when you are working out of your element. What will help is if you think through the process before you write the code. Create a flow chart if needed to determine what data you need to capture, what decision need to be made and what output should be generated. It may seem like it will take longer to accomplish your task when you want to start writing code, but by looking at the big picture first and making those decisions you will save your self many hours in having to rework/rewrite code because of a logic error you did not anticipate.
  6. Why are you passing four parameters to the check_output(0 function which only accepts two? The problem that you are going to have is that if you are going to limit the comments to a certain length, you will end up with some invalid HTML code because some opening HTML tags may come after the point where you are going to limit the length. This is not a trivial problem to solve. I'd suggest some google searching to find a solution that someone has already built. This seems to include some good resources: https://www.google.com/#q=php+truncate+text+retain+HTML
  7. Hmm, that can't be your working script. you define the passed value as the variable $lied, but then use $song in the query. A few other things: 1. Use comments in your code. It will make it easier for you and us 2. You are using the return value of the email() function to determine if the user sees that their vote was registered or not. You should be determining that based upon whether the query passed. If the email is not sent, that doesn't mean their vote wasn't registered. I wouldn't show the user any error based upon the email. It is not pertinent to the process for them. In fact, the fact that the query passed is not an indication that their vote passed. The query would succeed with ANY passed value. Even ones that don't exist in the database - it just wouldn't update any records. You should check that there were affected rows. 3. You should turn off error reporting when putting the script into production. The detailed reporting of errors can leak information that one could use to perform malicious activities. 4. I would suggest not 'bundling' up multiple functions in a single line - especially in an if() condition. If there is a problem, it makes it more difficult to debug Give this a try <?php //Check if the user had voted in the last 24 hours if(isset($_COOKIE['voted'])) { $expireString = date('m-d-Y h:i:s', $_COOKIE['voted']); $output = "Sorry, you can only vote once every 24 hours. You can vote again after $expireString"; } else { //Start session and enable error reporting session_start(); error_reporting(E_ALL | E_STRICT | E_NOTICE); ini_set('display_errors', '1'); //Connect to DB $host="localhost"; $user="jingleko_reload"; $pwd="*******"; $dbname="jingleko_reloader"; $link = mysqli_connect($host,$user,$pwd,$dbname) or die(mysqli_error()); //Update count for selected song $song = mysqli_real_escape_string($link,$_GET['Song']); $query = "UPDATE voting SET Votes = Votes+1 WHERE Song = '$song'"; $result = mysqli_query($link, $query); if (!$result) { //Query failed #die(mysqli_error()); //Uncomment for debugging only $output = "There was a problem processing your request."; } elseif(!mysqli_affected_rows($link)) { //No records were updated $output = "The song you selected doesn't exist." } else { //Vote was registered $songSafeHtml = htmlspecialchars($_GET['Song']); $output = "You voted for <b>$songSafeHtml</b><br> U het gestem vir <b>$songSafeHtml</b></br>"; //Set cookie to prevent multiple votes $expire = time() + (60 * 60 * 24); //Set expiration for 24 hours setcookie('voted', $expire, $expire); //Send confirmation email $to = "beheer@vlaamseradio.tk"; $subject = "There was a vote"; $message = "Someone voted for $songSafeHtml."; $header = "From: systeem@jinglekot.cu.cc \r\n"; $retval = mail($to, $subject, $message, $header); } } ?> <html> <head></head> <body> <?php echo $output; ?> </body> </html>
  8. Also, You are using the mysql_ version of real_escape_string Plus, it looks like you are putting the song title on the query string. Ideally, you should be using an ID and not a textual value for the song anyway. And, you are not checking for errors. Try this <?php //Get the passed value $song = trim($_GET['Song']); //Create DB connection $host="localhost"; $user="*****"; $pwd="******"; $dbname="jingleko_reloader"; $con = mysqli_connect($host,$user,$pwd, $dbname); //Update record count $songSQL = mysqli_real_escape_string($song); $query = "UPDATE voting SET Votes = Votes+ 1 WHERE Song = '$song'"; mysqli_query($query) or die(mysqli_error()); $songSafeHtml = htmlspecialchars($_GET['Song']); echo ("You voted for $songSafeHtml"); ?>
  9. You would, of course, escape content before inserting it into the database to prevent SQL Injection using the proper method for the database engine you are uisng (e.g. mysqli_real_escape_string() or prepared statements). However, some people would also escape the content for use on a web page [e.g. htmlentities()]. I think that is the wrong approach. It makes it easier since you don't have to think about it so much when you pull data from the database to display on your page, but you will lose fidelity. Once you escape content you can not with certainty) revert it back to its original state. I believe you should only escape content using the appropriate method at the time that you will use it. Otherwise, keep the content in it's original format. For example, if you were to run the content through htmlentities() before storing the in the database and later decided you wanted a way to output the data to a text file you would end up with something much different than was intended. So, I would store the content exactly as it is entered (escaping for the database, of course). Then, when building the page I would use htmlentities() or htmlspecialchars() on any of that content to ensure it doesn't get rendered as actual HTML code.
  10. Here's another way of explaining the problem that may make sense. That loop is defining a function to run when the links are clicked. If you strip out just that function you end up with this function(){ alert(links[i].href); return false; }; links is not defined when the function is called by the onclick event. It is not inserting the value of links[i].href on each iteration of the loop. But, that's just the wrong way to do this anyway. For that to work you have to dynamically create a unique function for each hyperlink. Instead, just create one function that the links pass an event handler to so the function can reference the href value - as requinix showed.
  11. You marked your own response as the best answer?
  12. Did you think to test what the result of ($i % 4) would be for different values of $i? If you had it would have shown that you were on the right track, but made one flaw. for($i=0; $i<14; $i++) { echo "{$i} : mod 4 = " . ($i%4) . "<br>\n"; } Here are the results of that test (I've highlighted the ones that I think you should pay attention to: EDIT: cyberRobot beat me to it (because he took the easy route ), but I wanted to hopefully teach you how to solve problems like this in the future.
  13. I had originally wrote the code with the assumption that you had an ID column in your database and then decided to change it to only use the link value. In doing so, I forgot to revert a line to the correct value This $link = mysql_real_escape_string($_GET['id']); Should be this $link = mysql_real_escape_string($_GET['link']); Also, in case it isn't clear. The second block of code in my first reply would be for the page referrer.php that you would create for the links to point to.
  14. This forum is intended for people to get help with code they have written. So there is an expectation that the person has at least a basic knowledge. I left off the DB connection in my code because I assumed you would add that (and anything else you want to include). Also, I mistakenly used the mysql_ versions and not the mysqli_ That sounds correct I always use the same variable to define my queries. Once I run the query, I store the result in $result. After that I no longer need the value stored in $query because I've already run it. Here's a revise of what I provided previously <?php //Connect to DB $con = mysqli_connect('database', 'username', 'password', 'random_link'); if (!$con) { die('Could not connect: ' . mysql_error()); } //Get the first link with the lowest count and lowest ID $query = "SELECT id, link FROM links_table ORDER BY count ASC, id ASC LIMIT 1"; $result = mysqli_query($con, $query); $link = mysqli_fetch_assoc($result); //Update the count for the selected link $query = "UPDATE links_table SET count = count + 1 WHERE id = {$link['id']}"; $result = mysqli_query($con, $query); //Display the link to the user echo "<a href='{$link['link']}'>{$link['link']}</a>"; ?>
  15. First off, the terminology "load balancing" means something completely different than what you are asking for. Which may be why no one has responded yet. In any event, you are making this way too complicated. Just keep a count (in the database) of when these links are used. Then you can simply use an ORDER BY in your query to get the next record. This assumes the links have an ID in a specific numerical order to determine the order in which they would be displayed. //Get the first link with the lowest count and lowest ID $query = "SELECT id, link FROM links_table ORDER BY count ASC, id ASC LIMIT 1"; $result = mysql_query($query); $link = mysql_fetch_assoc($result); //Update the count for the selected link $query = "UPDATE links_table SET count = count + 1 WHERE id = {$link['id']}"; $result = mysql_query($query); //Display the link to the user echo "<a href='{$link['link']}'>{$link['link']}</a>";
  16. You can do this in one of two ways. 1. Use JavaScript to add an onclick function to the links to run a function that would make an AJAX call to a PHP page to increment the counter for the page being requested then allow the link to open the selected page. 2. Use an intermediary page. Instead of having your links open directly to the external page have them open to a page you host - passing a value to identify the external page. On that intermediary page, perform your Database query to update the hit count and then redirect to the external page. Assuming you have a unique ID for your links, change your current page to something like this: <?php $query = "SELECT link FROM links WHERE link='external'"; $result = mysql_query($query) if (!$result) { echo "Error" . mysql_query(); die(); } if(!mysql_num_rows($result)) { echo "No data"; } else { while ($row = mysql_fetch_assoc($result)) { echo "<a href='referrer.php?link={$row['link']}'>{$row['link']}</a>\n"; } } ?> <?php //Get value from URL and update count $link = mysql_real_escape_string($_GET['id']); $query = "UPDATE link SET count = count + 1 WHERE link='$link'"; $result = mysql_query($query); if (!$result || !mysql_num_rows($result)) { echo "Error" . mysql_query(); die(); } //Redirect user to external link header("Location: {$link}"); exit(); ?>
  17. Yeah, no reason to actually fix the underlying problem. Much better to keep putting patchwork band-aids in place that you'll continually need to work around and tweak over time. As stated previously INSERT IGNORE will suppress all errors - not just duplicate checks. Based on the level of code in question, I don't think it makes sense to ignore errors. Plus, the unique constraints would only work for the values in the same columns. If you don't want to fix the real problem, then I would suggest doing a SELECT first to check for existing records. If none are found then do the INSERT. But, as stated previously, you could end up with duplicates due to race conditions - i.e. two people inserting records at the exact same time. It will be pretty rare. But, you could also follow up with the third query to look for duplicates and delete the latter to cover that very small possibility.
  18. Psycho

    FIND_IN_SET

    You're doing this the wrong way. You don't need to run the two queries. You only need one. A good indicator that there's a problem is the user of GROUP_CONCAT(). You should never be dealing with comma separated lists to compare/search for values. $query = "SELECT injuryreport.*, 0 AS section FROM injuryreport JOIN injurylocations ON injuryreport.injury = injurylocations.location WHERE report='yes' AND injurylocations.general='$general'"; $result = mysql_db_query($db, $query, $conn); // check for errors if (!$result) { die("ERROR: " . mysql_error()); } // check for results if (!mysql_num_rows($result)) { echo "I CANT FIND A LIST OF INJURY LOCATION REFERENCES"; } else { //Do something with the results }
  19. @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.
  20. 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.
  21. 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.
  22. 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.
  23. 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.
  24. 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.
  25. 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"; }
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.