我尝试使用mysqli
来在我的数据库中插入数据。但是不起作用。哪里可能是错误?
$myDb = new mysqli($hostname, $username, $password, $database);
if($myDb->connect_errno > 0){
die('Unable to connect to database [' . $myDb->connect_error . ']');
}
$statment = $myDb->prepare("INSERT INTO user(name,surname,age)
VALUES (?,?,?)");
$statement->bind_param('s', $_POST['name']);
$statement->bind_param('s', $_POST['surname']);
$statement->bind_param('i', 25);
$statement->execute();
$statement->free_result();
编辑:
我收到此错误:
Binding parameters failed: (0) Execute failed: (2031) No data supplied for parameters in prepared statement
答案 0 :(得分:2)
你在这里得到了错误:
$ statement-> bind_param(' i',25);
25不是变量。绑定参数时只能使用变量。绑定时,您不能使用常量,也不能使用固定的字符串或数字。
此外,绑定时分割参数对我来说从未奏效。我收到了一个错误。我需要这样做:
$myDb = new mysqli($hostname, $username, $password, $database);
if($myDb->connect_errno > 0){
die('Unable to connect to database [' . $myDb->connect_error . ']');
}
$statement = $myDb->prepare("INSERT INTO user (name,surname,age) VALUES (?,?,25)");
$statement->bind_param('ss', $_POST['name'], $_POST['surname']);
$statement->execute();
$statement->free_result();
$statement->close();
答案 1 :(得分:0)
我使用正确的参数绑定解决了问题。这里有正确的代码:
$myDb = new mysqli($hostname, $username, $password, $database);
if($myDb->connect_errno > 0){
die('Unable to connect to database [' . $myDb->connect_error . ']');
}
$statment = $myDb->prepare("INSERT INTO user(name,surname,age)
VALUES (?,?,?)");
$statement->bind_param('s', $name);
$statement->bind_param('s', $surname);
$statement->bind_param('i', $age);
$name = $_POST['name'];
$surname = $_POST['surname'];
$age = 25;
$statement->execute();
$statement->free_result();