使用用户名php更新表

时间:2017-06-15 23:10:42

标签: php html pdo

我目前正致力于一个工作索赔系统,目前正努力让用户能够在我的工作表中索取一份可用的工作。

当替换更新按钮调用的更新查询的部分时,似乎是未从原始查询中正确传递给查询的order_id。

我对此非常陌生,所以任何其他评论或方向都会非常有用

<?php
  session_start();

  $servername = "localhost";
  $username = "username";
  $password = "password";
  $dbname = "dbname";


  echo "You are currently logged in as " . $_SESSION["login_user"] . ".<br>";

  echo "<table style='border: solid 1px black;'>";
  echo "<tr><th>Order ID</th><th>Status</th><th>Service</th><th>Document Type</th><th>Word Count</th><th>Other Considerations</th><th>Date Received</th><th>Claim</th></tr>";

  class TableRows extends RecursiveIteratorIterator { 
     function __construct($it) { 
        parent::__construct($it, self::LEAVES_ONLY); 
     }

    function current() {
        return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
    }

    function beginChildren() { 
        echo "<tr>"; 
    } 

    function endChildren() { 
        echo  '<td><form id="view_admin" method="post">
   <input type="submit" name="username" value="Accept"></td>';
         echo "</tr>" . "\n";
     } 
 } 

 try {
      $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $stmt = $conn->prepare("SELECT `Order_ID`,`Status`,`Service`,`Document_Type`,`Word_Count`,`Other_Considerations`,`Receive_Date`
      FROM `PRW_JOBS` where `staff_username` is null"); 
      $stmt->execute();

      // set the resulting array to associative
      $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 
      foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v)   { 
          echo $v;
      }
  }
  catch(PDOException $e) {
      echo "Error: " . $e->getMessage();
  }    

  echo "</table>";


  if($_POST && isset($_POST['username'])){


    $sql = "update `PRW_JOBS` set `staff_username` =  :staff_username  where `Order_ID`= :Order_ID and `staff_username` is NULL";
    $stm = $conn->prepare($sql);
    $stm->bindParam(':Order_ID', $result['Order_ID'], PDO::PARAM_INT); 
    $stm->bindParam(':staff_username', $_SESSION["login_user"], PDO::PARAM_STR); 
    $stm->execute();
  }
  $conn = null;

?>

1 个答案:

答案 0 :(得分:0)

您的问题出现是因为您以错误的方式使用setFetchMode()setFetchMode()返回一个布尔值(true或false),而不是$resultfetchAll()返回$result!所以,而不是使用这个:

$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

使用它:

$assigned = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll();

然后它会正常工作。

我建议您像这样使用它们:

$fetchedData = $selectStatement->fetchAll(PDO::FETCH_ASSOC);

我还建议你总是查看你正在使用的每个函数的php.net文档:参数列表,返回值,尤其是它抛出的错误/异常类型。因此:始终使用异常处理。就像你已经做的那样。但是,例如,PDO::prepare函数不仅可以抛出&#39; PDOexception&#39;,而且还可以返回false。还必须涵盖此案例。请参阅:PDO::prepare(&#34;返回值&#34;部分)。

我为您的问题代码准备了一个完整的php解决方案。我这样做是为了向您展示如何将HTML输出与php分开,并向您展示如何覆盖所有数据访问功能和异常处理。

有四个页面:主页面(index.php),包含表格行类的TableRows.php,用于数据访问的DataAccess.php和具有打印功能的Printer.php (一个或多个)。

我建议你总是在自己的php页面中保存一个类,该页面与类名同名。

我在这些文件中使用了函数。但是,您当然可以使用OOP,例如类。例如,用于处理所有数据库连接的Connection类,用于打印功能的Printer类等。

注意我如何放松&#34; html代码和整个PHP的处理在一个地方。你看到现在的HTML代码有多苗条?

请注意,我不会在页面上添加fetchAll()等功能。我在一个地方调用所有数据访问功能,我获取数据并使用此$fetchedData我可以在页面上执行我想要的操作。在代码中尽快关闭数据库连接是安全的。

Nota bene,用于开发,而非用于生产(!):如果您认为需要查看完整的详细异常而不是自定义异常消息,请更换以下内容:

printData($pdoException->getMessage());
printData($exception->getMessage());

用这些:

printData($pdoException);
printData($exception);
祝你好运!

Printer.php

<?php

/**
 * Print data on screen in a preformatted way.
 * 
 * @param mixed $data Data to print.
 * @return void
 */
function printData($data) {
    echo '<pre>' . print_r($data, true) . '</pre>';
}

DataAccess.php

<?php

