簡體   English   中英

無法從表PDO PHP編輯記錄

[英]Unable to edit record from a table PDO PHP

我有一個記錄列表,每個人都可以編輯。 每當用戶單擊“編輯”時,就會出現一個輸入掩碼,需要在其中輸入新數據以替換舊數據。 我使用PDO處理數據庫連接,我堅信問題是我無法更新現有表

這是我以前的帖子驗證和數據添加到數據庫表的鏈接

第一個代碼段創建一個表單,用戶可以在其中輸入一些數據。

<?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>
$errors = $stmt->errorInfo();
    foreach ($errors as $error) {
        echo $error ,'<br />';
    }

您可以使用上面的代碼來查找錯誤

添加一些錯誤處理代碼。

您設置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;
}

我已經在Web服務器上重新創建了您的代碼,它似乎可以按您的預期工作- 我唯一更改的是mysql的登錄信息 我在您的表單中鍵入的任何內容都會更新id = 1的記錄,或者如果數據無效則生成錯誤消息。 顯然,我必須創建一個與您期望的模式匹配的數據庫,因此我只創建了除id外的所有字段作為VARCHAR(255)。

我有一些建議可以嘗試:

  1. 檢查您的數據庫用戶是否具有UPDATE權限集
  2. 檢查數據庫是否確實有id = 1的記錄(是否可行,您已刪除並替換了記錄,並且id被auto_increment更改了嗎?)

希望這可以幫助!

**編輯:與您交談后,請查看以下代碼,該代碼可以滿足您的要求(至少在我的服務器上):

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的記錄。 此更新的代碼將添加您缺少的位,以傳遞“當前正在編輯”記錄的ID。

進一步編輯 :根據您的要求,我已經更改了tages.php,以顯示您在頂部的查詢結果。 您已經為$ sth設置了當前值或初始化了它們的應有值,並且還具有!empty? 在那里-您所需要做的就是將兩者放在一起。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM