Второй оператор SQL не вставляет / не обновляет, но первый - PullRequest
2 голосов
/ 04 января 2012

Я пытаюсь выполнить два оператора SQL подряд.РЕДАКТИРОВАТЬ: только первые текстовые поля "коробки" сообщения правильно.Кажется, что 3 другие переменные, bubbleWrap, studentAddress1 и studentAddress2, все пустые.Оба оператора SQL работают в инструментальной среде mysql.

Текстовые поля для studentAddress1 и studentAddress 2 включены в ту же форму, что и поля и переключатели bubblewrap (true / false).Я могу включить форму, если хотите, но она довольно простая и простая.

AJAX:

$("#needEmptyBoxesForm").submit (function() {
    alert('click');
    boxes = $("#boxes").val();
    bubbleWrap = $("#bubbleWrap").val();
    studentAddress1 = $("#studentAddress1").val();
    studentAddress2 = $("#studentAddress2").val();

    $.post('needEmptyBoxesRequest.php', 'boxes=' + boxes + 'bubbleWrap=' + bubbleWrap + 'studentAddress1=' + studentAddress1 + 'studentAddress2=' + studentAddress2, function (response) {
    alert('post');
    $("#needEmptyBoxesRequestResults").html(response);
    alert (response);
    });
return false;
});

Страница обработки (php)

    else {
    $boxes = mysql_real_escape_string($_POST['boxes']);
    $bubbleWrap = mysql_real_escape_string($_POST['bubbleWrap']);
    $studentAddress1 = mysql_real_escape_string($_POST['studentAddress1']);
    $studentAddress2 = mysql_real_escape_string($_POST['studentAddress2']);

    $email = mysql_real_escape_string($_SESSION["email"]);
    $clientId = mysql_real_escape_string($_SESSION["clientId"]);

    $sql =  "INSERT INTO supplies (`clientId`, `boxesRequested`, `bubbleWrapRequested`)
                VALUES ('".$clientId."', '".$boxes."', '".$bubbleWrap."');";

    //set results to variables
    $result = mysql_query($sql);
    $row = mysql_fetch_array($result);
        //in case query fails
        if (!$result) { 
            die("Database query failed: " . mysql_error()); 
        }

    $sql2 =     "UPDATE `clients` SET `studentAddress1`= '".$studentAddress1."',`studentAddress2`= '".$studentAddress2."' WHERE clientId = '".$clientId."';";

    //set results to variables
    $result2 = mysql_query($sql2);
    $row2 = mysql_fetch_array($result2);
        //in case query fails
        if (!$result2) { 
            die("Database query failed: " . mysql_error()); 
        }


    }

Формакод:

echo
    '<form id = "needEmptyBoxesForm">
        <table class = "needEmptyBoxes1">
            <tr>
                <td>
                    <span class="buttonText">
                        Our free signature boxes are 24"x18"x16", and double-walled to protect your items.  How many boxes would you like delivered?
                    </span>
                </td>
            </tr>
            <tr>
                <td>
                    <input      type="text"
                                    class="boxRequestBlank"
                                    id="boxes"
                                    name="boxes">
                </td>
            </tr>
            <tr>
                <td>
                    <span class="buttonText">
                        Free tape will be delivered with the boxes.
                    </span>
                </td>
            </tr>
            <tr>
                <td>
                    <span class="buttonText">
                        Would you like to purchase bubble wrap for $5?
                    </span>
                </td>
            </tr>
            <tr>
                <td>
                    <input      type="radio"
                                    class="radioButton"
                                    name="bubbleWrap"
                                    value="1">
                        <span class="buttonText">
                            Yes
                        </span>
                    <input      type="radio"
                                    class="radioButton"
                                    name="bubbleWrap"
                                    value="0">
                        <span class="buttonText">
                            No
                        </span>
                </td>
                            </tr>
            <tr>
                <td>
                    <img        src="images/arrow.png"
                                    class="needEmptyBoxesFormForward1"
                                    id="needEmptyBoxesFormForward1">
                </td>
            </tr>
        </table>

        <table class = "needEmptyBoxes2">
            <tr>
                <td>
                    <span class="buttonText">
                        Please confirm  your address:
                    </span>
                </td>
            </tr>
            <tr>
                <td>';

                        $sql = "SELECT  A.studentAddress1, A.studentAddress2
                        FROM clients A
                        WHERE '".$_SESSION["email"]."' = A.studentEmail";

                include "databaseConnection.php";

                //Close connection 
                mysql_close($connection); 

                    echo
                    '<input
                                    type="text"
                                    class="needEmptyBoxesTextbox"
                                    name="studentAddress1"
                                    value="'.$row["studentAddress1"].'">
                    <input
                                    type="text"
                                    class="needEmptyBoxesTextbox"
                                    name="studentAddress2"
                                    value="'.$row["studentAddress2"].'">

                </td>
            </tr>
        </table>
  <input        type="submit"
                    src="images/arrow.png"
                    class="needEmptyBoxesFormForward2"
                    id="needEmptyBoxesFormForward2">
</form>';

Ответы [ 3 ]

1 голос
/ 04 января 2012

Хм ... я бы многое здесь сделал по-другому, и это могло бы изменить ситуацию.

Во-первых, по вашей команде .post() я рекомендую использовать JSON:

$.post('needEmptyBoxesRequest.php', 
    {'boxes': boxes, 'bubbleWrap': bubbleWrap, 
    'studentAddress1': studentAddress1, 'studentAddress2': studentAddress2}, 
    function (response) { ...

Во-вторых, по вашим запросам я бы вставил строки:

 $sql =  "INSERT INTO supplies (`clientId`, `boxesRequested`, `bubbleWrapRequested`)
            VALUES ('$clientId', '$boxes', '$bubbleWrap');";

Я не думаю, что данные вашей формы публикуются правильно.

UPDATE: Посмотрев на код вашей формы, я заметил, что вы восстанавливаете входные данные по идентификатору в вашем jQuery, но по имени в коде формы. Пожалуйста, добавьте id атрибуты к вашим входам и посмотрите, что произойдет.

1 голос
/ 04 января 2012

Сообщение Ajax неверно. Используйте JSON для сопоставления параметров.

$.post(
    'needEmptyBoxesRequest.php', 
    {
        'boxes': boxes,
        'bubbleWrap': bubbleWrap,
        'studentAddress1':studentAddress1,
        'studentAddress2': studentAddress2
    },
    function (response) {
        alert('post');
        $("#needEmptyBoxesRequestResults").html(response);
        alert (response);
    }
);

Также ставьте свои if (!$result) заявления сразу после mysql_query звоните . Как это

$result2 = mysql_query($sql2);
//in case query fails
if (!$result2) { 
    die("Database query failed: " . mysql_error()); 
}
$row2 = mysql_fetch_array($result2);
1 голос
/ 04 января 2012

Похоже, вам не хватает & в строке запроса, которую вы создали:

$.post('needEmptyBoxesRequest.php', 'boxes=' + boxes + '&bubbleWrap=' + bubbleWrap + '&studentAddress1=' + studentAddress1 + '&studentAddress2=' + studentAddress2,
//-----------------------------------------------------^^-----------------------------^^-------------------------------------^^
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...