[英]Error when trying to insert with PHP / PDO / MySQL
Trying to make an insertion with two parameters and I'm getting this return:尝试使用两个参数进行插入,我得到了这个回报:
PDOStatement::bindValue() expects parameter 3 to be int, string given in. PDOStatement::bindValue() 期望参数 3 为 int,字符串中给出。
No meu banco tenho id(AUTO_INCREMENT), nome(VARCHAR) e Localizaçao (VARCHAR).没有 meu banco tenho id(AUTO_INCREMENT)、nome(VARCHAR) 和 Localizaçao (VARCHAR)。 My function to insert is this one我要插入的功能是这个
public function inserir() { //create
$query = 'insert into tb_usuarios(name,localizacao)values(:name,:location:)';
$stmt = $this->conexao->prepare($query);
$stmt->bindValue('$name','$location', $this->location->__get('name','location'));
$stmt->execute();
}
I already tried to put the Id in the insertion query and I didn't get any results, this code is from another project that I did the insertion of only one field, but all the other 3 fields in the table were Aut-increment我已经尝试将 Id 放入插入查询中,但没有得到任何结果,这段代码来自另一个项目,我只插入了一个字段,但表中的所有其他 3 个字段都是 Aut-increment
The PDO function bindValue()
accepts one parameter at a time. PDO 函数bindValue()
一次接受一个参数。 You can't bind all of them in one call.您不能在一次调用中绑定所有这些。
The code you were trying to write should look like this:您尝试编写的代码应如下所示:
public function inserir() { //create
$query = 'insert into tb_usuarios(name,localizacao)values(:name,:location:)';
$stmt = $this->conexao->prepare($query);
$stmt->bindValue('name',$this->location->__get('name'));
$stmt->bindValue('location',$this->location->__get('location'));
$stmt->execute();
}
You can also make an array of param name=>value pairs, and pass that array to execute()
which does the same thing as using bindValue()
for each param.您还可以创建一个参数 name=>value 对的数组,并将该数组传递给execute()
,这与对每个参数使用bindValue()
执行相同的操作。
public function inserir() { //create
$query = 'insert into tb_usuarios(name,localizacao)values(:name,:location:)';
$stmt = $this->conexao->prepare($query);
$params = [
'name'=>$this->location->__get('name'),
'location'=>$this->location->__get('location')
];
$stmt->execute($params);
}
Note another difference: For a placeholder like :name
you can use a param key ':name'
or 'name'
, but '$name'
will not work.注意另一个区别:对于像:name
这样的占位符,您可以使用参数键':name'
或'name'
,但'$name'
不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.