无法使用SQLi连接方法将数据插入SQL

时间:2014-10-18 07:29:40

标签: html mysql

使用SQLi连接方法连接到localhost中的SQL数据库,以下是我将数据插入SQL DB的代码

SQL表

create table `test`(
`id` int(4) NOT NULL auto_increment,
`first` varchar(255) NOT NULL default '',
`last` varchar(255) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 ;

表格处理

<?php
$db_username="sanoj";
$db_password="123456";
try {
#connection 
$conn = new PDO('mysql:host=localhost;dbname=localtest', $db_username, $db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$data = $conn->prepare('INSERT INTO test VALUES(:first)');
$data->bindParam(':first', $first);

$first = 'Huzoor Bux';
$data->execute();

#exception handiling
} catch(PDOException $e) {
echo $e->getMessage();
}
?>

形式

<FORM method="post" action="for.php">
        <input type="text" name="first" placeholder="first"><br>
        <input type="text" name="last" placeholder="last">
        <input type="submit">
</FORM>

错误

SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1

4 个答案:

答案 0 :(得分:1)

试试这个:

#connection 
$conn = new PDO('mysql:host=localhost;dbname=localtest', $db_username, $db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$data = $conn->prepare('INSERT INTO test (first, last) VALUES (:first, :last)');
$first = 'Huzoor Bux';
$last = 'Bux Huz';
$data->execute(array(':first' => $first, ':last' => $last));

#exception handiling

请注意您使用的是正确的PDO。 Using mysql_connect() is deprecated

答案 1 :(得分:0)

看起来您要将带有一个字段的行添加到包含两个(或更多)列的表中。 您可能需要更改SQL,例如&#34; INSERT INTO test(firstFieldName)VALUES(:first)&#34;。

答案 2 :(得分:0)

https://www.drupal.org/node/1279532

看一下这个链接,它将帮助你理清你的概率。

答案 3 :(得分:0)

尝试使用此方法,它将起作用

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");


$first=filter_input(INPUT_POST, 'first');
$last=filter_input(INPUT_POST, 'last');

$sql="INSERT INTO $tbl_name(first, last)VALUES('$first', '$last')";
$result=mysql_query($sql);
echo "$first <br>";
echo "$last";

mysql_close();
?>