Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
If you are setting "pm_id" manually then you already have the value. So, you could just set it in both quries as needed. But, if "pm_id" is getting set via an auto-increment id in one table and you need the same value for the insertion into a second table, then you would want to be using mysql_insert_id() to get the auto generated ID from teh first query so you can use that value as a foreign key in the subsequent query.
-
Your query is failing. Either you have not connected to the db properly or there is a typo in your query. Try using this to see what the error is $query = "SELECT prof_pic FROM members_profile WHERE id = '".$_SESSION['EEID']."'"; $result = mysql_query($query) or die("Query: {$query}<br>Error: " . mysql_error()); $mem_num_rows = mysql_num_rows($result); if($mem_num_rows =1
-
What are you taking about "every line". There is only a single database query. Are you trying to run the query through PHP or are you running it via PHPMyAdmin (or whatever DB management tool you have)? If this is a one-time operation, just run it through PHPMyAdmin. If you need this to be run via a web-page, you should still test it via PHPMyAdmin first to see if it works. As a test, you could run a select query to see that the JOIN is working correctly and what the "correct" results will be. The following SELECT query is exactly the same as the UPDATE query but it will show the current 'first_name' value in the info table and the current 'name' value in the users table. If you were to run the UPDATE query above, then the first column would have the same value as the second column. SELECT info.first_name as first_name, users.name FROM jos_vm_user_info AS info JOIN jos_users AS users ON info.user_id = users.id
-
Well, what do you mean by "each line"? I can type a whole paragraph and it is only one line, but it will display on multiple lines based upon how wide the content frame is to display it. Usually when text is "quoted" in the manner you describe (such as in an email) the content has hard breaks added to it. So, assuming you want to add hard breaks, you need to decide how many characters there should be per line. So, you can use wordwrap() to split the strings into lines. Then explode() the content into an array based upon the line breaks, loop through each line to add the preface characters (i.e. "> message >>"), then lastly implode() the content back into a string with line breaks. Assuming $input holds the text to be quoted: //Break each line by no more than 60 characters //And explode itno an array by each line $lines = explode("\n", wordwrap($input, 60)); //Add the preface text to each line foreach($lines as &$line) { $line = "> message >> {$line}"; } //Implode the results back into a string variable to be output $output = implode("\n", $lines);
-
Did you just create an HTML file on your computer and run it or did you put the file on a web server and access it via http? What do you mean "direct access" a JQuery request is direct access. If the page is not supposed to be accessed directly and should only be include()ed in other PHP files then simply put the file outside the publicly accessible web directory. But, if your goal is only to allow the file to be accessed via AJAX you can put a ton of work into it and it would never be foolproof. The server doesn't know an AJAX request vs. a normal browser request and all of the data sent/received in either case is easily spoofed.
-
I think you are thinking too hard on this. A little context specific content is a good thing, but going overboard just makes it way too complicated. And complicated = more bugs and harder to maintain. Plus, some of the scenarios you think are valid may not be. > - Creating an Account Why not show the login page. What if the person got here accidentally by clicking the wrong link. Instead of forcing the user to hit the back button and then click login, they could simply click login from this page. > - Resetting Your Password Again, why wouldn't you show the login link here. What if the user came here by accident OR after clicking the link to come here they suddenly remembered what their password is or (more likely) found the sticky note with their password? Don't make things more complicated than you need to lest you venture down the hole after the white rabbit. Some things are no brainers. If the user is logged in then you shouldn't show the login or create account links. But, you should show the logout link. But if the user is not logged in, there really isn't any harm in displaying the Login and Create Account links on any of the pages - even the login page and the create account page. If the user clicks them it will only take them back to the form. no data is submitted or saved to the database. If you really want to tailor the headers/available links for some of the "management" pages, then consider using different header includes on those specific pages instead of over-complicating your main header.
-
How to organize and name photos and albums for a photogallery
Psycho replied to shank888's topic in PHP Coding Help
The "naming" and "sorting" of the galleries and the photos really has no dependency on the file system. You can simply dump all the photos into a single directory and just make sure they have a unique filesystem name. You could use the user ID along with a timestamp for instance. All of the actual naming and sorting can be done in the database. I would only consider different folder for the images based upon my need to keep a structured filesystem not for the management of the images/galleries. -
I assume the Login/Registration links are included in the body_header.inc.php file which is called from many different other files. So, just set a var (or vars) that you can use to determine if you will show the Login/Registration links or not - or other content (or not). You already know that you will use the user's logged in status as ONE determination for displaying those links the My Account/Log out links. So, you need another variable to determine when NOT to show the Login/Registration links and NOT to show the logout links (i.e. during registration.). So, in pages that you don't want to show the login/registration links create a var for this. Persoanlly I prefer to set the default value for such a var in my config script that is loaded in all pages and then set it to the non-default value as needed. That way I don't have to worry about checking isset() all over the place. But, let's say you only set it on the pages where you do NOT want to show the login/registration links. Just use: $noLogin = true; Then in the page to create your header links, use something like this: if(isset($loggedIn) && $loggedIn) { //Show logout / my account links } elseif(isset($noLogin) && $noLogin) { //Show any links/text on the registration pages } else { //Show login / registration links }
-
OK, I just ran your script (I commented out the code that would cause me failures: DB stuff and includes) and the fields without validation failures were sticky. So, the problem may be with your browser doing some weird caching, something in one of the include files, or a configuration setting such as the register globals. Although I can't think of a config setting that would cause this not to work. I don't see anything in the DB code that would cause this not to work, but I do see three include files that are called before the form loads. require_once('../config/config.inc.php'); require_once(WEB_ROOT . 'private/mysqli_connect.php'); require_once(WEB_ROOT . 'components/body_header.inc.php'); But, only the last one is called after $firstName is set and before you use it to set the saved value in the field. Here is your PHP code from that script where I have added some debugging code to see what the value of $firstName is along the processing of the PHP code. Here you can see if it is getting properly set and if it is getting unset() somewhere along the line due to the included file. <?php //Build Date: 2011-12-26 // Initialize a session. session_start(); // Access Constants require_once('../config/config.inc.php'); // ************************************************************* // HANDLE FORM. // ************************************************************* if ($_SERVER['REQUEST_METHOD']=='POST') { // Form was Submitted (Post). // Initialize Variables. $_SESSION['resultsCode'] = ''; $errors = array(); // Trim all Form data. $trimmed = array_map('trim', $_POST); // Connect to the database. require_once(WEB_ROOT . 'private/mysqli_connect.php'); // ************************ // Validate Form Data. // ************************ // Validate First Name. if (empty($trimmed['firstName'])){ $errors['firstName'] = 'Please enter your First Name.'; }else{ if (preg_match('#^[A-Z \'.-]{2,20}$#i', $trimmed['firstName'])){ $firstName = $trimmed['firstName']; echo "First name is set as ($firstName)<br>\n"; ##DEBUGGING LINE }else{ $errors['firstName'] = 'First Name must be 2-20 characters (A-Z \' . -)'; } } // Validate Email. if (empty($trimmed['email'])){ $errors['email'] = 'Please enter your E-mail address.'; }else{ // **************************** // Check Email Availability. // **************************** // (Replacement for non-supported Email-Filter.) // Limit to 60 characters. if (preg_match('#^[A-Z0-9_\+-]+(\.[A-Z0-9_\+-]+)*@[A-Z0-9-]+(\.[A-Z0-9-]+)*\.([A-Z]{2,7})$#i', $trimmed['email'])){ // Valid Email. // Build query. $q = 'SELECT email FROM member WHERE email=?'; // Prepare statement. $stmt = mysqli_prepare($dbc, $q); // Bind variable. mysqli_stmt_bind_param($stmt, 's', $trimmed['email']); // Execute query. mysqli_stmt_execute($stmt); // Transfer result-set from prepared statement. // (Required for all queries that return results.) mysqli_stmt_store_result($stmt); // Check # of Records Returned. if (mysqli_stmt_num_rows($stmt)==0){ // Unique Email. $email = $trimmed['email']; }else{ // Duplicate Email. $errors['email'] = 'This E-mail is taken. Try again.'; } }else{ // Invalid Email. $errors['email'] = 'Please enter a valid E-mail address.'; }// End of CHECK AVAILABILITY. }//End of VALIDATE EMAIL. // Check Password. /* TBD */ if (empty($trimmed['pass1'])){ $errors['pass'] = 'Please enter your Password.'; }else{ // Compare Passwords. if ($trimmed['pass1'] == $trimmed['pass2']){ // Passwords Match. $pass = $trimmed['pass1']; }else{ // Passwords Different. $errors['pass'] = 'Your Passwords did not match.'; } }//End of VALIDATE PASSWORD // **************************** // Attempt to Create Member. // **************************** if (empty($errors)){ // Valid form data. // Create Activation Code. $activationCode = md5($email . uniqid(rand(), true)); // Build query. $q = "INSERT INTO member(email, pass, first_name, activation_code, created_on) VALUES(?, ?, ?, ?, NOW())"; // Prepare statement. $stmt = mysqli_prepare($dbc, $q); // Bind variables to query. mysqli_stmt_bind_param($stmt, 'ssss', $email, $pass, $firstName, $activationCode); // Execute query. mysqli_stmt_execute($stmt); // Verify Insert. if (mysqli_stmt_affected_rows($stmt)==1){ // Insert Succeeded. // Set Message. $_SESSION['resultsCode'] = 'ACCOUNT_MEMBER_ACCT_CREATED'; $_SESSION['registrationEmail'] = $email; //--------------------------------- // Create Email Content. $body = "Thank you for creating a new account.\n\nTo activate your account, please click on the link below:\n\n"; $body .= BASE_URL . 'members/activate.php?x=' . $activationCode; // Send Email. mail($trimmed['email'], 'Re: Please Activate Your Account', $body, 'From: admin@MySite.com <admin@MySite.com>'); }else{ // Insert Failed. $_SESSION['resultsCode'] = 'ACCOUNT_MEMBER_ACCT_FAILED'; }// End of VERIFY INSERT. // Close prepared statement. mysqli_stmt_close($stmt); // Close the connection. mysqli_close($dbc); // Redirect to Display Outcome. header("Location: " . BASE_URL . "members/create_account_results.php"); // End script. exit(); }else{ // Invalid form data. // Drop through to display Form. }//End of ATTEMPT TO CREATE MEMBER }else{ // Form was not Submitted (Get). // Drop through to display Form. }//End of HANDLE FORM ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <!-- ################## DEBBIE ##################### --> <!-- HTML Metadata --> <title>Create an Account</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- Page Stylesheets --> <link type="text/css" rel="stylesheet" href="/css/_main.css" /> <link type="text/css" rel="stylesheet" href="/css/_layout.css" /> <link type="text/css" rel="stylesheet" href="/css/top_menu.css" /> <link type="text/css" rel="stylesheet" href="/css/components.css" /> </head> <body> <div id="pageWrapper" class="clearfix"> <div id="pageInner"> <!-- BODY HEADER --> <?php echo "First name value before 'body_header.inc.php' is called: ($firstName)<br>\n"; ##DEBUGGING LINE require_once(WEB_ROOT . 'components/body_header.inc.php'); echo "First name value after 'body_header.inc.php' is called: ($firstName)<br>\n"; ##DEBUGGING LINE ?> <!-- MIDDLE COLUMN --> <div id="pageMidCol_1"> <!-- CREATE ACCOUNT FORM --> <form id="createAccount" action="" method="post"> <fieldset> <legend>Create a Member Account</legend> <ul> <!-- Required Note --> <li id="requiredNote"> <b>*</b> = Required Field </li> <!-- First Name --> <li> <label for="firstName"><b>*</b>First Name:</label> <input id="firstName" name="firstName" type="text" maxlength="20" value="<?php if(isset($firstName)){ echo htmlspecialchars($firstName, ENT_QUOTES); } ?>" /><!-- Sticky Field --> <?php if (!empty($errors['firstName'])){ echo '<span class="error">' . $errors['firstName'] . '</span>'; } ?> </li> <!-- Email --> <li> <label for="email"><b>*</b>E-mail:</label> <input id="email" name="email" type="text" maxlength="60" value="<?php if(isset($email)){echo htmlspecialchars($email, ENT_QUOTES);} ?>" /><!-- Sticky Field --> <?php if (!empty($errors['email'])){ echo '<span class="error">' . $errors['email'] . '</span>'; } ?> </li> <!-- Password1 --> <li> <label for="pass1"><b>*</b>Password:</label> <input id="pass1" name="pass1" type="password" maxlength="40" /> <?php if (!empty($errors['pass'])){ echo '<span class="error">' . $errors['pass'] . '</span>'; } ?> </li> <!-- Password2 --> <li> <label for="pass2"><b>*</b>Confirm Password:</label> <input id="pass2" name="pass2" type="password" maxlength="40" /> </li> <!-- Submit Form --> <li> <input type="submit" name="createAccount" class="button" value="Create Account"/> </li> </ul> </fieldset> </form> </div><!-- End of #MIDDLE --> </div><!-- End of #INNER --> </div><!-- End of #WRAPPER --> <!-- BODY FOOTER --> <?php ###require_once(WEB_ROOT . 'components/body_footer.inc.php'); ?> </body> </html>
-
Why? I gave you an example of why. If the user makes a simple typo they would only have to make a small correction instead of having to retype everything. You say you are "used to incorrect data being wiped clean" but I know that the vast majority of applications I use do repopulate the invalid date (except for data in password fields). In addition to allowing the user to make the minor correction it also allows the user to "see" the validation error for themselves. Most validation errors are from simple typos. So, if I was to submit a form and get a message that one or more of the fields was invalid (with or without the reasons) and the data I entered was not displayed, I would question whether or not the validation was in error vs. my input. I have encountered numerous instances where a site was incorrectly validating input I entered and I had to modify my input to allow it to pass. If the value I had entered was not displayed it would take numerous trial and error attempts to figure this out. For example, your current logic does not support accented characters; someone with the name "ValentÃn" would consider all their characters as being between A-Z, but your validation would tell them that their name is invalid (ALso, you might want to take a second look at the error message - since it is wrong). Back your problem, if you are setting the value for $firstName and it is not being output when you do an echo then either 1) the same variable name is not being used (which doesn't seem to be the problem), 2) the variable is being unset or changed somewhere between where it is set and where it is output (unable to tell from what has been provided) or 3) the value is not begin set before it is being output (i.e. there is a problem with the logical flow). For reasons #2 and #3 are why you have been asked to provide the entire code. It would be interesting to see where you are initiating the form validation logic vs. the output of the form. And, I just had a thought, are you doing a header() redirect to the form if validation fails? IF so, then reason #2 explains your problem. EDIT: I just checked three "major" sites (Gmail, Facebook & Windows Live) and tried to create a new account with invalid data. In all three instances, the invalid data was not wiped. As I said, this is an industry standard.
-
Well, I don't know what to tell you. I used the table structures above to exactly duplicate the tables you have. Then I populated them with some sample data as follows: jos_users id | name ------------ 1 name1 2 name2 3 name3 4 name4 jos_vm_user_info user_info_id | user_id | first_name ----------------------------------- 1 1 8 2 10 3 I then ran the exact script I provided above and the jos_vm_user_info table was changed as follows user_info_id | user_id | first_name ----------------------------------- 1 1 name1 8 2 name2 10 3 name3 I also tried running AGuyWithAthing's query. Although I have seen that particular format before I kept getting a syntax error and couldn't find the proper format. But, I came up with the following that does do the same thing without a subquery and should be more efficient. UPDATE jos_vm_user_info AS info JOIN jos_users AS users ON info.user_id = users.id SET info.first_name = users.name Again, both the original query I provided and the one above work as expected against two tables set up exactly as you have them.
-
Why are you not using session values? That is pretty "weak" security if that is your goal. A user could simply put a link into an HTML page with the full URL and the HTTP_REFERER will have a value. A session value will persist across all page requests and takes zero management - i.e. you don't need to append the value to query string and make sure it persists from page request to page request. All you need to do is put session_start(); at the top of any page that you need to set/access the session values. In index.php you would have something like session_start(); $_SESSION['JEXEC'] = true; Then in the page myinerpage.php you would have session_start(); if(!isset($_SESSION['JEXEC']) || !$_SESSION['JEXEC']) die("Access denied"); Then you do not need anything in the JavaScript/AJAX code.
-
That's the point... (I don't want *invalid data* to be sticky!!) And, why do you want to go with a completely different process than what has been working fine as an industry-wide standard. As a general rule the only fields that are not made sticky are password type fields because the user cannot see what they contain. If a user types in "username@mydomaincom" and simply forgets the period for the ".com" why would you want to wipe out what they had entered. Simply re-populate with the value they entered so they can enter the period. You are making this much more complicated than it needs to be. If $firstName is getting set, then the problem would likely be in the order that you are running the code such that $firstName is not set when you are generating the form.
-
Look at your logic. You are only defining $firstName if validation passes. Just set $firstName, THEN do the validation. If validation passes then $firstName is set and if validation fails $firstName is set. // Validate First Name. $firstName = (!empty($trimmed['firstName'])) ? $trimmed['firstName'] : false; if (!$firstName) { $errors['firstName'] = 'Please enter your First Name.'; } elseif(!preg_match('#^[A-Z \'.-]{2,20}$#i', $trimmed['firstName'])) { $errors['firstName'] = 'First Name must be 2-20 characters (A-Z \' . -)'; }
-
mixing html and php variable names in an echo statement
Psycho replied to Aaron4osu's topic in PHP Coding Help
Variables are only parsed in a string that is defined with double quotes or the heredoc method of defining strings. You can use the double quotes to define your string and single quotes around the html tag parameter values or you can escape the double quotes around the tag parameters. //Use single quotes for html parameters echo "< img src='{$row['image_source']}' />"; //Escape double quotes for html parameters echo "< img src=\"{$row['image_source']}\" />"; Of if you don't want to use single-quotes and you don't want to escape look into the heredoc method: http://www.php.net/manual/en/language.types.string.php -
The problem is that the definition you set in index.php will not exist in myinerpage.php because it is a separate script execution. The AJAX is a separate page request. It is no different than if you clicked a link to go to another page - any variables defined in the previous page will not exist in the next page. You could either set a session variable to check or you could write the value of _JEXEC as a JavaScript variable and append it to the AJAX call so you can check in within the $_GET array
-
Hmm . . . I ran it on two tables I set up to mimic your setup and it updated all the records accordingly.
-
You need to take a different approach. I would calculate average of the DATEDIFF (in days) of each record and divide by 365. You can also calculate the highest age using the MIN() date. I also threw in the option for the minimum date. Of course all of the dates int eh calculations must be above 21 years old. SELECT AVG(DATEDIFF(NOW(), date_of_birth))/365 as avg_age, DATEDIFF(NOW(), MAX(date_of_birth))/365 as min_age, DATEDIFF(NOW(), MIN(date_of_birth))/365 as max_age FROM table_name WHERE date_of_birth <= DATE_SUB(NOW(), INTERVAL 21 YEAR)
-
Then show the query you would use. This should be for a one-time operation so I wasn't interested in efficiency. I did above ^^ But, why didn't you display it in a manner that I wouldn't miss it and make a fool of myself. How rude.
-
You cannot do that - it is not a DOM compliant document. It would have to be a rendered HTML document to do that. If you have content that needs to be modified, then you should store that content in a database. Or, you could even put the editable text into separate flat text files that you could read/modify. Or, if you really, really want to take this approach you could build a complex process to do the following: 1. Load the file via an http request. 2. Use DOM to find the DIV content you want to modify and save it to a variable ($original) 3. Make the modifications you want to the content and save to a different variable ($new) 4. Open the same file via the file system and load the contents into a variable ($content) 5. Do a str_replace() using str_replace($original, $new, $content) 6. Write the new, modified contents back to the file
-
Then show the query you would use. This should be for a one-time operation so I wasn't interested in efficiency.
-
Then something is NOT as you say it is. According to you the checkboxes are created like this: <input name="checkbox[]" type="checkbox" value="{$r['id']},{$r['friendid']}"> So, if you had three checkboxes with various values, they may look like this <input name="checkbox[]" type="checkbox" value="5,31"> <input name="checkbox[]" type="checkbox" value="12,8"> <input name="checkbox[]" type="checkbox" value="5,7"> If the user checked all those boxes the resulting POST array would be [`] => "5,31", [1] => "12,8", [2] => "5,7" That is an array with three string values. If you iterate through that array you can explode each value using the comma to get the two unique values. The code I provided should do just that - if your checkboxes are in the format you say they are.
-
What? There is only ONE array: $_POST['checkbox'] The values of those array elements are simple a string with what appears to be two numbers separated by a comma. I don't know why you would want to implode the POST data. I would think you would want to run a foreach() loop on the checkbox array and then explode the value on the comma to get the two unique IDs and then perform an operation on them. foreach($_POST['checkbox'] as $postVal) { list($id, $friendid) = explode(',', $postVal); echo "ID: {$id}, Friend ID: {friendid}<br>\n"; }
-
Oh, I didn't see that those two queries were from two different tables. No matter, you can still run just one query. I'm just not sure of the exact syntax. I'll post back shortly with a solution. EDIT: Here you go UPDATE jos_vm_user_info AS i SET i.first_name = (SELECT u.name FROM jos_users AS u WHERE u.id = i.user_id)