Jump to content

Conjurer

Members
  • Posts

    107
  • Joined

  • Last visited

    Never

Posts posted by Conjurer

  1. I would really suggest being more explicit in your code. Instead of using a foreach() loop on the individual fields, explicitly list the fields and the code you want. It makes debugging and modification much easier. Sometimes trying to make your code "simple" causes more trouble than it is worth.

     

    The function do_query is written in such a way that you are apparently using it to run/output many different queries. If you take that approach and start implementing if/else statements for each and every possible query it is going to be a nightmare to manage. Just create a function/process for each query/output you want to run. It's better to have more code that is logically structured.

     

    Note: I used mysql instead of mysqli functions in the code below because I have them remembered by heart. Modify them as needed.

     

    PHP code:

    <?php
    
    function db_connect()
    {
        $conn = new mysqli("localhost", "username", "password", "databasename");\
    }
    
    function do_query($conn, $query)
    {
        return mysqli_query($conn, $query);
    }
    
    //connect to database
    $conn = db_connect();
    
    $query = "Select member_image, member_name, city, phone, email
              FROM directory";
    
    //call function do_query to run the query and output the table
    $directoryResult = do_query($conn, $querey);
    
    if(!$directoryResult)
    {
        $output = "<tr><td>There was a problem running the query.</td></tr>";
    }
    elseif(mysql_num_rows($directoryResult))
    {
        $output = "<tr><td>There are no records to display.</td></tr>";
    }
    else
    {
        $imgPath = "images/";
        $output  = "<tr>\n";
        $output .= "<th>Image</th>\n";
        $output .= "<th>Name</th>\n";
        $output .= "<th>City</th>\n";
        $output .= "<th>Phone</th>\n";
        $output .= "<th>Email</th>\n";
        $output .= "</tr>\n";
        while($record)
        {
            $output .= "<tr>\n";
            $output .= "<td><img src=\"{$imgPath}{$record['member_image']}\" /></td>\n";
            $output .= "<td>{$record['member_name']}</td>\n";
            $output .= "<td>{$record['city']}</td>\n";
            $output .= "<td>{$record['phone']}</td>\n";
            $output .= "<td><a href=\"mailto:{$record['email']}\">{$record['email']}</td>\n";
            $output .= "</tr>\n";
        }
    }

     

    Then in the HTML code

    <table>
    <?php echo $output; ?>
    </table>

     

    Just now trying to implement and I don't understand the piece above where it says:

    elseif(mysql_num_rows($directoryResult))
    {
        $output = "<tr><td>There are no records to display.</td></tr>";
    }

     

    Don't I just want that when the value is 0 - cause if it is 1 or higher there are rows to display?  So should it be like this instead:

    elseif(mysql_num_rows($directoryResult)='0')
    {
        $output = "<tr><td>There are no records to display.</td></tr>";
    }

     

    Thanks for the help!

  2. I have a database query set up that returns an array. I then cycle through the rows in a foreach statement that wraps each value in a <td> tag to output it to a table.

     

    It works really great, but now I need to access two of the values and add some info to them. The first field returned is an image filename and I want to wrap it in an image tag that also concatenates the image path location to the value. All the images are stored in the same location, so basically I want to take the first value form the array and add the path to where the images are and wrap the whole thing in an <img> tag.

     

    The other field I need to modify is the last value in the array which is actually an email address. For that field I want to make them an active email link so I need to wrap an <a>href=mailto: </a> tag around the value.

     

    How could I modify this code so I could add the necessary tags to these elements of the array?

     

    Here is the code I am running:

    $query = "Select
                     member_image as 'Image',
                     member_name as 'Name',
                     city as 'City',
                     phone as 'Phone',
                     email as 'Email'
                     FROM directory";
    
    //connect to database
    $conn=db_connect();
    
    //call function do_query to run the query and output the table
    do_query($conn, $querey);
    
    

    The functions called are as follows:

    function db_connect()
    {
    
        $conn = new mysqli("localhost", "username", "password", "databasename"); 
    
    }
    
    function do_query($conn, $query);
    {
    
        $result = mysqli_query($conn, $query); 
    
       WHILE ($row = mysqli_fetch_assoc($result)) 
       { 
         If (!$heading) //only do if header row hasn't been output yet 
         {  $heading = TRUE; //so we only do it once 
             echo "<table>\n<tr<>\n";
             foreach ($row as $key => $val) 
               { echo "<th>$key</th>";
                }
              echo "</tr>\n"; 
          } 
          echo "<tr>"; 
          foreach ($row as $val) 
         {
              echo "<td> $val </td>"; 
          } 
         echo "</tr>\n"; 
    } //close the while 
    echo "</table>\n"; 
    
    }
    
    

  3. I have a form that is populating fields based on a database query.  I am then trying to update the database based on any changes made in the form and passed through a POST action.

     

    The problem I am having is with the block where I declare short variable names for the $_POST variables that will be passed when the user hits the submit button.  For each variable declaration I get an error message like this:

    Encountered error: 8 in mbr_profile_updt_form.php, line 130: Undefined index: email

     

    I have tried testing the $_POST variable using the isset function but it apparently is set but empty. 

     

    What would be a good way to test to see if the user has pressed the submit button before I go into the processing block that is intended to handle those values from the form?

     

    Here is where my code is at right now:

    	if (!isset($_POST))
    	{
    		throw new Exception('You have not filled the form out completely - please go back'
    		.' and try again.');    
    	}
    else
    	{
    	//filled in so create short variable names
    		$email=$_POST['email'];
    		$first_name=$_POST['first_name'];
    		$last_name=$_POST['last_name'];
    

  4. Sorry, I had db_connect defined in an include file:

    function db_connect()
    {
        
    $conn = new mysqli("localhost", "xyz_xyzuser", "x213", "xyz_members");
         if (mysqli_connect_errno() > 0) 
      {
           $errmsg = "Failure - Could not connect to database with db_connect.<br />mysqli_connect_error message: ".mysqli_connect_error()."<br /><br />"; 
           throw (new Exception($errmsg));
         } 
         else
         {
    //echo "Connection worked! <br>";
         return $conn;
         }	  
    } 

  5. I am a bit rusty with mySQL and I tried to borrow some other query code and modify it into an update command...apparently I am trying to use an invalid property in my error checking.

     

    Basically I just want to check and see if there were NO rows updated so I can let the user no that nothing was changed.  There are probably easier ways to do this?  :confused:

     

    The page where I set the variable values is based on a form post.  I am not sure how to write my validation tests.  Right now it is running the update successfully but it is reporting back an error based on hitting the "else if" test where I am trying to see if no rows were updated. 

     

    The error message is:

    Encountered error: 8 in /home/omgma/public_html/member_community/mbr_profiles/mbr_profile_updt_post.php, line 85: Trying to get property of non-object

    No fields were updated!

     

    Error: 0

     

    //create a SQL statement
    	$updt_cmd = "UPDATE users t1, directory t2 " 
    				."SET t1.email = '$email', "
    				."t2.first_name='$first_name', "
    				."t2.last_name='$last_name', "
    				."t2.suffix='$suffix', "
    				."t2.website_url='$website_url' "
    				."WHERE t1.username ='$username' AND t2.directory_id = t1.directory_id";
    
    	$conn = db_connect();
    
    	$result = $conn->query($updt_cmd);
    	if (!$result)
    		{//could not execute query
    		  throw new Exception('<h2>Could not execute member profile update!</h2><p>Error: '
    								.mysqli_errno($conn)
    								.mysqli_error($conn)
    								.'</p>' );
    		}
    	else if ($result->num_rows==0)
    		{// no rows so nothing was updated.  
    		  throw new Exception('<h2>No fields were updated! </h2><p>Error: '
    								.mysqli_errno($conn)
    								.mysqli_error($conn)
    								.'</p>' );
    		}
    	else
    		{
    		  $mbr_profile = $result->fetch_object();
    		  print_r($mbr_profile);			 	
    		  return $mbr_profile;
    		}
    
    
    

     

    Am I using the right functions here to do this and if so where can I find the class properties to use to test if nothing was updated?

     

    Thanks

  6. Hmmm, not finding much on SALT and how to.  There were two recent approaches at the MD5() documentation discussion. 

     

    Are these both pretty much the same or would one approach be better than the other?

    Very ugly way to combine.
    
    <?php
    
    $salt = md5("1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
    $password = hash( 'MD5',$salt );
    $hash = $password . $salt;
    $rand = rand(1, 256)%4;
    
    for ( $i = 0; $i < $rand; $i++ ) {
      $hash = hash('md5',$hash );
    }
    echo $hash, '<br>';
    echo (microtime(1)-$time)*10000,': time in ms';
    ?>
    Anonymous
    08-Jun-2010 08:36
    Here's a relatively simple function I designed to hash out passwords using MD5.  Assumes max length of user supplied password (20) max length of database field (40).
    
    <?php
    define ('SALT_ONE', 'some_random_123_collection_&$^%_of_stuff');
    define ('SALT_TWO', 'another_random_%*!_collection_ANbu_of_stuff');
    
    $password = 'dragon';
    
    function generate_encrypted_password($str) {
    $new_pword = '';
    
    if( defined('SALT_ONE') ):
       $new_pword .= md5(SALT_ONE);
    endif;
    
    $new_pword .= md5($str);
    
    if( defined('SALT_TWO') ):
       $new_pword .= md5(SALT_TWO);
    endif;
    
    return substr($new_pword, strlen($str), 40);
    }
    
    echo generate_encrypted_password($password);
    ?>
    

  7. :o:confused:::)

    So it sounds like I need to modify the function since I am not adding SALT except on my food.  ;D

     

    Here is the code I came up with for changing password.  I am not sure how to SALT it and will research that in the reference doc, but given that I have to modify it to add SALT - should I change to something else?

     

     

    //---------------------------------------------------------------------------
    // function to change user password
    //---------------------------------------------------------------------------
    
    function change_password($username, $old_password, $new_password)
    // change password for username/old_password to new_password
    // return true or false
    {
      // if the old password is right 
      // change their password to new_password and return true
      // else throw an exception
      $conn = db_connect();
      assert ($conn);
    //  echo "login parameters for the change_password function:<br>";
    //  echo "User = $username, Password = $old_password, Connection = $conn<br>";
      login($username, $old_password, $conn);
      $result = $conn->query( "update users
                                set password = sha1('$new_password')
                                where username = '$username'");
      if (!$result)
        throw new Exception('Password could not be changed.');
      else
        return true;  // changed successfully
    }
    //---------------------------------------------------------------------------
    // function to get random word

     

    Suggestions on how best to modify the encryption would be appreciated.

     

     

    Thanks for the help.

  8. Well is there a need to do something more than sha1?  Why do a md5 inside the sha1???!

     

    This site just has things like bylaws and meeting minutes and names/addresses.  What I am really wondering is whether there is a compelling reason to change the sha1 encryption I am using.  If it ain't broke....

  9. ::)

    Boy, that is way deeper than I can assimilate.  It is a membership area for a professional association.  So my old work was to use SHA1()  to encrypt and store the password. 

     

    Is that probably good enough or should I seriously be using something else?

     

    Looking for real world practice here...if it isn't broke then I would prefer to not mess with it.  ;)

     

  10. I am reworking some code from a password authentication I did a long long time ago.  The original code is using SHA1() function to encrypt the passwords for storage in the MySQL database.

     

    Is that still considered the way to go, or should I be using a different method for encrypting the little buggers?

     

    Thanks

  11. Thanks - I also posted a help ticket at the server site and got the following:

    PHP, Apache and MySQL was updated to the latest stable release (according to http://forums.xyzhosting.com/showthread.php?t=86495 topic) and some php extensions wasn't enabled automatically by cpanel.

     

    Please check all your sites and let us know if you find similar problems.

     

    Grrrr... glad it is sorted but wish I had found that out a couple hours earlier!

     

    Thanks for your help.

  12. I have had a nice stable little club directory up and running and suddenly one of the forms is no longer working.  Instead when it tries to connect to the database I am getting an error message that the Class 'mysqli' not found in /home/omgma/public_html/Directory/includes/db_fns.php5 on line 6

     

    That line in that file is where my database connection script is so somehow it is no longer connecting.  The db connection script is as follows:

    function db_connect()
    {
        
        $conn = new mysqli("localhost", "username", "password", "database");
        if (mysqli_connect_errno() > 0) 
      {
           $errmsg = "Failure - Could not connect to database with db_connect.<br />mysqli_connect_error message: ".mysqli_connect_error()."<br /><br />"; 
           throw (new Exception($errmsg));
         } 
         else
         {
    //    echo "Connection worked! <br>";
         return $conn;
         }	  
    } 

     

     

    Are there any changes to the mysqli class that might be an issue here? 

  13. I saw some code somewhere and can't remember now how you do it. But they had a text box in a form and they wanted to show the user the current value that they returned from a database and then give them an option to change it.

     

    They set a variable like $foo = "bar"

    and then somehow used php for the default value of the form box to get it to show the value "bar"

     

    How do you do that?

  14. I have let myself get rusty,  >:( and am now trying to go through a php project I did long ago.  I don't think my error messages are kicking in correctly.

     

    My server phpinfo can be viewed here: http://tinyurl.com/4cnkxe

     

    I am not sure what I need to do to change any of the settings but error reporting shows as follows:

    error_reporting 2039

     

    Is that going to display errors I might hit or do I need to change it somehow?

     

     

    Thanks!

     

  15. I have some code set up to mail out a reset password.  For testing mode I want to add a blind copy to myself but am not sure how to add that to the script.

     

    Here is the guts of the existing code:

     

       
    /*I connected successfully and an email address exists in the mysql database so now I fetch it.*/
    
    $row = $result->fetch_object();
          $email = $row->email;   /* Sets variable equal to the email */
    
          $from = "From: support@XYZ.com \r\n";
          $mesg = "Your password for the XYZ Member directory has been changed. \r\n"
      				."You can login to the membership directory at http://www.XYZ.com/Directory/index.php5 \r\n\r\n"
    				."Your username is: $username \r\n"
    				."Your new password is: $password\r\n\r\n"
                  ."You can either keep this password or change it to one you preferr the next time you log in. "
    		  ."To change it, once you log in click on the \"Change Password\" button.\r\n";
          
        /* so here is where I put the email together from the variables.  How can I hard code a blind copy into the if statement behind the $email variable? */
      
          if (mail($email, 'XYZ login information', $mesg, $from))    
      {		echo "Your new password has been e-mailed to you at $email.<br />";
    		echo "If you no longer have access to the $email e-mail account, please contact our webmaster at info@XYZ.com for assistance.<br />";
    
            	return true;      }

  16. So if I did that would I do something like:

     

    Create a csv table as newdata

     

    and then assuming my existing table is called olddata

     

    write an update script something like:

     

    Update olddata t1, newdata t2 set t1.first_name = t2.first_name where t1.user_id = t2.user_id

     

     

    Where can I find a reference to using the CSV as a table.  Maybe I should just create a new table, insert the new data including the assigned user_id and then do the update like above?

×
×
  • 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.