Редактирование формы в MySQL и PHP - PullRequest
0 голосов
/ 17 марта 2012

Я работаю над проектом.Что мне нужно сделать, так это ввести некоторую информацию в форму, сохранить ее в базе данных, отобразить данные и затем отредактировать данные.До сих пор я могу делать все, кроме редактирования данных.Я пытался использовать $ _GET для получения идентификатора конкретной «ошибки», которую мне нужно отредактировать, и я могу это сделать и получить всю информацию, но я не уверен, как отредактировать этот конкретный идентификатор в моей базе данных,Вот мой обработчик: http://pastebin.com/mR6QWpJ7 и моя форма:

<form action="week10handle.php" method="POST">
        <fieldset width="300px">
            <legend width="300px"><b>Add a bug report</b></legend>
                Product Name:<br/><input type="text" name="product_name"><br/>
                Product Version: <br/><input type="text" name="product_version"><br/>
                Hardware Type: <br/><input type="text" name="hardware"><br/>
                Operating System: <br/><input type="text" name="os"><br/>
                Frequency: <br/><input type="text" name="frequency"><br/>
                Proposed Solutions: <br/><textarea name="solutions"></textarea><br/>
                <input type="submit" value="Submit">
        </fieldset>
</form>

Здесь я получаю данные для получения на странице редактирования формы, но на данный момент я не уверенКак отредактировать определенный идентификатор в базе данных.

    $getbug = htmlspecialchars($_GET["bugid"]);


    if (!empty($getbug)){
        $getbuginfo = mysql_query("SELECT * FROM `bugs` WHERE `id`= '$getbug'");
        if ($getbuginfo = mysql_fetch_assoc($getbuginfo)){
            $edit_product_name = $getbuginfo['product_name'];
            $edit_prod_version = $getbuginfo['product_version'];
            $edit_hardware = $getbuginfo['hardware_type'];
            $edit_os = $getbuginfo['os'];
            $edit_frequency = $getbuginfo['frequency'];
            $edit_solutions = $getbuginfo['solutions'];
            ?>
<form action="week10handle.php" method="POST">
        <fieldset width="300px">
            <legend width="300px"><b>Edit bug <?php echo $getbug;?></b></legend>
                Product Name:<br/><input type="edit" name="product_name" value="<?php echo $edit_product_name;?>"><br/>
                Product Version: <br/><input type="edit" name="product_version" value="<?php echo $edit_prod_version;?>"><br/>
                Hardware Type: <br/><input type="edit" name="hardware" value="<?php echo $edit_hardware;?>"><br/>
                Operating System: <br/><input type="edit" name="os"value="<?php echo $edit_os;?>"><br/>
                Frequency: <br/><input type="edit" name="frequency"value="<?php echo $edit_frequency;?>"><br/>
                Proposed Solutions: <br/><textarea name="solutions"><?php echo $edit_product_name;?></textarea><br/>
                <input type="submit" value="Submit">
        </fieldset>
</form>

РЕДАКТИРОВАТЬ: Вот мой код php обновления, но он все еще не работает, когда я отправляю свою форму, он обновляет страницу, но это не такt обновить базу данных:

<?php
if (mysql_connect('localhost','root','') && mysql_select_db('bug_reports')){

    $errors = array();

    if (isset($_POST['product_name'], $_POST['product_version'],$_POST['hardware'],$_POST['os'],$_POST['frequency'], $_POST['solutions'])){
        $product_name = mysql_real_escape_string(htmlentities($_POST['product_name']));
        $product_version = mysql_real_escape_string(htmlentities($_POST['product_version']));
        $hardware = mysql_real_escape_string(htmlentities($_POST['hardware']));
        $os = mysql_real_escape_string(htmlentities($_POST['os']));
        $frequency = mysql_real_escape_string(htmlentities($_POST['frequency']));
        $solutions = mysql_real_escape_string(htmlentities($_POST['solutions']));
        $getbug = mysql_real_escape_string(htmlentities($_POST['bugid']));
        if (empty($product_name) || empty($product_version) || empty($hardware) || empty($os) || empty($frequency) || empty($solutions)){
            $errors[] = 'All fields are required.';
        }

        if (!is_numeric($product_version) || !is_numeric($frequency)){
            $errors[] = 'Product version and frequency must both be numbers';
        }

        if (empty($errors)){
            $update = "UPDATE `bugs` SET `product_name` = '$product_name', `product_version = '$product_version', `hardware_type = '$hardware', `os` = '$os', `frequency` = '$frequency', `solutions` = '$solutions' WHERE `id` = $getbug";
            if ($update = mysql_query($update)){
                header('Location: week10handle.php');
            } else{
                $errors[] = 'Something went wrong, please try again.';
            }
        } else{
            foreach($errors as $error){
                echo '<p><strong>'.$error.'</strong></p>';
            }
        }

    }else{
    $getbug = htmlspecialchars($_GET["bugid"]);
    }



    if (!empty($getbug)){
        $getbuginfo = mysql_query("SELECT * FROM `bugs` WHERE `id`= '$getbug'");
        if ($getbuginfo = mysql_fetch_assoc($getbuginfo)){
            $bugid = $getbuginfo['id'];
            $edit_product_name = $getbuginfo['product_name'];
            $edit_prod_version = $getbuginfo['product_version'];
            $edit_hardware = $getbuginfo['hardware_type'];
            $edit_os = $getbuginfo['os'];
            $edit_frequency = $getbuginfo['frequency'];
            $edit_solutions = $getbuginfo['solutions'];
            ?>
    <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
        <fieldset width="300px">
            <legend width="300px"><b>Edit bug <?php echo $getbug;?></b></legend>
                Product Name:<br/><input type="edit" name="product_name" value="<?php echo $edit_product_name;?>"><br/>
                Product Version: <br/><input type="edit" name="product_version" value="<?php echo $edit_prod_version;?>"><br/>
                Hardware Type: <br/><input type="edit" name="hardware" value="<?php echo $edit_hardware;?>"><br/>
                Operating System: <br/><input type="edit" name="os"value="<?php echo $edit_os;?>"><br/>
                Frequency: <br/><input type="edit" name="frequency"value="<?php echo $edit_frequency;?>"><br/>
                Proposed Solutions: <br/><textarea name="solutions"><?php echo $edit_product_name;?></textarea><br/>
                <input type="hidden" name="bugid" value="<?php echo $bugid;?>" >
                <input type="submit" value="Update">
        </fieldset>
    </form>
<?
        }else{
            echo "something went wrong";
        }
    }else{
        echo "No bug found.";
    }

}else
    echo 'Could not connect at this time.';

?>

Ответы [ 2 ]

1 голос
/ 17 марта 2012

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

if (isset($_GET['id']) {

    // do update
    $sql = 'UPDATE `bugs` SET ... WHERE id = ' . intval($_GET['id']);

} else {

    // do insert
    $sql = 'INSERT INTO `bugs` VALUES ....';

}
0 голосов
/ 17 марта 2012
UPDATE `bugs` SET `product_name` = '...', `product_version` = '...', ... WHERE `id` = $bugid;

Где "..." будет заменено новыми значениями $ _POST-ed для каждого столбца

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...