I have a login script which checks the value of a username and password against a database and proceeds to a secure page if the info is correct. I am trying to also set up a link based on the login info which will delete a record in another table (not the one containing the login info.). I think I am about there. I have the Query set-up. I just need help with setting up a link which actually does the deleting when you click it.

The code I have so far...

<?php
ini_set("display_errors","1");
ERROR_REPORTING(E_ALL);
function my_error_handler($errno, $errstr, $errfile, $errline, array $errcontext = array()) {
    die($errstr);
}
set_error_handler('my_error_handler');

session_start();
$con = mysql_connect("localhost", "uname", "pw") or trigger_error('Could not connect: ' . mysql_error());
mysql_select_db("nestle_exam", $con) or trigger_error(mysql_error());

class EmptyCredentialsException extends Exception {}
class InvalidCredentialsException extends Exception {}

// Same checking stuff all over again.
function clean($value, $db = null) {

$value = addslashes($value);
return $value;
}

function login($username, $password, $db = null) {
    if (empty($username) || empty($password)) {
        throw new EmptyCredentialsException();
    }

$username = clean($username, $db);
$pwid = clean($password, $db);

$pwid = intval($pwid);
$query = "SELECT name, username FROM TableName WHERE pwid = MD5('$pwid') AND username = '$username'";
$result = mysql_query($query, $db);
if ($result && mysql_num_rows($result)) {
    $user = mysql_fetch_assoc($result);
    user_update(array('login_timestamp' => time()), $username, $db);

    session_regenerate_id();

    $meta_data = array('ip' => $_SERVER['REMOTE_ADDR'], 'browser' => $_SEVER['HTTP_USER_AGENT']);
    session_store($user + $meta_data);
    return true;
}

throw new InvalidCredentialsException();
}

function user_update($data, $username, $db = null) {
    $query = 'UPDATE TableName SET ';
    $data = array_map('user_update_callback', $data, array_keys($data));
    $query = $query . implode(', ', $data);
    $query = "$query WHERE username = '$username'";
    $result = mysql_query($query, $db) or trigger_error(mysql_error());
    return $result && mysql_affected_rows($result);
}

function user_update_callback($value, $key) {
    return "$key = '{clean($value)}'";
}

function session_is_auth() {
    return (isset($_SESSION['ip']) && isset($_SESSION['browser'])) &&
           (($_SESSION['ip'] === $_SERVER['REMOTE_ADDR']) && ($_SESSION['browser'] === $_SERVER['HTTP_USER_AGENT']));
}

function session_store($data) {
    $_SESSION = array_merge($_SESSION, $user);
}

if (isset($_POST['submit'])) {
    try {
        login($_POST['username'], $_POST['pwid']);
    } catch (EmptyCredentialsException $e) {
        echo "<h2 class='fail'>Please fill in both your username and password to access your exam results.<br />",
             "<br >You will be redirected back to the login screen in five seconds.</h2>";
        echo "<meta http-equiv='refresh' content='5; url=StudentLogin.php'>";
        exit;
    } catch (InvalidCredentialsException $e) {
        echo "<h2 class='fail'>You have entered a username or password that does not match our database records.",
             " please try again.<br><br>You will be redirected back to the login screen in five seconds.</h2> ";
        echo "<meta http-equiv='refresh' content='5; url=StudentLogin.php'>";
        exit();
    }
}

// Start a session. If not logged in will be redirected back to login screen.
if (!session_is_auth()) {
    header("Location:StudentLogin.php");
    exit;
}

echo "<table id='header'><tr><td align='middle'><div id='welcome'><h3>Welcome! You are now logged in " . $_SESSION['name'] . "</h3></td></tr>";

echo "<tr><td><a class='logout' href='LogoutStudent.php'>Logout</a></td></tr></table>";

$user_id = $_GET['user_id'];
//DELETE QUERY TO SELECT RECORD TO DELETE BASED ON LOGIN INFO.
$query_delete = "DELETE FROM TableName WHERE user_id = $user_id AND TableName.user_id = $user_id";
//echo $query; //for debugging test
$result_delete = mysql_query($query_delete) or die(mysql_error());
?>

    doesn't your code work? If not highlight the code u suspect not working well.

      Actually, I get an error when I try and run this. The error is:

      mysql_query(): supplied argument is not a valid MySQL-Link resource
      

      not exactly sure where it is occurring.

        despite the fact that I have:

        ini_set("display_errors","1");
        ERROR_REPORTING(E_ALL);
        

        the line number where the error is occurring does not display.

          That's because you're not doing anything with $errline in your custom error handler:

          die($errstr); 

            I thought I could add $errline like this

            die($errstr,$errline); 
            

            but that doesn't work. How should I handle adding $errline?

              [man]die[/man] (a.k.a. [man]exit[/man]) takes only 1 parameter, not 2. Just add the line # into the string... something like:

              die("Line #$errline: $errstr");

              Or, comment out the set_error_handler() line and let PHP's internal error handler do what it does best.

                ok, I am getting an error here:

                $query = "SELECT name, username FROM roster_March2010 WHERE pwid = MD5('$pwid') AND username = '$username'";
                $result = mysql_query($query, $db);
                

                not sure why the error though. The SQL is correct.

                  Your problem is that when you call the function:

                  login($_POST['username'], $_POST['pwid']); 

                  you don't pass the database connection parameter. Thus, the function argument takes on the default value you specified (a.k.a. NULL).

                    thanks, so how would I do that if you don't mind posting?

                      Use $con as a third parameter when you call the login() function.

                        ok, great. I don't get the error anymore, but I still need to create the delete link within my html.

                        this part

                        $query_delete = "DELETE FROM log_March2010 WHERE user_id = $user_id AND roster_March2010.user_id = $user_id";
                        //echo $query; //for debugging test
                        $result_delete = mysql_query($query_delete) or die(mysql_error());
                        

                        doesn't seem to delete the record.

                          What's the link look like that gets you to that page? Are you including the user id in the URL?

                            the page before is simply a login page and the code is

                            <fieldset>
                            <legend>Please enter your username(email) and password to login to the results page.</legend>
                            
                            <form enctype="multipart/form-data" method="post" action="StudentResults.php">
                            
                            <label for="username">Username: </label><br />
                            <input type="text" name="username" id="username"><br />
                            <label for="password">Password : </label><br />
                            <input type="password" name="pwid" id="pwid"><br />
                            
                            <input class="submit" type="submit" name="submit" value="Log In" />
                            </form>
                            </fieldset>
                            

                            the URL for the login page is login.php

                              I guess I'm confused about what your question is then. Does the login functionality work? What are you trying to add?

                                login works fine. What I am trying to add is a button once they login successfully which when clicked will delete a record in a log table. The button will need to delete the log record associated with their login info. which pulls from a roster table. The two tables (roster and log) both share a common field user_id. The log record by the way isn't created from logging into this form, but is created from another login.

                                Let me know if I need to explain anything further.

                                  Since you're storing their user information in a session (and I'm assuming the user id is part of that information), simply create a regular link to a delete script that uses that user id to execute a DELETE query.

                                    well here is the delete script

                                    $user_id = $_GET['user_id'];
                                    //DELETE QUERY TO SELECT RECORD TO DELETE BASED ON LOGIN INFO.
                                    $query_delete = "DELETE FROM log_March2010 WHERE user_id = $user_id AND roster_March2010.user_id = $user_id";
                                    //echo $query; //for debugging test
                                    $result_delete = mysql_query($query_delete) or die(mysql_error());
                                    

                                    how would I create the link. Would it be best to use a form? Or can I just use <a href="script_for_delete">Delete me</a>

                                    this is the part I am trying to figure out.

                                      webguync;10949656 wrote:

                                      Or can I just use <a href="script_for_delete">Delete me</a>

                                      That's what I was suggesting. I wouldn't use a form (or the query string) to pass the user id, since both would allow the user to alter the id and start deleting other users' records. You already have the information in the session - just use [man]session_start/man in the delete script and grab the id from there.