Использование PHP для добавления числовых значений в две строки базы данных MySQL - PullRequest
0 голосов
/ 03 февраля 2012

У меня есть сайт, на котором вошедшие в систему пользователи могут накапливать баллы, которые они позже могут купить через корзину.На странице ниже представлена ​​функция администратора php, в которой администратор может выставлять баллы отдельному пользователю (пока одному пользователю).

С этим сценарием связаны три таблицы:

пользователи: содержит данные о пользователях

tally_point: хранит все транзакции с точками, как входящие, так и заказывающие

reward_points: хранит общее количество баллов, которые есть у пользователя

Сценарий извлекает сведения о пользователях через раскрывающееся меню и добавляет точки в таблицу баллов, но ....

        <?php # add-points-ind.php
        // This is the main page for the site.

        // Include the configuration file for error management and such.
        require_once ('./includes/config.inc.php');

        // Set the page title and include the HTML header.
        $page_title = 'Add Points to User';
        include ('includes/header_admin_user.html');

        // If no dealer_code variable exists, redirect the user.
        if (!isset($_SESSION['admin_int_id'])) {

           // Start defining the URL.
           $url = 'http://' . $_SERVER['HTTP_HOST']
            . dirname($_SERVER['PHP_SELF']);
           // Check for a trailing slash.
           if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
                $url = substr ($url, 0, -1); // Chop off the slash.
           }
           // Add the page.
           $url .= '/login.php'; 

        ob_end_clean(); // Delete the buffer.
        header("Location: $url"); 
        exit(); // Quit the script.
        }
        ?>

        <h1>Add Points to User</h1>
        <div id="maincontent_inner">
        <div id="maincontent_inner2">  

        <?php //add-points-ind.php
        // This page allows the admin to add points to an individual user

        require_once ('mydatabase.php'); // Connect to the database.

        if (isset($_POST['submitted'])) { // Check if the form has been submitted.

        // Check if points were submitted through the form.
        if (is_numeric($_POST['tally_points_in'])) {
        $p = (float) $_POST['tally_points_in'];
        } else {
        $p = FALSE;
        echo '<p><font color="red">Please enter the pointås!</font></p>';
        }

        // Validate the User has been selected
        if ($_POST['selected_user'] == 'new') {

        // If it's a new categories, add the categories to the database.
        $query = 'INSERT INTO tally_points (users_id) VALUES (';

        // Check for a last_name.
        if (!empty($_POST['users_id'])) {
        $query .= "'" . escape_data($_POST['users_id']) . "')";

        $result = mysql_query ($query); // Run the query.
        $a = mysql_insert_id(); // Get the categories ID.

        } else { // No last name value.
        $a = FALSE;
        echo '<p><font color="red">Please enter the Dealers name!</font></p>';
        }

        } elseif ( ($_POST['selected_user'] == 'existing') && ($_POST['existing'] > 0))
        { // Existing categories.
        $a = (int) $_POST['existing'];
        } else { // No categories selected.
        $a = FALSE;
        echo '<p><font color="red">Please select a registered Dealer!</font></p>';
        }

        if ($p && $a) { // If everything's OK.

        // Add the print to the database.
        $query = "INSERT INTO tally_point (users_id, tally_points_in, order_id, total, tally_points_entry_date) VALUES ('$a', '$p', '0', '0', NOW())"; 
        if ($result = mysql_query ($query)) 
        { 
        // Worked.
        echo '<p>The reward product has been added.</p><br /><a href="add-points-ind.php">Go back</a><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
        } else { 
        // If the query did not run OK.
        echo '<p><font color="red">Your submission could not be 
        processed due to a system error.</font></p>';
        }
        } else { // Failed a test.
        echo '<p><font color="red">Please click "back" and try again.</font></p>';
        }
        } else { // Display the form.

        ?>

        <form enctype="multipart/form-data" action="add-points-ind.php" method="post">

        <input type="hidden" name="MAX_FILE_SIZE" value="524288" />

        <fieldset>
        <legend>Add Points Individually:</legend>

        <p><b>Select User:</b></p>

        <p>
        <select name="existing"><option>Select One</option>
        <?php // Retrieve all the users details and add to the pull-down menu.
        $query = "SELECT users_id, users_sale_id, users_first_name, users_surname FROM users ORDER BY users_surname ASC";
        $result = @mysql_query ($query);
        while ($row = @mysql_fetch_array ($result, MYSQL_ASSOC)) {
        echo "<option value=\"{$row['users_id']}\">{$row['users_sale_id']}: {$row['users_first_name']} {$row['users_surname']} </option>\n";
        }
        @mysql_close($dbc); // Close the database connection.
        ?>

        </select></p>
        <span class="extras"><input type="radio" name="selected_user" value="existing" /> Please confirm this is the correct user</span>
        <p><b>Points:</b> <br />
        <input type="text" name="tally_points_in" size="10" maxlength="10" /></p>
        </fieldset>

        <div align="center"><input type="submit" name="submit" value="Submit" /></div>
        <input type="hidden"name="submitted" value="TRUE" />
        </form>

        <?php
        } // End of main conditional.
        ?>

        <br class="clearboth" />
        End text
        </div>

        <?php // Include the HTML footer file.
        include ('includes/footer_admin_user.html');
        ?> 

... У меня проблемы с получением новых баллов, добавленных к полю итоговых очков (reward_user_points) в таблице reward_points , у меня есть код ниже, но я не уверен, куда мне его положить, если у кого-нибудь есть предложения, пожалуйста, дайте мне знать.

    <?php
    $query = "SELECT reward_user_points FROM reward_points WHERE users_id = $a";
    $result = mysql_query($query);
    $row = mysql_fetch_array($result, MYSQL_ASSOC);
    $TotalPoints = $row['reward_user_points'];

    if (@mysql_affected_rows($dbc) == 1) { // Whohoo!

        $new_credit = $TotalPoints + $p;
        $query = "UPDATE reward_points SET reward_user_points ='$new_credit' WHERE users_id = $a";
        $result = @mysql_query($query); 
        }
    ?>

1 Ответ

0 голосов
/ 03 февраля 2012

Хорошо, я должен сказать, что я не очень хорошо понимаю, в чем ваша проблема. Вы говорите, что у вас возникают проблемы с добавлением новых очков в поле общего количества очков, но не могли бы вы быть более точным? Есть ли какие-либо сообщения об ошибках, возвращаемые php или mysql?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...