php - 我无法使用 php 将数据输入数据库

标签 php jquery mysql html sql-insert

我尝试使用 PHP 将数据插入到 MySQL 表中,但是当我在 PHP 表单中按发送时,出现此错误:

Column count doesn't match value count at row 1

1) 我的 php 表单:

<form method="post" action="process_addstud.php">
  <table width="400" border="0" cellspacing="1" cellpadding="2" align="center">

<th colspan="2" align="left">Add Student</h2>

  <tr>
    <td width="100">First Name</td>
    <td>
      <input name="trigger1" type="text" id="trigger1">
    </td>
  </tr>

  <tr>
    <td width="100">Last Name</td>
    <td>
      <input name="reply2" type="text" id="reply2">
    </td>
  </tr>

  <td width="100"> </td>
  <td>
    <input name="save" type="submit" id="save" value="Add Student">
  </td>
  </tr>
  </table>
</form>

2)发送PHP:

<?php

//set up for mysql Connection
$dbhost = 'localhost';
$dbuser = 'DB_user';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
//test if the connection is established successfully then it will proceed in next process else it will throw an error message
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}

//we specify here the Database name we are using
mysql_select_db('DB_name');
$trigger1 = $_POST['trigger1'];
$reply2 = $_POST['reply2'];

//It wiil insert a row to our tblstudent`
$sql = "INSERT INTO `DB_name`.`replies` (`trigger`, `reply`) 
        VALUES (NULL, '{$trigger1}', '{$reply2}');";
//we are using mysql_query function. it returns a resource on true else False on error
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not enter data: ' . mysql_error());
}
?>
                    <script type="text/javascript">
                        alert("New Record is Added to the Database");
                        window.location = "addStudent.php";
                    </script>
                    <?php
//close of connection
mysql_close($conn);
?>

3)Mysql代码:这里我有“usercontrib”和“rid”,但我不想更改这两列。

CREATE TABLE IF NOT EXISTS `replies` (
  `trigger` text NOT NULL,
  `reply` text NOT NULL,
  `usercontrib` tinyint(4) NOT NULL DEFAULT '0',
  `rid` int(10) unsigned NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=316 DEFAULT CHARSET=utf8;

我该如何解决这个问题?

最佳答案

在 INSERT 语句中,值列表中有三个值,但只有两列接受这些值:

INSERT INTO DB_name.replies (`trigger`, `reply`) 
    VALUES (NULL, 'two', 'three')

在列列表中指定三列,或从值列表中删除其中一个值。

<小时/>

其他一些注意事项:

您的代码似乎容易受到 SQL 注入(inject)攻击。 SQL 文本中包含的潜在不安全值必须正确转义。更好的是,将准备好的语句绑定(bind)占位符结合使用。

不要使用已弃用的mysql_接口(interface);使用 mysqli_PDO 代替。

关于php - 我无法使用 php 将数据输入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29829102/

相关文章:

php - 如何在页面加载期间从 Symfony2 获取学说查询统计信息

php - popen 将错误重定向到文本文件

php - 关于迁移的 Laravel 问题

php - POST 的大小限制

javascript - 删除 html 类不会使用 jQuery removeClass 分离已删除的类功能

java - 从 MySQL 中检索部分数据的数据

javascript - 拖动时更改元素类

php - 提交之前从选择选项中发布或获取所选值(同一页面)

mysql - 多列困惑

php - 如何获取数据库字段+ mysql中的realesacpe值