我尝试使用 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/