简体   繁体   中英

Data from database don't show in my edit page

Everything's working fine now. I can now view and update my data from my database. Thank you for helping me out. I already updated the code below. Thank you :)

edit_news.php // this is where the contents from my database to show to be able to update

    <?php
        mysql_connect("localhost", "root");
        mysql_select_db("alumni");
        if(isset($_GET['edit_id']))
        {

        $sql = "SELECT * FROM news WHERE id=".$_GET['edit_id']; 
        $result = mysql_query($sql);
        $row = mysql_fetch_array($result);

?>
<form action="/admin/update_news.php" method="post">
<div>
<input type="hidden" name="id" value="<?php echo  $row['id'] ?>"/>
<input type="text" name="title" value="<?php echo $row['title']; ?> "/>
<input type="text" name="body" value="<?php echo $row['body']; ?>"/>

<input type="submit" name="update" value="Save Changes"/>
<input type="submit" name="cancel" value="Cancel"/>

</div>
</form>

<?php 
        }
        ?>

update_news.php // this is where the update function happens

    <?php 
    date_default_timezone_set('Asia/Manila');
    include_once('db.php');
    if(isset($_POST['update']))
    {
        $title = mysql_real_escape_string(htmlspecialchars($_POST['title']));
        $body = mysql_real_escape_string(htmlspecialchars($_POST['body']));

        $sql = ("UPDATE news SET title='$title', body='$body' WHERE id=".$_POST['id']) or die(mysql_error());

            if(mysql_query($sql))
            {
            echo "<script type='text/javascript'>alert('Changes saved!!');
                    window.location.assign('admin_profile.php');</script>";
            }
            else
            {
            echo "<script type='text/javascript'>alert('Error while updating data.');
                    window.location.assign('admin_profile.php');</script>";
            }
    }
            if (isset($_POST['cancel']))
            {
                header("Location: admin_profile.php");
            }
?>

// this is where the user click the edit link that will lead them to edit_news.php

<a href="/admin/edit_news.php?edit_id=<?php echo $row[0]; ?>">EDIT</a>

You will get id in edit_news.php by

 $id = $_GET['id']

Then using that id fetch data from Database using select query to variables $title and $body

$sql = "SELECT * FROM news WHERE id = $id";

Then populate form elements using values you got by issuing the query above using any of the mysql_fetch functions

Now you have removed input type hidden from form and used $_GET['id'] in update_news.php which again gone wrong.Add the field there again and use $_POST['id'] instead of $_GET['id'] in update_news.php

The rest looking fine now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM