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条)

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录