无法编辑表格中的记录PDO PHP

时间:2015-07-29 16:10:39

标签: php mysql pdo

我有一个记录列表,每个人都可以编辑。每当用户单击编辑时,就会出现输入掩码,其中需要输入新数据以替换旧数据。我使用 PDO 来处理数据库连接,我坚信问题是我无法更新现有表格

以下链接指向我的旧帖validation and data add to a db table

第一段代码创建了一个用户输入一些数据的表单。

<?php
error_reporting(-1);
ini_set('display_errors', 'On');
?>
<?php
$servername = "xxxx";
$username = "xxxx";
$password = "xxxxx";
$dbname = "xxxxx";

try {
    $dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
?>
<?php
if ($_GET['action'] == 'edit') {
    //retrieve the record's information 
   $sth = $dbh->prepare("
  SELECT nome, cognome, indirizzo, civico, citta, prov
  FROM   tagesroma
  WHERE  id = ?
");
$sth->execute(array($_GET['id']));
    } else {
    //set values to blank
    $nome = '';
    $cognome = '';
    $indirizzo = '';
    $civico = 0;
    $citta = '';
    $prov = '';
}
?>
<html>
    <head>
        <meta charset="UTF-8">
        <title><?php echo ucfirst($_GET['action']); ?> Tages</title>
        <style type="text/css">
        <!--
        #error { background-color: #600; border: 1px solid #FF0; color: #FFF;
         text-align: center; margin: 10px; padding: 10px; }
        -->
        </style>
    </head>
    <body>
        <?php
            if (isset($_GET['error']) && $_GET['error'] != '') {
                echo '<div id="error">' . $_GET['error'] . '</div>';
            }
        ?>
        <form action="commit.php?action=<?php echo $_GET['action']; ?>&type=tages"
           method="post" accept-charset="UTF-8">
            <table>
                <tr>
                    <td>Nome</td>
                    <td><input type="text" name= "nome" value="<?php echo !empty($_POST['nome']) ? $_POST['nome'] : ''; ?>"></td>
                </tr><tr>
                    <td>Cognome</td>
                    <td><input type="text" name= "cognome" value="<?php echo !empty($_POST['cognome']) ? $_POST['cognome'] : ''; ?>"></td>                  
                </tr><tr>
                    <td>Indirizzo</td>
                    <td><input type="text" name= "indirizzo" value="<?php echo !empty($_POST['indirizzo']) ? $_POST['indirizzo'] : ''; ?>"></td>
                </tr><tr>
                    <td>Civico</td>
                    <td><input type="text" name= "civico" value="<?php echo !empty($_POST['civico']) ? $_POST['civico'] : ''; ?>"></td>
                </tr><tr>
                    <td>Citta</td>
                    <td><input type="text" name= "citta" value="<?php echo !empty($_POST['citta']) ? $_POST['citta'] : ''; ?>"></td>
                </tr><tr>
                    <td>Prov</td>
                    <td><input type="text" name= "prov" value="<?php echo !empty($_POST['prov']) ? $_POST['prov'] : ''; ?>"></td>
                </tr><tr>
                    <td colspan="2" style="text-align: center;">
                    <?php
                        if ($_GET['action'] == 'edit') {
                            echo '<input type="hidden" value="' . $_GET['id'] . '" name="id" />'; 
                        }
                    ?>
                    <input type="submit" name="submit"
                    value="<?php echo ucfirst($_GET['action']); ?>" />
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>

代码的第二部分验证输入的数据,当且仅当一切正确时,新数据才会更新

<?php
error_reporting(-1);
ini_set('display_errors', 'On');
?>
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxxx";
$dbname = "xxxx";

try {
    $dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
    $sth = $dbh->prepare("use accessibilita");
?>
<?php
 switch ($_GET['action']) {    
case 'edit':
    switch ($_GET['type']) {
    case 'tages':
        $error = array();
        $nome = isset($_POST['nome']) ?
            trim($_POST['nome']) : '';
        if (empty($nome)) {
            $error[] = urlencode('Si prega di inserire un nome.');
        }
        $cognome = isset($_POST['cognome']) ?
            trim($_POST['cognome']) : '';
        if (empty($cognome)) {
            $error[] = urlencode('Si prega di inserire un cognome.');
        }
        $indirizzo = isset($_POST['indirizzo']) ?
            trim($_POST['indirizzo']) : '';
        if (empty($indirizzo)) {
            $error[] = urlencode('Si prega di inserire un indirizzo.');
        }
        $civico = isset($_POST['civico']) ?
            trim($_POST['civico']) : '';
        if (empty($civico)) {
            $error[] = urlencode('Si prega di inserire un numero civico.');
        }
        $citta = isset($_POST['citta']) ?
            trim($_POST['citta']) : '';
        if (empty($citta)) {
            $error[] = urlencode('Si prega di inserire una citta valida.');
        }
        $prov = isset($_POST['prov']) ?
            trim($_POST['prov']) : '';
        if (empty($prov)) {
            $error[] = urlencode('Si prega di inserire una provincia.');
        }
        if (empty($error)) {
          $stmt = $dbh->prepare("UPDATE tagesroma SET nome=?, cognome=?, indirizzo=?, civico=?, citta=?, prov=? WHERE id=1");
          $stmt->execute(array($nome, $cognome, $indirizzo, $civico, $citta, $prov));         
        } else {
          header('Location:tages.php?action=edit&id=' . $_GET['id'] .
              '&error=' . join($error, urlencode('<br/>')));
        }
        break;
    }
    break;
}
?>

<html>
 <head>
  <title>Commit</title>
  <meta charset="UTF-8">
 </head>
 <body>
  <p>Done!</p>
 </body>
</html>

3 个答案:

答案 0 :(得分:0)

$errors = $stmt->errorInfo();
    foreach ($errors as $error) {
        echo $error ,'<br />';
    }

您可以使用上面的代码来查找您获得的错误

答案 1 :(得分:0)

添加一些错误处理代码。

您设置了PDO :: ERRMODE_EXCEPTION,因此错误应该抛出异常。

下面

if (!empty($error)) {
    header('Location:tages.php?action=edit&id=' . $_GET['id'] . '&error=' . join($error, urlencode('<br/>')));
    exit;
}

try {
    $stmt = $dbh->prepare("UPDATE tagesroma SET nome=?, cognome=?, indirizzo=?, civico=?, citta=?, prov=? WHERE id=1");
    $stmt->execute(array($nome, $cognome, $indirizzo, $civico, $citta, $prov));         
}
catch ( PDOException $e ) {
    echo 'INSERT FAILED WITH: ' . $e->getMessage();
    exit;
}
catch( Exception $ex ) {
    echo 'Some other error ' . $ex->getMessage();
    exit;
}

答案 2 :(得分:0)

我已经在我的网络服务器上重新创建了你的代码,它似乎按你的意图工作 - 我唯一改变的是mysql的登录信息;我在表单中键入的内容会更新id = 1的记录,或者如果数据未经验证则会生成错误消息。显然我必须创建一个与你期望的模式匹配的数据库,所以我只创建除了id为VARCHAR(255)之外的所有字段。

我有几个建议要尝试:

  1. 检查您的数据库用户是否具有UPDATE权限集
  2. 检查数据库是否确实拥有id = 1的记录(您是否可以删除并替换记录,并且auto_increment更改了ID?)
  3. 希望这有帮助!

    **编辑:在与您通话后,请参阅以下代码,该代码可以满足您的需求(至少在我的服务器上):

    tages.php:

    <?php
    error_reporting(-1);
    ini_set('display_errors', 'On');
    ?>
    <?php
    $servername = "localhost";
    $username = "redacted";
    $password = "redacted";
    $dbname = "test";
    
    try {
        $dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        // set the PDO error mode to exception
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
    catch(PDOException $e)
        {
        echo "Connection failed: " . $e->getMessage();
        }
    ?>
    <?php
    if ($_GET['action'] == 'edit') {
        //retrieve the record's information 
       $sth = $dbh->prepare("
      SELECT nome, cognome, indirizzo, civico, citta, prov
      FROM   tagesroma
      WHERE  id = ?
    ");
    $sth->execute(array($_GET['id']));
        } else {
        //set values to blank
        $nome = '';
        $cognome = '';
        $indirizzo = '';
        $civico = 0;
        $citta = '';
        $prov = '';
    }
    ?>
    $thisrecord=$sth->fetch(PDO::FETCH_ASSOC);
    
    <html>
        <head>
            <meta charset="UTF-8">
            <title><?php echo ucfirst($_GET['action']); ?> Tages</title>
            <style type="text/css">
            <!--
            #error { background-color: #600; border: 1px solid #FF0; color: #FFF;
             text-align: center; margin: 10px; padding: 10px; }
            -->
            </style>
        </head>
        <body>
            <?php
                if (isset($_GET['error']) && $_GET['error'] != '') {
                    echo '<div id="error">' . $_GET['error'] . '</div>';
                }
            ?>
        <!-- NOTICE THE ADDITION TO THE END OF THE action= TO PASS THE ID ON TO YOUR SCRIPT -->
            <form action="commit.php?action=<?php echo $_GET['action']; ?>&type=tages&id=<?php echo $_GET["id"];?>"
               method="post" accept-charset="UTF-8">
                <table>
                    <tr>
                        <td>Nome</td>
                        <td><input type="text" name= "nome" value="<?php echo !empty($_POST['nome']) ? $_POST['nome'] : $thisrecord["nome"]; ?>"></td>
                    </tr><tr>
                        <td>Cognome</td>
                        <td><input type="text" name= "cognome" value="<?php echo !empty($_POST['cognome']) ? $_POST['cognome'] : $thisrecord["cognome"]; ?>"></td>                  
                    </tr><tr>
                        <td>Indirizzo</td>
                        <td><input type="text" name= "indirizzo" value="<?php echo !empty($_POST['indirizzo']) ? $_POST['indirizzo'] : $thisrecord["indirizzo"]; ?>"></td>
                    </tr><tr>
                        <td>Civico</td>
                        <td><input type="text" name= "civico" value="<?php echo !empty($_POST['civico']) ? $_POST['civico'] : $thisrecord["civico"]; ?>"></td>
                    </tr><tr>
                        <td>Citta</td>
                        <td><input type="text" name= "citta" value="<?php echo !empty($_POST['citta']) ? $_POST['citta'] : $thisrecord["citta"]; ?>"></td>
                    </tr><tr>
                        <td>Prov</td>
                        <td><input type="text" name= "prov" value="<?php echo !empty($_POST['prov']) ? $_POST['prov'] : $sth["prov"]; ?>"></td>
                    </tr><tr>
                        <td colspan="2" style="text-align: center;">
                        <?php
                            if ($_GET['action'] == 'edit') {
                                echo '<input type="hidden" value="' . $_GET['id'] . '" name="id" />'; 
                            }
                        ?>
                        <input type="submit" name="submit"
                        value="<?php echo ucfirst($_GET['action']); ?>" />
                        </td>
                    </tr>
                </table>
            </form>
        </body>
    </html>
    

    commit.php:

    <?php
    error_reporting(-1);
    ini_set('display_errors', 'On');
    ?>
    <?php
    $servername = "localhost";
    $username = "redacted";
    $password = "redacted";
    $dbname = "test";
    
    try {
        $dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        // set the PDO error mode to exception
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
    catch(PDOException $e)
        {
        echo "Connection failed: " . $e->getMessage();
        }
        $sth = $dbh->prepare("use accessibilita");
    ?>
    <?php
     switch ($_GET['action']) {    
    case 'edit':
        switch ($_GET['type']) {
        case 'tages':
            $error = array();
            $nome = isset($_POST['nome']) ?
                trim($_POST['nome']) : '';
            if (empty($nome)) {
                $error[] = urlencode('Si prega di inserire un nome.');
            }
            $cognome = isset($_POST['cognome']) ?
                trim($_POST['cognome']) : '';
            if (empty($cognome)) {
                $error[] = urlencode('Si prega di inserire un cognome.');
            }
            $indirizzo = isset($_POST['indirizzo']) ?
                trim($_POST['indirizzo']) : '';
            if (empty($indirizzo)) {
                $error[] = urlencode('Si prega di inserire un indirizzo.');
            }
            $civico = isset($_POST['civico']) ?
                trim($_POST['civico']) : '';
            if (empty($civico)) {
                $error[] = urlencode('Si prega di inserire un numero civico.');
            }
            $citta = isset($_POST['citta']) ?
                trim($_POST['citta']) : '';
            if (empty($citta)) {
                $error[] = urlencode('Si prega di inserire una citta valida.');
            }
            $prov = isset($_POST['prov']) ?
                trim($_POST['prov']) : '';
            if (empty($prov)) {
                $error[] = urlencode('Si prega di inserire una provincia.');
            }
            if (empty($error)) {
              $stmt = $dbh->prepare("UPDATE tagesroma SET nome=?, cognome=?, indirizzo=?, civico=?, citta=?, prov=? WHERE id=?"); // changed to WHERE id=?
              $stmt->execute(array($nome, $cognome, $indirizzo, $civico, $citta, $prov,$_GET["id"])); // added $_GET["id"] to the end        
            } else {
              header('Location:tages.php?action=edit&id=' . $_GET['id'] .
                  '&error=' . join($error, urlencode('<br/>')));
            }
            break;
        }
        break;
    }
    ?>
    
    <html>
     <head>
      <title>Commit</title>
      <meta charset="UTF-8">
     </head>
     <body>
      <p>Done!</p>
     </body>
    </html>
    

    花一点时间看一下这些变化 - 事实证明你的问题是它总是编辑id = 1的记录,无论你选择哪个记录进行编辑;这个更新的代码添加了您缺少的位来传递&#34;当前正在编辑的ID#34;记录。

    进一步修改:根据您的要求,我已更改了tages.php,以显示您在顶部的查询结果。你已经用$ sth设置当前值或初始化它们应该如何,你还有!空?那里 - 你需要做的就是把两者放在一起。