Jump to content

Psycho

Moderators
  • Posts

    12,146
  • Joined

  • Last visited

  • Days Won

    127

Everything posted by Psycho

  1. That code you posed may work, but it is inefficient and doesn't follow a logical flow. For instance you have several places where you have code to connect to the database. That is a waste of code. You just need to check if at least one checkbox is checked - and then connect to the db. That code also has the same problem with the code to display the results. By "copying and pasting" the same code to different places the code will be difficult to debug and will be error prone. For example, if you discovered an error in the display code it might get fixed in one place and not another.
  2. It would be very helpful if you provided a few lines of data from the text file and explained exactly what you want returned. Without knowing the format of the input and output it is difficult, if not impossible, to provide a good response.
  3. Your original post didn't mention anything about that! I see several problems in the above code: 1. The final "else" for the logic to display the records if there are any is not enclosed withing opening and closing brackets, so even when there are 0 records that code will run 2. The code for determining the records to display includes a WHERE clause, but the code to determine the max page count does not. So, there will be page links for ALL the records, not just the records in the result set. 3. There is no validation for "user" input - e.g. the page number. The code would error if the user put an invalid value on the query string. Or, worse, the user could use SQL inqection to cause serious problems. Here is a quick rewrite (may be some syntax errors, since I didn't test): <?php // how many rows to show per page $rowsPerPage = 2; //Get user ID $sessid = $_SESSION["username"] ; // how many rows we have in database $query = "SELECT COUNT(id) AS numrows FROM job WHERE username='" . $sessid. "'"; $result = mysql_query($query) or die('Error, query failed'); $row = mysql_fetch_assoc($result, MYSQL_ASSOC); $numrows = $row['numrows']; // how many pages we have when using paging? $maxPage = ceil($numrows/$rowsPerPage); // determine the current page number // if $_GET['page'] defined, use it as page number // NEED TO VALIDATE THAT $_GET['page'] IS A VALID NUMBER $pageNum = 1; //Default value if(isset($_GET['page']) && $_GET['page']>=1 && $_GET['page']<=$maxPage) { $pageNum = $_GET['page']; } // counting the offset $offset = ($pageNum - 1) * $rowsPerPage; // run the query $query = "SELECT * FROM job WHERE username='" . $sessid. "' LIMIT $offset, $rowsPerPage"; $result = mysql_query($query) or die('Error, query failed'); //Determine if there are results to display if(!$result) { // check if is something wrong print "Error:" . mysql_error(); } else if (mysql_num_rows($result) == 0) { print "No Jobs Exist, please select 'Add job' to add a job vacancy to the system."; } else { // print the random numbers while($row = mysql_fetch_array($result)) { $username=$row['username']; $id=$row['id']; ?> <form class="jobform" action=""> <fieldset> <p class="edit"> </fieldset> <fieldset> <label for="jobtitle">Job Title:</label> <input readonly name="jobtitle" type="text" id="jobtitle" value="<?php echo $row["jobtitle"]; ?>" /><br /> </fieldset> <fieldset style="width: 602; height: 58"> <label for="jobcatergory">Job Catergory:</label> <input readonly name="jobcatergory" type="text" id="jobcatergory" value="<?php echo $row["jobcatergory"]; ?>" /> </fieldset> <fieldset> <table border="0" align=right width="40%" id="table14"> <tr> <td align="right"><span class="navyboldtxt"><p align="right"><?php echo "<a href='editjob.php?username=$username&id=$id'>Edit/Update Job</a>"?></p></td> <td align="right"><span class="navyboldtxt"><p align="right"><?php echo "<a href='deletejob.php?username=$username&id=$id'>Delete Job</a>"?></p></td> </tr> </table> </fieldset> </form> <?php } // end while loop echo '<br>'; echo '<br>'; // print the link to access each page $self = $_SERVER['PHP_SELF']; $nav = ''; for($page = 1; $page <= $maxPage; $page++) { if ($page == $pageNum) { $nav .= " $page "; // no need to create a link to current page } else { $nav .= " <a href=\"$self?page=$page\">$page</a> "; } } // creating previous and next link // plus the link to go straight to // the first and last page if ($pageNum > 1) { $page = $pageNum - 1; $prev = " <a href=\"$self?page=$page\">[Prev]</a> "; $first = " <a href=\"$self?page=1\">[First Page]</a> "; } else { $prev = ' '; // we're on page one, don't print previous link $first = ' '; // nor the first page link } if ($pageNum < $maxPage) { $page = $pageNum + 1; $next = " <a href=\"$self?page=$page\">[Next]</a> "; $last = " <a href=\"$self?page=$maxPage\">[Last Page]</a> "; } else { $next = ' '; // we're on the last page, don't print next link $last = ' '; // nor the last page link } // print the navigation link echo $first . $prev . $nav . $next . $last; } ?>
  4. it doesnt same to work properly What does that mean. What does it do? The code looks OK as long as you add two closing brackets to the end of the code that displays the results. Personally, I wouldn't use nested IF statements and just use a single closing bracket after the result code, like this: if(!$result){ // check if is something wrong print "Error:" . mysql_error(); }else if (mysql_num_rows($result) == 0){ print "No Jobs Exist"; }else{ // Results code goes here } //closing bracket
  5. <?php //Read import file into an array $data = file("import_file.txt"); //Iterrate through each record foreach ($data as $record) { //Explode record into individual data elements $record_set = explode(',', $record) //Create the query //modify the field names and record values as needed $query = "UPDATE table SET fieldA = '{$record[3]}', fieldB = '{$record[4]}', fieldC = '{$record[5]}', fieldD = '{$record[6]}' WHERE company = '{$record[0]}' AND contact = '{$record[1]}' AND zip = '{$record[2]}'" //Update the records (if exist) mysql_query($query) or die (mysql_error()); } ?>
  6. You might want to consider using formatting within your code (i.e. indenting) and comments to help make it easier to understand and follow the logic. <?php //At least one checkbox selected if (isset($_POST['a']) || isset($_POST['b'])) { //Connect to database mysql_connect("localhost","root",""); mysql_select_db("a"); if (isset($_POST['a1']) && isset($_POST['b1'])) { //Both checkboxes selected $query = "select * from a where id like '$_POST[a]' or id like '$_POST[b]'"; } else if (isset($_POST['a']) { //Only A checkbox selected $query = "select * from a where id like '$_POST[a]'"; } else { //Only B checkbox selected $query = "select * from a where id like '$_POST[b]'"; } //Query & Display the results $result = mysql_query ($query) or die (mysql_error()); while ($row = mysql_fetch_array($result)) { echo "$row[id]<br>"; } } ?>
  7. Ah yes, thanks for the correction.
  8. Keep the code in the php file where it belongs and not in the database. A database is meant for data not code. You have not provided any information concerning the reason for wanting to put code into the database so I cannot provide any meaningful comments. But, the fact that you can't simply take "code" from the database and have it execute should be a clue that it was not built for that purpose. But, like I said you should be able to so it with exec()
  9. No, it is not a glitch. I am assuming you are storing "text" in the form of PHP code in your database and then querying for that code - which is actually "text" not code. You could use the exec() command, but I think there are probably much better solutions than storing PHP code int he database to begin with.
  10. "applyForumChildrenTree" is a recursive function, how the function works is it starts from the root parent, then gets all topics and replies from that forum, then runs that function again based on the current child forum that had the parent from the start and so on.. it keeps doing the process over and over. But I'm going to use $GLOBALS I think. Well you *could* do that. You could simply modify applyForumChildrenTree() to accept a parameter that is the input array and it returns the output array. So, when it goes through it's recursive process it adds to the array and in the end it passes back the completed array. But, I think laffin has a better solution anyway.
  11. No it's not a bug. Just because you call a function from within another function does not mean variables are "accessible" between the two (i.e. they do not have the same scope). Try this. Modify the function applyForumChildrenTree() to return the array. Then change the getForumChildrenTree() as follows: {code]function getForumChildrenTree( $id ) { $id = intval( $id ); $treeResult = applyForumChildrenTree( $id ); }
  12. Well, I have no clue what you are trying to accomplish by having this in your FORM tag: onSubmit=\"return validate($_POST)\" First off $_POST would be an array in PHP and could not be made available to JavaScript in that fashion. Remember the FORM posts to a PHP page not to the JavaScript. Just change that line to this: onSubmit=\"return validate()\" And change your JavaScript validation to this: <script type="text/javascript"> function validate() { var email = document.getElementById("userEmail"); if (!validEmail(email.value)) { alert("Please Insert a Valid Email Address"); email.focus(); return false; } var password = document.getElementById("userPassword"); if (!$password.value || password.value.length<6) //Use minimum length here { alert("Please Insert a Valid Password"); password.focus(); return false; } var passwordconfirm = document.getElementById("userConfirmPassword"); if (password.value != passwordconfirm.value) { alert("Passwords do not match!"); password.focus(); return false; } var firstname = document.getElementById("userFName"); if (!firstname.value) { alert("Please Insert a Valid First Name"); firstname.focus(); return false; } var surname = document.getElementById("userSName"); if (!surname.value) { window.alert("Please Insert a Valid Surname"); surname.focus(); return false; } return true; } function validEmail(emailStr) { validEmailRegEx = /^[\w\+-]+([\.]?[\w\+-])*@[a-zA-Z0-9]{2,}([\.-]?[a-zA-Z0-9]{2,})*\.[a-zA-Z]{2,4}$/ return emailStr.match(validEmailRegEx) } </script>
  13. Um, what? First off there is nothing in that code that would output anything to the page. Seconds, you changed the definitions to cmparisons as well (which shouldn't be). Third why would the code go through the logic to determine the value of $order, just to then define $order2 to be the same? <?php $order = (empty($_GET['order'])) ? "albumname ASC" : $_GET['order'] ; echo $order; ?>
  14. And, what errors are you receiveg, if any. Which process does not execute? You should add error handling at every DB action. <?php $connect = mysql_connect($db_host,$db_user,$db_pass) or die(mysql_error()); mysql_select_db($db_name)or die("Couldn't select") or die(mysql_error()); // Empty table $query = "DROP TABLE IF EXISTS `jhearnsberger.books_copy`"; mysql_query($query) or die($query."<br>".mysql_error()); $query = "CREATE TABLE IF NOT EXISTS `jhearnsberger.books_copy` SELECT * FROM `jhearnsberger.books`"; mysql_query($query) or die($query."<br>".mysql_error()); $query = "DELETE FROM $db_name.$destable"; mysql_query($query) or die($query."<br>".mysql_error()); // do the data import $query = "load data infile \"$source_file\" INTO TABLE $destable FIELDS TERMINATED BY '|'"; mysql_db_query($db_name, $query, $connect) or die(mysql_error()); ?>
  15. I hear you. But, the original question makes no sense. If the field exists but is NULL then you would still do an UPDATE not an INSERT. I went with a different interpretation since the OP did mention using an INSERT.
  16. Your request makes no sense as written. Why would you have a WHERE clause on an insert? I *think* you are wanting to update a value in a record if it exists and if the record does not exist, then create one. If that is the case you should be using INSERT ... ON DUPLICATE KEY UPDATE http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html You will need to make the "field" a UNIQUE index or PRIMARY KEY. <?php $SQL = "INSERT INTO table (field) VALUES ('{$_POST['value']}') ON DUPLICATE KEY UPDATE field='{$_POST['value']}'"; ?>
  17. User enters this into a textarea: Here is some text with several line breaks You would enter that (as is) into the database. Now when you need to display that text in HTML you would use this: nl2br($textFromDB) which would output this: Here is<br />some text<br />with several<br />line breaks However if you need to populate the original text back into a textarea for editing you just use the value from the database w/o nl2br().
  18. Hmm, I'm not 100% sure, but I'm thinking that destroying the session is causing the problem. Try removing just that line, or you can try this (might be less efficient, but should do what you are looking for): <?php //Unset all SESSION values except 'id' foreach ($_SESSION as $index => $value) { if ($index!='id') { unset($_SESSION[$index]); } } ?> EDIT: Found this in the manual (emphasis added):
  19. I'm assuming you meant to post a < br /> tag above. I would suggest NOT converting line breaks to BR tags before saving to the database. Otherwise youwill have to convert again if you need to repopulate a textarea for editing. Instead, when you get the content from the database, use nl2br() when displaying it.
  20. Thanks for the elaboration. A quick test verified your position. It's not that I don't believe you - I just always test something, if possible, instead of blindly accepting. Running through 10,000 itterations of both methods gave varrying results, but the latter method was approximately 50% faster: 0.1 seconds vs. .05 seconds. Considering that is for 10,000 itterations the difference may not seem relevant. But, for sites with a large amount of traffic every little bit adds up. Thanks again.
  21. @effigy, Our RegEx's appear to do the exact same thing, but using different logic. After reviewing yours it appears more elegant and easier to understand. However, I'm curious, did you see a flaw in my expression or did you just want to post your version?
  22. I would suggest preg_replace() instead. $new_text = preg_replace('/<img.*?>/', '', $old_text);
  23. Your "question" is way too long and convoluted. The quality of the answers are directly proportional to the quality of the questions asked. All you needed to do was to boil the question down to the specific problem.
  24. Yeah, there are some problems with the opening and closing brackets. Your opening script tag should be using "type" instead of "language". Here are some validations that should work for you below: The alpha check allows letters, the space, the hyphen and the apostrophe (since names can contain those characters). The phone check allows numbers, parenthesis, space, and the hyphen The email check only allows properly formatted email addresses. You can get more restrictive on these validations (e.g. phone numbers must be 7 or 10 characters), but I included validations based upon your post. <script type="text/javascript"> function validateForm(form) { var fe = form.elements; //validate owner id if (!requiredCheck(fe['dbOwnerId'], 'Owner')) return false; //validate first name if (!requiredCheck(fe['dbFname'], 'First Name')) return false; if (!validAlpha(fe['dbFname'], 'First Name')) return false; //validate last name if (!requiredCheck(fe['dbLname'], 'Last Name')) return false; if (!validAlpha(fe['dbLname'], 'Last Name')) return false; //validate email address if (!requiredCheck(fe['dbemail'], 'Email address')) return false; if (!validEmail(fe['dbemail'], 'Email address')) return false; //validate main phone if (!requiredCheck(fe['dbmainphone'], 'Main Phone')) return false; if (!validPhone(fe['dbmainphone'], 'Main Phone')) return false; //validate other phone if (!validPhone(fe['dbotherphone'], 'Other Phone')) return false; //validate address if (!requiredCheck(fe['dbaddress'], 'Address')) return false; //validate address 1 if (!requiredCheck(fe['dbcity'], 'City')) return false; if (!validAlpha(fe['dbcity'], 'City')) return false; //validate post code if (!requiredCheck(fe['dbpostcode'], 'Post Code')) return false; //validate password if (!requiredCheck(fe['dbpassword'], 'Password')) return false; return true; } function requiredCheck(fieldObj, fieldName) { if (!fieldObj.value) { alert(fieldName+' is required.'); fieldObj.focus(); return false; } return true; } function validEmail(fieldObj, fieldName) { validEmailRegEx = /^[\w\+-]+([\.]?[\w\+-])*@[a-zA-Z0-9]{2,}([\.-]?[a-zA-Z0-9]{2,})*\.[a-zA-Z]{2,4}$/ if (!fieldObj.value.match(validEmailRegEx)) { alert(fieldName+' is not in the proper format.'); fieldObj.focus(); return false; } return true; } function validAlpha(fieldObj, fieldName) { validAlphaRegEx = /^[a-zA-Z '-]*$/ if (!fieldObj.value.match(validAlphaRegEx)) { alert(fieldName+' contains invalid characters.'); fieldObj.focus(); return false; } return true; } function validPhone(fieldObj, fieldName) { validNumberRegEx = /^[\d \-()]*$/ if (!fieldObj.value.match(validNumberRegEx)) { alert(fieldName+' contains invalid characters.'); fieldObj.focus(); return false; } return true; } </script>
  25. It's not that there are no records to display. Using die in that fashion means there was a critical error when trying to run the query. But, you can (and should) take an approach that exits the script gracefully. Note: You should create your queries as variables so you can echo them to the page when there is an error: Example: <?php $query = "Select count(*) from carshare"; $result = mysql_query($query); if (!$result) { echo "The query:<br>$query<br><br>"; echo "failed with the following error:<br>".mysql_error(); } else { //display the results } //Continue with rest of page ?>
×
×
  • 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.