Запросы PDO не работают - PullRequest
       2

Запросы PDO не работают

0 голосов
/ 10 марта 2011

Я часами просматривал один и тот же код, пытаясь выяснить, почему мои запросы не работают.Два, которые я перечислил ниже, это два, которые не работают.

$getRequestIdQuery = "SELECT request_id
    FROM request_table
    WHERE request_key = '$requestKey'
    AND sort_order = $so";

$getRequestId = $pdo->prepare($getRequestIdQuery);
$getRequestId->execute();
foreach($getRequestId as $idRow)
{
    $requestId = $idRow['request_id'];
}

// This will update the ready status of the request id returned above
$updateReadyStatusQuery = "UPDATE request_table
    SET request_ready = 1
    WHERE request_id = $requestId";
$updateReadyStatus = $pdo->prepare($updateReadyStatusQuery);
$updateReadyStatus->execute();

Вышеописанное выполняется всякий раз, когда копия файла возвращает true.Я уже уверен, что это работает, поскольку в приведенном выше журнале ошибок отсутствуют пропуски, которые отображаются при каждом запуске теста.Я также уверен, что рассматриваемый запрос работает, поскольку я успешно выполнил запрос (как он отображается в журнале ошибок) в phpmyadmin.Ниже приведен фрагмент кода, который работает корректно всего на несколько строк выше:

$checkForComposedQuery = "SELECT *
    FROM composed_files
    WHERE file_source_id = '$fsi'
    AND file_number = '$fn'";

$checkForComposed = $pdo->prepare($checkForComposedQuery);
$checkForComposed->execute();

Есть ли какие-либо подсказки относительно того, что может быть причиной того, что это не работает?Оба приведенных выше фрагмента кода встречаются в цикле foreach, если это помогает.

Заранее большое спасибо.

ОБНОВЛЕНИЕ:

Ниже приведен код, содержащий предложения, добавленные Чарльзом ниже.:

$gotCopied = copy($sourceHymnFile, $destHymnFile);

if ($gotCopied == true) {
    error_log("The file has been successfully copied.");

    $idRow;
    $getRequestIdQuery = "SELECT request_id
        FROM request_table
        WHERE request_key = ?
        AND sort_order = ?";
    $getRequestId = $pdo->prepare($getRequestIdQuery);
    $getRequestId->execute(array($requestKey, $so));
    error_log("this is the value of request key : ".$requestKey);
    // Displays correct $requestKey value
    error_log("This is the value of sort order : ".$so);
    // Displays correct $so value
    $idRow = $getRequestId->fetch(PDO::FETCH_ASSOC);
    $requestId = $idRow['request_id'];
    error_log("This is the value of the request id : ".$requestId);
    // No output in error log for $requestId above

    // This will update the ready status of the request id returned above
    $updateReadyStatusQuery = "UPDATE request_table
        SET ready = 1
        WHERE request_id = ?";
    error_log("This updates the status of the song request if the song is played : ".$updateReadyStatusQuery);
    $updateReadyStatus = $pdo->prepare($updateReadyStatusQuery);
    $updateReadyStatus->execute(array($requestId));
}

Следующие корректно выполняются для введенных констант:

    if ($gotCopied == true) {
    error_log("The file has been successfully copied.");

    $idRow;
    $getRequestIdQuery = "SELECT request_id
        FROM request_table
        WHERE request_key = ?
        AND sort_order = ?";
    $getRequestId = $pdo->prepare($getRequestIdQuery);
    $getRequestId->execute(array(5, 2));
    error_log("this is the value of request key : ".$requestKey);
    error_log("This is the value of sort order : ".$so);
    $idRow = $getRequestId->fetch(PDO::FETCH_ASSOC);
    $requestId = $idRow['request_id'];
    error_log("This is the value of the request id : ".$requestId);
    // No output in error log for $requestId above

    // This will update the ready status of the request id returned above
    $updateReadyStatusQuery = "UPDATE request_table
        SET ready = 1
        WHERE request_id = ?";
    error_log("This updates the status of the song request if the song is played : ".$updateReadyStatusQuery);
    $updateReadyStatus = $pdo->prepare($updateReadyStatusQuery);
    // This execute works correctly if a value is set for $requestId
    $updateReadyStatus->execute(array($requestId));
}

1 Ответ

2 голосов
/ 10 марта 2011

У вас есть две проблемы здесь.

Во-первых, заполнители и привязка.Ваш код здесь уязвим для внедрения SQL.PDO содержит инструмент, помогающий смягчить эту угрозу.

$getRequestIdQuery = "SELECT request_id
    FROM request_table
    WHERE request_key = ? -- new!
    AND sort_order = ?";

$getRequestId = $pdo->prepare($getRequestIdQuery);
$getRequestId->execute(array($requestKey, $so));

? в запросе являются заполнителями.Массив, переданный в execute, предоставляет список замен для любых заполнителей.Они автоматически экранируются и цитируются по мере необходимости.

Во-вторых, вы получаете результаты неправильно.Вам нужно вызвать fetch метод (или fetchAll метод ) в дескрипторе оператора.Например:

$idRow = $getRequestId->fetch(PDO::FETCH_ASSOC);
$requestId = $idRow['request_id'];

Обратите внимание, что здесь нет петли.Ваш предыдущий цикл ожидал нескольких результатов, но он перезаписывал одну и ту же переменную в каждом цикле.Похоже, вы ожидаете только одного результата, поэтому вам нужно беспокоиться только об одном результате.

Нам также следует обновить ваш другой запрос, чтобы использовать заполнители.

$updateReadyStatusQuery = "UPDATE request_table
    SET request_ready = 1
    WHERE request_id = ?";
$updateReadyStatus = $pdo->prepare($updateReadyStatusQuery);
$updateReadyStatus->execute(array($requestId));

...и твой третий ...

$checkForComposedQuery = "SELECT *
    FROM composed_files
    WHERE file_source_id = ?
    AND file_number = ?";

$checkForComposed = $pdo->prepare($checkForComposedQuery);
$checkForComposed->execute(array($fsi, $fn));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...