为什么这不是更新信息

时间:2015-04-16 09:42:40

标签: php html mysql database

为什么此代码不是更新信息?

HTML表单:

<form>
<lable> ID# :</lable>
<input id= "ID" name= "ID" type= "text">

<p>
    <label>Select field to Edit</label>
    <select name="change">
    <option value=""></option>
    <option value="fname">First Name</option>
    <option value="lname">Last Name</option>
    <option value="email">Email</option>
    <option value="city">City</option>
    <option value="zip">Zip</option>
</select>
<lable> Enter the value to be replaced </label>
<input id = "replace" name = "replace" type = "text">
</p>

<input name="submit" type="submit" value="Submit">

用于更新数据库信息的PHP代码:

  <?php
    $servername = "localhost";
    $username = "root";
    $password = "root";

    $conn = mysql_connect($servername,$username,$password);
    if(!$conn)
    { 
      die('Error!' . mysqli_error()); 
    }
    $sql = 'SELECT * FROM users';
    mysql_select_db('mitsdatabase');

    $retval = mysql_query($sql, $conn);

    if(! $retval) 
    {
      die('Could not get data:' . mysql_error());
    }

    echo "<table width='300' cellpadding='5' border='1'>";
    echo "<tr> <td>ID#</td> <td>FirstName</td> <td>LastName</td> <td> Email </td> <td> City </td> <td> State </td> <td> Zip </td> </tr>";



    while($row = mysql_fetch_array($retval,MYSQL_ASSOC))
    {

      echo "<tr> <td>{$row['ID']}</td> . <td>{$row['fname']}</td> . <td>{$row['lname']}</td> . <td>{$row['email']}</td> . <td>{$row['city']}</td> . <td>{$row['state']} </td>. <td>{$row['zip']}</td>";
     }
    echo "</table>";
    $db_id = $_POST['ID'];
    $db_select = $_POST['change'];
    $db_replace= $_POST['replace'];

    echo " Do you want to edit any entry?";

    if(!_POST['submit'])
    {
        echo " ";
    }
    else{
        mysqli_query("UPDATE users SET db_select='$db_replace' WHERE ID = $db_id ");
    }
    mysql_close($conn);
  ?>

我想更新从选择字段中选择的信息,但不知何故它没有做任何事情。有人可以帮我解决这段代码的错误。

2 个答案:

答案 0 :(得分:2)

您的PHP与HTML在同一页面上吗?如果没有,您不会在HTML中的<form>元素中指向您的PHP代码。

例如,如果您的PHP文件名为“myphpcode.php”(并且与HTML代码位于同一文件夹中),那么您可以使用以下命令直接指向它:

<form method="post" action="myphpcode.php">

答案 1 :(得分:0)

如果您想要发布到同一页面,只需将<form>更改为<form method="post" action="#">,然后像$nameofvar = $_POST['nameofinputfield']一样在php中获取变量。每个输入字段都应具有名称标签。 还尝试将你的mysql连接改为:

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";

完成查询后

$conn->close();

和要插入的查询

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

您可以修改此$ sql字符串以更新或删除