Jump to content

help with an action tag!


WillUK

Recommended Posts

Hi

 

I am building a class to manage site users (Via a CMS).

 

In order to complete this I am building a delete/remove user function/method. Things are going ok (I think), but I am confused about what to put in the action tag of the form being used to process the data.

 

Before coding my method, I referred to a script that someone showed me which does something similar in functionality: it deletes photos previously uploaded to a folder, and also removes the associated information from the database.

 

I used this script as the framework for the code that I am working with.

 

Eveything seems to be working fine - EXCEPT - when I click on the 'delete users' button, nothing happens.

 

The first thing that I examined for error was the action attribute within my form.

The value of the action attribute is:

action = "<? php htmlentities($_SERVER["PHP_SELF"]) ?>"

 

This format has worked for previous forms.

 

I compared this to the action attribute within the script that I was using as a guide. It's value is set as follows:

 

action = "remove_photo.php?<?php echo "action='godel' ";?>

 

In this instance, remove_photo.php is the file that is being used to both process and display the form.

 

The reference script works perfectly but it uses a procedural approach .

 

For my application, I am using a more object oriented approach, so both my opening and closing form tag elements are stored in a seperate file to the class file that processes it. I am new to OO but relatively comfortable with the paradigm so far (my other methods etc are working fine).

 

I therefore suspect that the reason for my script's inability to process is due to the action attribute setting (I cannot be 100% sure of course!).

 

I am going to therefore apply the action attribute settings used successfully in the reference script, to the application that I am building.

 

However, the trouble is, I don't understand it  :(

 

I don't like it when something works, but I can't see the logic behind why it does. I am not concerned about the form id or method attrbutes. I understand what is going on there - and why they are set as they are.

However, the action attribute is very difficult to understand for the following reasons:

 

1/ There is no variable/method/entity/object/ANYTHING called 'godel' elsewhere in the reference script.

    For this reason I thought that it might not be needed, so removed the bit of code within PHP tags concerning it:

    <?php echo "action='godel' ";?>

 

    - When I did this - the script didn't work. In fact - nothing at all would process. This was a similar result to what was happening with the script I am building.

 

2/ I then put the PHP line back in, but replaced 'godel' with 'something'. I saved and processed the form.

  - it worked.

 

3/ I then tried it again replacing 'godel' with an empty string i.e: ' '.

  - it worked.

 

Has anyone come across forms being processed in a similar way before? If so, please could you explain what is happening here.  I can't find anything relating to this type of occurence online....

 

I am going to place the php tags in the file I am building, to see if it has the desired effect. If it does, I will obviously keep it. But not understanding what is happening, or why it is happening is very annoying!!

 

Thanks

 

 

 

 

 

 

 

 

 

 

 

Link to comment
Share on other sites

I've decided to post my code, because I'm having no luck with this :(

 

I have two files:

 

1/remove_user.php

  - this instantiates the class (userManagement) and calls the method (removeUsers). It also contains the html form opening and closing elements (the opening element is clean html. The closing element is contained within PHP tags).

2/userAuthorisationFunctions.php

  - this contains the class which contains the removeUsers method.

  - this class also contains the getUsers method, but this is not being used, and it is probably redundant.

 

The concept is as follows:

 

I am using a form to display user data within a CMS Administrator environment. I want the administrator to be able to remove users accordingly.

 

I am using checkboxes, whereby the administrator can select multiple users to delete if necessary.

 

I am using a while loop to store the SQL data pulled from the database.

 

In the first instance, the user data is displayed. This part of the method works fine and displays the data correctly.

 

A delete button has been added outside of the loop because I want the user to to be able to check multiple boxes, but only be required to action the delete call once to remove them (rather than deleting one user at a time, which would have been the case had I stored the delete button within the loop).

 

When I select a user, and click on delete, nothing happens. This leads me to believe that there is something wrong with the action attribute that I have set.

 

Here's the code, and thanks for any help you can give me.

 

remove_user.php

 

 
session_start();
$pageTitle = "Remove User";
include("../includes/admin_header.php");
include("../classes/userAuthorisationFunctions.php");
echo '<div class="admin_main_body">';
echo '<br /><br />';
$userManagement = new userManagement();

<form name="userList" action="

 htmlentities($_SERVER["PHP_SELF"]) 

" method="post">

 

$userManagement->removeUsers();
echo '<form>';
echo '<div>';
include("../includes/admin_footer.php");

 

 

userAuthorisationFunctions.php

 

class userManagement {
            function getUsers() {
    ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "root", "")) or die(((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
    ((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE practicesite")) or die (((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));

   $query = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM admin ORDER BY username ASC");
   while ($user = mysqli_fetch_assoc($query)) {
   echo '<table><tr><th colspan="1">Username</th><th colspan="1">Email Address</th></tr>';
   echo '<tr class="yellow"><td class="width">' . $user['username'] . '</td><td class="adjacent">' . $user['email'] . '</td></tr>';     
   echo '</table>';
        }
    }
            function removeUsers() {
    ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "root", "")) or die(((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
    ((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE practicesite")) or die (((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
    
    //if (isset($_POST['submit'])){
    if(!isset( $_REQUEST['action']) ) {
       $sql = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM admin ORDER BY username ASC");
       while ($user = mysqli_fetch_assoc($sql)) {
            echo '<table>';
            echo '<tr class="yellow"><td class="width">Username</td><td class="adjacent">Email Address</td><td class="adjacent"></td><td class="adjacent"></td></tr>';
        echo '<tr><td>' . $user['username'] . '</td><td class="adjacent">' . $user['email'] . '</td><td class="adjacent"><input type="checkbox" name=' . $user['username'] . '/></td></tr>';     
        echo '</table>';
                    }
        echo '<input type="submit" value="Delete Selected User(s)"/>';
        } else if(isset($_REQUEST['action']))
              {
        if (count($_POST) > 0 ) {
        $userDelcount = 0;
        foreach($_POST as $name => $value)
                {
        $query = "DELETE * FROM admin WHERE where username = '$name'";
        echo $query;
        $result = mysqli_query($GLOBALS["___mysqli_ston"], $query);                
        if ($result) {
        echo $result;
        $userDelcount ++;
                    }            
                }
                                }               
                else 
                   if (count($_POST) != $userDelCount )
                        {
                        echo "<p>There was a problem processing your request.Please try again later.</p>";              	 
                        } 
                            else 
                            {
                             echo "<p>The user(s) you selected has/have been deleted.</p>";              	    
                             unset($_REQUEST['action']);
                             echo "<p>Please <a href = '../admin170976/remove_user.php'>click here to continue.</p>";
              	        }
                 } else 
                 echo "<p>You did not select any users.</p>";
                      //"<p>Please <a href = '../admin170976/remove_user.php'>click here to return.</p>";
                }
    }

 

Thanks!  :confused:

 

Link to comment
Share on other sites

I've made a number of amendments to the scripts, so I've attached an updated version. When I click on delete, the form still fails to process....It must be something to do with the action attribute...????

 

remove_user.php

 

 
session_start();
$pageTitle = "Remove User";
include("../includes/admin_header.php");
include("../classes/userAuthorisationFunctions.php");
echo '<div class="admin_main_body">';
echo '<br /><br />';
$userManagement = new userManagement();

<form name="userList" action="<?php htmlentities($_SERVER["PHP_SELF"]) ?>" method="post">

$userManagement->removeUsers();
echo '<form>';
echo '<div>';
include("../includes/admin_footer.php");

 

userAuthorisation.php

 

class userManagement {
            function getUsers() {
    ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "root", "")) or die(((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
    ((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE practicesite")) or die (((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));

   $query = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM admin ORDER BY username ASC");
   while ($user = mysqli_fetch_assoc($query)) {
   echo '<table><tr><th colspan="1">Username</th><th colspan="1">Email Address</th></tr>';
   echo '<tr class="yellow"><td class="width">' . $user['username'] . '</td><td class="adjacent">' . $user['email'] . '</td></tr>';     
   echo '</table>';
        }
    }
    function removeUsers() {
    ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "root", "")) or die(((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
    ((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE practicesite")) or die (((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
    
    //if (isset($_POST['submit'])){
    if(!isset( $_REQUEST['action']) ) {
       $sql = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM admin ORDER BY username ASC");
       while ($user = mysqli_fetch_assoc($sql)) {
        echo '<table>';
        echo '<tr class="yellow"><td class="width">Username</td><td class="adjacent">Email Address</td><td class="adjacent"></td><td class="adjacent"></td></tr>';
        echo '<tr><td>' . $user['username'] . '</td><td class="adjacent">' . $user['email'] . '</td><td class="adjacent"><input type="checkbox" name=' . $user['username'] . '/></td></tr>';     
        echo '</table>';
            }
        echo '<input type="submit" value="Delete Selected User(s)"/>';
        } else if(isset($_REQUEST['action']))
              {
        if (count($_POST) > 0 ) {
        $userDelcount = 0;
        foreach($_POST as $name => $value)
                {
        $query = "DELETE * FROM admin WHERE where username = '$name'";
        //$result = mysqli_query($GLOBALS["___mysqli_ston"], $query);                
        if (@mysqli_query($GLOBALS["___mysqli_ston"], $query));
        //if ($result)
                    {
        $userDelcount ++;
                    }            
                }
                                }               
                else 
                   if (count($_POST) != $userDelCount )
                        {
                        echo "<p>There was a problem processing your request.Please try again later.</p>";              	 
                        } 
                            else 
                            {
                             echo "<p>The user(s) you selected has/have been deleted.</p>";              	    
                             unset($_REQUEST['action']);
                             echo "<p>Please <a href = '../admin170976/remove_user.php'>click here to continue.</p>";
              	        }
                 } else 
                 echo "<p>You did not select any users.</p>";
                      //"<p>Please <a href = '../admin170976/remove_user.php'>click here to return.</p>";
                }
    }

Link to comment
Share on other sites

php self simply tells the form to post data to the current page. You can, and should, leave the action attribute blank in these instances. Do not rely on php self:

 

action=""

 

same as

 

action = "<? php htmlentities($_SERVER["PHP_SELF"]) ?>"

 

Also, although this is on the verges of being OOP, it isn't true OOP. You need to create another object for managing your database connection instead of throwing it in your user object. The user object shouldn't need to initiate any db connection. You are using mysqli and running queries directly which isn't optimal in OOP. The whole point is to abstract and therefore make things more maintainable and extend-able. instead of mysqli_query, it should be: $yourDbObject->query(). Now, when you change the database adapter you don't have to find every single line of code where you used mysqli_query, you simply extend $yourDbObject and use that.

 

The user object would also likely extend an abstract class which manages table rows or 'models', those models then speak to the database.

 

if you take a look at some frameworks like Zend you will see how OOP should be done.

 

On your specific issue:

 

"the form still fails to process"

 

We need to know exactly what data is being inputted, and exactly 'how' it is failing - blank screen, error messages, do you know where the script is getting to? Using echos after certain things can help here. First validate the input is what you expect by printing it to screen and go from there. Echo something in every function, after every if or else. This is the lazy mans way to test driven development :D I do it all the time :S

Link to comment
Share on other sites

Thank you :)

I'll try to objectify the database connection using your tip! I am worried that if I run before I can walk, I'll end up making numerous mistakes and then not be able to rectify them. If I can get the script working, I can then re-examine the class and break it up accordingly. Although based on what you have said about creating a new function for the database connection, it looks reasonably simple to achieve.

 

I'll take a look at Zend and see what they offer. Although this is my first 6 weeks of OO PHP so I'll probably find it pretty difficult to figure out....

 

Ok - I'm trying to output the data using an echo statement at the following point:

 

if (count($_POST) > 0 ) {

        $userDelcount = 0;

        foreach($_POST as $name => $value)

                {

        echo $name;       

                }

  I also tried echo "$name"; (because the values should be strings)....

 

Nothing at all is happening however. So this would suggest that no form isn't communicating with the database correctly. Although clearlly the database is being recognised earlier on in the script, because it is outputting the users to screen in the table....

 

I'll have a another go by changing the action attribute to  action = "" .

 

I noticed that on the procedural script that I was using as a framework for this - the action attribute was set as follows: action="remove_user.php?<?php echo action="getdel" ?;>"  This may be irrelevent, yet the procedural script works fine. That's why I thought that the error that I am making could well be to do with the form action attribute that I am setting. Come to think of it - what does the line <?php echo action="getdel" ?> actually mean? 'getdel' isn't a variable (I've checked the script a few times to find a reference to it).....There is no reference to it elsewhere in the script.

Anyway - it is probably irrelevent! But has been baffling me. All I know is that with the procedural script, when I removed the action=godel code, the script failed to run....

 

I'll keep examining!

 

 

 

   

Link to comment
Share on other sites

no probs!

 

Yeh, it will be simple enough to separate the database with the model (user). ON running before you can walk - you have to be careful. You don't want to pick up bad habits and not even know it. What if, bare with me (;)), you are currently walking but you're doing a silly walk. Then, you learn to run, but because you walk silly, you run silly. So, my advice is to learn to walk properly, then when you do start running, you don't have to 'unlearn' how to walk silly.

 

/the most boring, drawn out analogy every :)

 

hehe

 

On your other problem, try to echo something further up the script. print out the entire $_POST array, make sure error reporting is on also. Basically, what you are trying to do is output as much info as you can about what your script is doing. This should definitely help you determine *where* it is tripping up.

 

changing action="" will not change anything. I was just pointing out that it is better than using php self.

 

Also, by separation and not trying to do too much with one 'thing' (this includes functions or 'methods' in OOP), you will often be able to see exactly what is going wrong and where.

 

For example, this class should be broke up into more functions. Personally, I would have a function for parsing the $_POST variables and retruning the users for deletion, like an array of userids. Then you will use your foreach to construct the sql query which will be contained in yet another function just for that.

 

Finally, you will want to separate your html from this class because it is operating as a 'model'. It's only concern should be to return and change data. That's it.

 

Few other pointers:

 

when constructing your sql query, do not do a new query for each userid. You can create a single query for multiple deletions. Running a sql query inside a loop is usually a big no-no. You are using unfiltered, unvalidated data in your sql. That $name needs to be validated. Simply using:

 

$name = mysql_real_escape_string($name);

$query = "DELETE * FROM admin WHERE where username = '$name'";

 

..will suffice.

 

The above query also has WHERE repeated.

 

..now, what if there was something else in one of your post variables - liek in every form the submit button is also in the $_POST array. That will now also be inserted into the sql.

 

The best practice for this would be to include something which tells you that particular $_POST variable is a user. Like naming it 'user-1', 'user-2' then you find all variables with 'user-' in them, and loop through those. Simple way of separating.

 

I'll stop there :S Hopefully that will help.

Link to comment
Share on other sites

Hey...

I'm back again...with the same problem 'dressed differently'.

I gave up with the previous effort, and went back to the drawing board. I attempted to put into place some of your advice about breaking down classes and functions into smaller modules/components, but I think that the main problem I am having is getting the functions in the same class to 'talk to each other' properly....

 

For example:  the sql data (users) is being pulled from the database and outputted to screen. So like before - this part of the application works fine. The function to carry out this work is called showUsers().

 

Instead of then putting the code to carry out the 'delete' process in the same function, I created a new one: removeUsers().

 

So - I then wanted to pass both the $_POST['delete'], and the $_POST['checkbox'] values to the removeUsers() function.  Both of these variables/attributes were set in showUsers().  $_POST['delete'] contains the delete button data for the form. $_POST['checkbox'] contains an array of data, populated by the check boxes.

 

However, this is where it breaks down.

 

Now, when I click on 'delete users', the user list remains in view, but no users are deleted.

At the bottom of the list I am getting the following output:

 

'Error: Form not processed'.

 

This was an error checking line that I added within the if isset() conditional I created to check for errors....One of the confusing/fascinating issues here is that php must be recognising that the delete button has been pressed because I contained the error check WITHIN the if isset() conditional...So it MUST have passed that condition...then it is running through the code and then it breaks up somewhere and decides not to work....

If the delete event hadn't taken place, the code would have outputted "The form could not be processed": the string which is the 'else' part of the isset() conditional.

 

Ok - so the problem is somewhere else in the removeUsers() function.

 

I then used var_dump($checkbox) to see whether checkbox contains any data. $checkbox is the variable that the value of $_POST['checkbox'] was passed to in the removeUsers() function.

 

Var dump gave me the following output when I checked 4 users for deletion:

 

array(4) { [0]=> string(4) ".18." [1]=> string(3) ".8." [2]=> string(4) ".24." [3]=> string(4) ".15." } Error: form not processed

 

The output is saying that 4 users were selected, with user_ids 18, 8, 24 and 15 respectively....

I don't understand what string(4), string(3), and string(4) means however...

The final part of the output is saying that the form was not processed, which is the internal error output for the if isset condition that I created.....

 

Ok - I haven't a clue what to do now. Clearly the values are being passed to the removeUser() function, but then they are not being passed to the SQL query for deletion.  I've retained the var_dump line in order to give the error message I received above more clarity - but clearly this should be discounted from the final code....

 

Any ideas??

 

Here's the code:

 

class userManagement {

       function removeUsers() {
            
                    //$userManagement->showUsers();

                    //if (showUsers()) {

                    ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "root", "")) or die(((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
                    ((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE practicesite")) or die (((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));

                    if(isset($_POST['delete'])) // from button name="delete"
                {
                    //echo $_POST['checkbox'];
                    $checkbox = $_POST['checkbox']; //from name="checkbox[]"
                    //echo $checkbox;
                    var_dump($checkbox);
                    $countCheck = count($_POST['checkbox']); 
                    //var_dump($countCheck);
                    for($i=0;$i<$countCheck;$i++)
                            {
                    $del_id  = $checkbox[$i];
                    $query = "DELETE FROM admin WHERE admin_id = $del_id";
                    $result = @mysqli_query($GLOBALS["___mysqli_ston"], $query);
                            }
		        if($result)
	                    {	
                    header('Location: admin_index.php');
		                }
		        else
		                {
                    echo "Error: form not processed";
		                }
                } else {
                    echo "The form could not be processed";
                    }
            
                }
    
    function showUsers() {
    
    
                    ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "root", "")) or die(((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
                    ((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE practicesite")) or die (((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
    
                    $query = "SELECT admin_id, username, email FROM admin";
                    //$result = @mysqli_query($GLOBALS["___mysqli_ston"], ($query)or die(mysqli_error($connection)));
                    $result = @mysqli_query($GLOBALS["___mysqli_ston"], $query);
                    //$result = $connection->query($query) or die(mysqli_error($connection));
                    if ($result) {
                    //create a new form and then put the results into a table.
                    echo "<table cellspacing='0' cellpadding='10'>";
                    echo "<tr><th colspan='4'>List of Current Users</th></tr>";
                    //echo "<tr><th width='25%'>Username</th><th width='25%'>Email Address</th><th width='25%'>Delete</th></tr>";
                    echo "<tr><th>Username</th><th>Email Address</th><th>Select Users</th></tr>";
                    while ($row = $result->fetch_object()) {
                    //$this->email = $row->email;
                    //$this->username = $row->username;
                    //$this->admin_id = $row->admin_id;
                    $email = $row->email;
                    $username = $row->username;
                    $id = $row->admin_id;
                    echo "<tr><td>".$username."</td><td>".$email."</td><td><input type='checkbox' name='checkbox[]' id='checkbox[]'  value='.$id.'/></td></tr>";
                                                            }
                    echo "</table>";
                    echo "<p><input id='delete' type='submit' class='button' name='delete' value='Delete Selected Users'/></p></form>";
                                } else {
                    echo "The user list could not be displayed due to a technical error. Please consult the administrator.";
                                        }
                        }
}
class database_connection {
public function connection() {
$db_name = "practicesite";		
$db_server = "localhost";	
$db_user = 'root';		
$db_pass = ''; 			
            }
//connection($db_server, $db_user, $db_pass, $db_name) or die(mysqli_error());
}
$connection = new database_connection($db_server, $db_user, $db_pass, $db_name) or die(mysqli_error());

 

As you can see, I'm in the process of modulating the SQL connection, by putting it in its own class. I initially tried to implement(instantiate) it in this script - but had a problem with calling an object on a non object (or something or other like that).

 

 

 

Link to comment
Share on other sites

Eureka!

I've done it! It was nothing to do with the logic. It was to do with where I was putting the quotation marks in the table!

The use of var_dump pinpointed the problem!! :)

 

Thus I changed the respective code in displayUsers() to:

 

$email = $row->email;
                    $username = $row->username;
                    $id = $row->admin_id;
                    echo "<tr><td>$username</td><td>$email</td><td><input type='checkbox' name='checkbox[]' id='checkbox[]' value=$id /></td></tr>";

 

Damn quotation marks. They are a the bane of my development life!

 

Now to look at the Zend Framework!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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