我正在使用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

最佳答案

尝试使用此方法将有效

// 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();
?>

10-07 19:05
查看更多