dongsu0308
2017-08-11 11:08
浏览 216
已采纳

PHP PDO - 使用bindParam INSERT INTO不起作用

I stucked at this little piece of code:

$fruit_object = new fruit(1234, 'apple', 'red apple');    

try {
    $dbh = new PDO('mysql:host=localhost;charset=utf8;dbname=database', 'user', 'password');
    $exc = $dbh->prepare("INSERT INTO fruit( type, name) VALUES (:type, :name);");                               
    //$exc->bindParam(':id',   $fruit_object->id,   PDO::PARAM_INT);
    $exc->bindParam(':type', $fruit_object->type, PDO::PARAM_STR);
    $exc->bindParam(':name', $fruit_object->name, PDO::PARAM_STR);
    $exc->execute();
    $dbh = null;
    $exc = null;
} catch (PDOException $e) {
    //this function just do an echo with static content
    $this->error_database($e);
    $dbh = null;
    $exc = null;
    die();
}

I already used PDO for SELECTING things from my database, but with INSERTING something, it does not work. The user has the access to only INSERT stuff - i already tried that on my backend successfully.

So here is the error:

Fatal error: Uncaught Error: Cannot access private property fruit_object::$type

This is my fruit_object class:

<?php


class fruit
{
private $id;
private $type;
private $name;

function __construct($id, $type, $name)
{
    $this->id = $id;
    $this->type = $type;
    $this->name = $name;

}

function __toString()
{
    return $this->name;
}
}

For martin:

INSERT INTO fruit (id, type, name) VALUES (DEFAULT, 'apple', 'red apple');

My database is running on a MySQL server - is this the cause ? Do i have to work with questionmarks (?)?

Thank you, Louis

图片转代码服务由CSDN问答提供 功能建议

我坚持使用这段代码:

  $  fruit_object =新水果(1234,'苹果','红苹果');  
 
try {
 $ dbh = new PDO('mysql:host = localhost; charset = utf8; dbname = database','user','password'); 
 $ exc = $ dbh-&gt; prepare(  “INSERT INTO fruit(type,name)VALUES(:type,:name);”);  
 // $ exc-&gt; bindParam(':id',$ fruit_object-&gt; id,PDO :: PARAM_INT); 
 $ exc-&gt; bindParam(':type',$ fruit_object-&gt; type,  PDO :: PARAM_STR); 
 $ exc-&gt; bindParam(':name',$ fruit_object-&gt; name,PDO :: PARAM_STR); 
 $ exc-&gt; execute(); 
 $ dbh = null  ; 
 $ exc = null; 
} catch(PDOException $ e){
 //此函数只对静态内容执行回显
 $ this-&gt; error_database($ e); 
 $ dbh = null  ; 
 $ exc = null; 
 die(); 
} 
   
 
 

我已经使用PDO从我的数据库中选择东西,但是使用INSERTING东西, 这是行不通的。 用户只能访问INSERT东西 - 我已经在我的后端成功尝试了。

所以这是错误:

  致命错误:未捕获错误:无法访问私有属性fruit_object :: $ type 
   
 
 

这是我的fruit_object类:

 < 代码>&lt;?php 
 
 
class fruit 
 {
private $ id; 
private $ type; 
private $ name; 
 
_function__construct($ id,$ type,$ name)
 {\  n $ this-&gt; id = $ id; 
 $ this-&gt; type = $ type; 
 $ this-&gt; name = $ name; 
 
} 
 
_function__toString()
 {  
返回$ this-&gt; name; 
} 
} 
   
 
 

对于martin:

   INSERT INTO fruit(id,type,name)VALUES(DEFAULT,'apple','red apple'); 
   
 
 

我的数据库在MySQL服务器上运行 - 这是原因吗? 我是否必须使用问号(?)?

谢谢路易斯

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题