Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
Or return an object: <?php function multiValues($number1, $number2) { $vals->average = ($number1+$number2)/2; $vals->max = ($number1>$number2)?$number1:$number2; $vals->min = ($number1<$number2)?$number1:$number2; return $vals; } $values = multiValues(5, ; echo $values->average; echo $values->max; echo $values->min; //Output: // 6.5 // 8 // 5 ?>
-
From the manual: The default is both. So all elements are available by their column name and a numerical index. Either add the appropriate parameter to mysql_fetch_array() to get only one set of data or use mysql_fetch_assoc() or mysql_fetch_row(). EDIT: You posted your "any ideas?" comment while I was preparing this reply. If I had seen it before I wrote the above I would not have even bothered with a response. This is a forum where people voluntarily provide help. Waiting 11 minutes before asking "any ideas" is presumptuous to say the least.
-
Check the HTML source - I bet the value is there. The problem, I think, is that if there is a double quote in the email input then that quote is being interpreted by the HTML as ending the value. Example: <?php $userinput = ' "myemail address" '; ?> <input type="text" name="Email" value="<?php echo ($errors) ? $email : ""; ?>" /> This is what would be output to the browser: <input type="text" name="Email" value=" "myemail address" " /> Either escape the quotes before populating the value field or strip them out.
-
If you want to get VERY technical you can have just about ANY character in an email address. There is an extended standard that allows for many more characters than is in standard use. However, the extended standard is not fully supported by current email systems. Also, I have yet to see anyone using an email address using the extended format. After much research I created the following validation for email addresses (which does NOT include quote marks). It includes two parts: one to determine that the correct characters are inlcuded in each part of the email address and a second test to check for max lengths. <?php function validEmail($email) { $emailFormatTest = '/^[-\w+]+(?:\.[-\w+])*@[a-z\d]{2,}(?:[-.][a-z\d]{2,})*\.[a-z]{2,4}$/i'; $emailLengthTest = '/^(.{1,64})@(.{4,255})$/'; return (preg_match($formatTest, $email) && preg_match($lengthTest, $email)); } ?>
-
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.
-
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.
-
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; } ?>
-
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
-
<?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()); } ?>
-
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>"; } } ?>
-
Ah yes, thanks for the correction.
-
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()
-
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.
-
"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.
-
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 ); }
-
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>
-
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; ?>
-
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()); ?>
-
How to INSERT if field is empty and UPDATE if data is in it?
Psycho replied to gtrufitt's topic in PHP Coding Help
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. -
How to INSERT if field is empty and UPDATE if data is in it?
Psycho replied to gtrufitt's topic in PHP Coding Help
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']}'"; ?> -
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().
-
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):
-
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.
-
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.
-
@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?