我无法使用php

时间:2015-04-23 16:17:35

标签: php jquery mysql html5 sql-insert

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

  

列数与第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;

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

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

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

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

其他一些说明:

您的代码似乎容易受到SQL注入攻击。 SQL文本中包含的潜在不安全值必须才能正确转义。更好的是,使用准备好的声明绑定占位符

不要使用已弃用的 mysql _ 界面;请改用 mysqli _ PDO

相关问题