/**
 * Create a new db connection.
 * 
 * @param string $dsn Connection DSN.
 * @param string $username Username.
 * @param string $password Password.
 * @param array $options [optional] Driver options.
 * @return PDO Db connection.
 */
function createConnection($dsn, $username, $password, $options = array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => false,
    PDO::ATTR_PERSISTENT => true,
)) {
    $connection = new PDO($dsn, $username, $password);
    foreach ($options as $key => $value) {
        $connection->setAttribute($key, $value);
    }
    return $connection;
}

/**
 * Close a db connection.
 * 
 * @param PDO $connection Db connection.
 * @return void
 */
function closeConnection($connection) {
    $connection = NULL;
}

/**
 * Get the data type of a binding value.
 * 
 * @param mixed $value Binding value.
 * @return mixed Data type of the binding value.
 */
function getInputParameterDataType($value) {
    $dataType = PDO::PARAM_STR;
    if (is_int($value)) {
        $dataType = PDO::PARAM_INT;
    } elseif (is_bool($value)) {
        $dataType = PDO::PARAM_BOOL;
    }
    return $dataType;
}

TableRows.php:

<?php

use RecursiveIteratorIterator;

/*
 * Table rows class.
 */

/**
 * Table rows class.
 *
 */
class TableRows extends RecursiveIteratorIterator {

    function __construct($iterator) {
        parent::__construct($iterator, self::LEAVES_ONLY);
    }

    function current() {
        return "<td style='width:150px;border:1px solid black;'>" . parent::current() . "</td>";
    }

    function beginChildren() {
        echo "<tr>";
    }

    function endChildren() {
        echo '<td>';
        echo '<form id="view_admin" method="post">';
        echo '<input type="submit" name="username" value="Accept">';
        echo '</td>';
        echo '</tr>' . '\n';
    }

}

的index.php:

<?php
include 'TableRows.php';
include 'DataAccess.php';
include 'Printer.php';

session_start();

$servername = 'localhost';
$dbname = 'dbname';
$username = 'username';
$password = 'password';

$loginUser = isset($_SESSION['login_user']) ? $_SESSION['login_user'] : '';

try {
    // Create db connection.
    $connection = createConnection('mysql:host=' . $servername . ';dbname=' . $dbname, $username, $password);

    // Define sql statement.
    $sql = 'SELECT 
                `Order_ID`,`Status`,`Service`,`Document_Type`,
                `Word_Count`,`Other_Considerations`,`Receive_Date`
            FROM `PRW_JOBS` 
            WHERE `staff_username` IS NULL';

    // Prepare and check sql statement (returns PDO statement).
    $selectStatement = $connection->prepare($sql);
    if (!$selectStatement) {
        throw new Exception('The SQL statement can not be prepared!');
    }

    // Execute and check PDO statement.
    if (!$selectStatement->execute()) {
        throw new Exception('The PDO statement can not be executed!');
    }

    // Fetch all data.
    $fetchedData = $selectStatement->fetchAll(PDO::FETCH_ASSOC);

    // Get rows collection.
    $tableRows = new TableRows(new RecursiveArrayIterator($fetchedData));

    // Upon form submission by 'Accept' button.
    if (isset($_POST['username'])) {
        // Define sql statement.
        $sql = 'UPDATE `PRW_JOBS` 
                SET `staff_username` = :staff_username 
                WHERE `Order_ID` = :Order_ID AND `staff_username` IS NULL';

        // Prepare and check sql statement (returns PDO statement).
        $updateStatement = $connection->prepare($sql);
        if (!$updateStatement) {
            throw new Exception('The SQL statement can not be prepared!');
        }

        // Bind values to sql statement parameters.
        $updateStatement->bindValue(':Order_ID', $fetchedData['Order_ID'], getInputParameterDataType($fetchedData['Order_ID']));
        $updateStatement->bindValue(':staff_username', $loginUser, getInputParameterDataType($loginUser));

        // Execute and check PDO statement.
        if (!$updateStatement->execute()) {
            throw new Exception('The PDO statement can not be executed!');
        }
    }

    closeConnection($connection);
} catch (PDOException $pdoException) {
    printData($pdoException->getMessage());
    exit();
} catch (Exception $exception) {
    printData($exception->getMessage());
    exit();
}
?>

<span>
    You are currently logged in as <?php echo $loginUser; ?>
</span>

<br>

<table style="border: solid 1px black;">
    <tr>
        <th>Order ID</th>
        <th>Status</th>
        <th>Service</th>
        <th>Document Type</th>
        <th>Word Count</th>
        <th>Other Considerations</th>
        <th>Date Received</th>
        <th>Claim</th>
    </tr>
    <?php
    foreach ($tableRows as $row) {
        echo $row;
    }
    ?>
</table>