dongping1012 2015-04-04 17:54
浏览 27
已采纳

如何使用PHP向mySQL添加行?

I am trying to add an "admin" section of my website. Right now I am working on a section to add a new row to my MySQL database.

The first file is my admin.php:

<html>
...
<body>
<form action="add.php" method="post">
    <input type="text" name="order" />
    <input type="text" name="newstatus" />
    <input type="submit" value="Add" />

</form>

</body>
</html>

My goal here is to add 2 pieces of data (the table only has 2 columns right now) to the new row.

Then, I have my add.php file:

<?
//declare my connection variables - I'll move these to a secure method later
mysql_connect($servername, $username, $password) or die (mysql_error ());

// Select database
mysql_select_db($dbname) or die(mysql_error());

// The SQL statement is built

$sql="INSERT INTO $tblname(id, status)VALUES('$order', '$newstatus')";
$result=mysql_query($sql);

if($result){
    echo "Successful";
    echo "<BR>";
    echo "<a href='admin.php'>Back to main page</a>";
}

else {
    echo mysqli_errno($this->db_link);
}
?>

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

Anytime i input any data (non-duplicate of what is already in the table), it gives me an error. If I clear my table completely of all data, it will input once. I am getting a duplicate key error, but my key should be "orders", which is unique every time I input it.

Suggestions?

  • 写回答

2条回答 默认 最新

  • douci1677 2015-04-04 18:07
    关注

    If you are actually inserting a new row, you shouldn't fill the ID yourself but rather set it as AUTO_INCREMENT in your database. And then, have you form as such:

    <form action="add.php" method="post">
        <input type="text" name="newstatus" />
        <input type="submit" value="Add" />
    </form>
    

    And your PHP code like so:

    $newstatus = mysql_real_escape_string($_POST['newstatus']); // note the usage of $_POST variable
    $sql="INSERT INTO `$tbl_name` (`status`) VALUES ('$newstatus')";
    $result = mysql_query($sql) or die('Failed executing query: '.mysql_error());
    

    AUTO_INCREMENT can be set up in phpMyAdmin with the following query:

    ALTER TABLE `WorkOrders` MODIFY `id` INTEGER NOT NULL AUTO_INCREMENT;
    

    Finally, don't use mysql_* functions, they are deprecated.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?