在PHP,MySQL中,如何使用HTML表单更新表中的行

时间:2013-11-16 12:41:24

标签: php mysql sql

我有2个PHP文件。第一个update.php包含更新行的用户表单。下一个,update_ac包含执行此更新的编码。问题是我得不到合适的输出

<?php
$host = "localhost"; // Host name 
$username = "root"; // Mysql username 
$password = ""; // Mysql password 
$db_name = "yumyum"; // Database name 
$tbl_name = "food"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");

// get value of id that sent from address bar
//$id=$_GET['id'];

$id = $_REQUEST['id'];

// Retrieve data from database 
$sql = "SELECT * FROM $tbl_name WHERE id='$id'";
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
?>

<table width="400" border="0" cellspacing="1" cellpadding="0">
    <tr>
    <form name="form1" method="post" action="update_ac.php">
        <td>
            <table width="100%" border="0" cellspacing="1" cellpadding="0">

                <tr>

                    <td align="center"><strong>name</strong></td>
                    <td align="center"><strong>price</strong></td>
                    <td align="center"><strong>Quantity</strong></td>

                </tr>

                <td align="center">
                    <input name="name" type="text" id="name" value="<? echo $line['name']; ?>">
                </td>

                <td align="center">
                    <input name="price" type="text" id="price" value="<? echo $line['price']; ?>" size="15">
                </td>

                <td align="center">
                    <input name="Quantity" type="text" id="Quantity" value="<? echo $line['Quantity']; ?>" size="15">
                </td>


                <td>
                    <input name="id" type="hidden" id="id" value="<? echo $line['id']; ?>">
                </td>
                <td align="center">
                    <input type="submit" name="Submit" value="Submit">
                </td>

                </tr>
            </table>
        </td>
    </form>
</tr>
</table>

<?php
// close connection 
mysql_close();
?>

**This is update_ac.php**
    <?php
    $host="localhost"; // Host name 
    $username="root"; // Mysql username 
    $password=""; // Mysql password 
    $db_name="yumyum"; // Database name 
    $tbl_name="food"; // Table name 

    // Connect to server and select database.
    mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
    mysql_select_db("$db_name")or die("cannot select DB");

    // update data in mysql database 
    $sql="UPDATE $tbl_name SET name='$name', price='$price', Quantity='$Quantity' WHERE id='$id'";
    $result=mysql_query($sql);

    // if successfully updated. 
    if($result){
    echo "Successful";
    echo "<BR>";
    echo "<a href='yumhome.php'>View result</a>";
    }

    else {
    echo "ERROR";
    }

    ?>

1 个答案:

答案 0 :(得分:0)

在第一时间 将变量$lines更改为$rows

然后在update_ac.php
使用$_POST[]获取所有价值;
因为格式method="post"