Question

I am working on a PHP file that contains all my functions. I am currently sending the info through GET, then the file determines what action I am trying to do. Here is how my file is currently.

if ($action == 'creditBal')
{
    $user_id = $_GET['user_id'];
    $amt = $_GET['amt'];

    $mysql_query = "UPDATE Accounts SET BALANCE=BALANCE+$amt WHERE ID=$user_id";
    $result = mysql_query($mysql_query, $mysql_conn);

    if (!$result)
    {
        # die('MySQL Error: ' . mysql_error());

        $json_array = array(
            'response' => 'mysql_error'
        );

        return;
    }

    $json_array = array(
        'response' => 'success',
    );

    echo json_encode($json_array);

    mysql_close($mysql_conn);
}

The code above works great until I decide to change it up to the following.

function creditBal($user_id, $amt)
{
    $mysql_query = "UPDATE Accounts SET BALANCE=BALANCE+$amt WHERE ID=$user_id";
    $result = mysql_query($mysql_query, $mysql_conn);

    if (!$result)
    {
        # die('MySQL Error: ' . mysql_error());

        $json_array = array(
            'response' => 'mysql_error'
        );

        return;
    }

    $json_array = array(
        'response' => 'success',
    );

    return json_encode($json_array);

    mysql_close($mysql_conn);
}

if ($action == 'creditBal')
{
    $user_id = $_GET['user_id'];
    $amt = $_GET['amt'];

    echo creditBal($user_id, $amt);
}

I've tried checking for misspellings and everything, but it always doesn't work. Once I make it the if $action equals only, then it works. For some reason, the function doesn't work.

This has me really puzzled.

Was it helpful?

Solution

Two things:

  1. You don't have $mysql_conn available to your function. You can pass it as a parameter or use the global keyword to make it available in your function.

  2. When there is a MySQL error you don't actually return a response. You return nothing.

  3. As I mentioned in my comments, this code is insecure and vulnerable. Please fix that, too.

.

function creditBal($user_id, $amt, $mysql_conn)
{
    $mysql_query = "UPDATE Accounts SET BALANCE=BALANCE+$amt WHERE ID=$user_id";
    $result = mysql_query($mysql_query, $mysql_conn);

    if (!$result)
    {
        # die('MySQL Error: ' . mysql_error());

        $json_array = array(
            'response' => 'mysql_error'
        );
    }
    else {
        $json_array = array(
            'response' => 'success',
        );
    }
    mysql_close($mysql_conn);
    return json_encode($json_array);

}

if ($action == 'creditBal')
{
    $user_id = $_GET['user_id'];
    $amt = $_GET['amt'];

    echo creditBal($user_id, $amt, $mysql_conn);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top