简体   繁体   English

PHP PDO-使用bindParam插入INTO不起作用

[英]PHP PDO - INSERT INTO with bindParam does not work

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. 我已经使用PDO从数据库中选择内容,但是通过插入某些内容,它不起作用。 The user has the access to only INSERT stuff - i already tried that on my backend successfully. 用户只能访问INSERT内容-我已经在后端成功尝试了该操作。

So here is the error: 所以这是错误:

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

This is my fruit_object class: 这是我的fruit_object类:

<?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 ? 我的数据库在MySQL服务器上运行-这是原因吗? Do i have to work with questionmarks (?)? 我必须使用问号(?)吗?

Thank you, Louis 谢谢路易斯

You are missing closing brace for prepare and semi colon 您缺少准备和半冒号的右括号

$exc = $dbh->prepare("INSERT INTO fruit(id, type, name) VALUES (:id, :type, :name)");

if not working then add this line to check error 如果不起作用,则添加此行以检查错误

print_r($exc->errorInfo());

Answering Question 1: 回答问题1:

PHP PDO - INSERT INTO with bindParam does not work PHP PDO-使用bindParam插入INTO不起作用

If you're inserting an ID into an auto increment field and you've already inserted then it will cause a MySQL error (dupliate A_I field value) – Martin 如果您要在自动递增字段中插入ID并且已经插入,则将导致MySQL错误(A_I字段值重复)– Martin


Yeah i know that, I am using the DEFAULT keyword in my real statement. 是的,我知道,我在实际陈述中使用了DEFAULT关键字。 – louis12356 – louis12356


explain; 说明; default keyword for what? 默认关键字是什么? – Martin –马丁


There is a SQL keyword 'DEFAULT' which automaticly counts the ID up. 有一个SQL关键字“ DEFAULT”可以自动递增ID。 – louis12356 – louis12356


You should not be supplying a value for your Auto Increment ( id ) column. 应该提供您自动递增(值id )列。 What it looks like is that you're giving a MySQL Instruction via PDO variable which will Never Work . 看起来是通过PDO变量给出了MySQL指令 ,该指令 永远不会起作用 This is because PDO uses Prepared Statements and so variables are only ever going to be variables and can never be instructions . 这是因为PDO使用预处理语句 ,因此变量只会成为变量,而永远不会成为指令

The Default keyword in MySQL is an instruction to the MySQL program. MySQL中的Default关键字是对MySQL程序的指令。 This instruction will be ignored, not only because it is disallowed but also because you're passing a STRING value to PDO INSERT which claims it should be an INT : 该指令将被忽略,这不仅是因为不允许使用该指令,还因为您正在将STRING值传递给PDO INSERT,该值声称它应该是INT

 $exc->bindParam(':id',   $fruit_object->id,   PDO::PARAM_INT);

If $fruit_object->id == "DEFAULT" this is NOT AN INTEGER; 如果$fruit_object->id == "DEFAULT"则它不是整数; so therefore PDO will not run the query. 因此,PDO将不会运行查询。

Solution

Auto Increment values simply don't need to be inserted, ignore them: 自动增量值根本不需要插入,请忽略它们:

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;
}

Example of what you're trying to run: 您尝试运行的示例:

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

But due to the security constraints of PDO (ignoring the String / Int data type issue) what is actually being run is: 但是由于PDO的安全性限制(忽略String / Int数据类型问题),实际上正在运行的是:

INSERT INTO fruit (id, type, name) 
     VALUES ( <int var> "DEFAULT", <str var> "apple", <str var> "red apple"); 

So you're trying to insert the string variable "Default" into an integer column in MySQL 因此,您尝试将字符串变量“ Default”插入MySQL的整数列中


Answering Question 2: 回答问题2:

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

This is due to your class setting the value of this type to being Private rather than Public , which means the value can not be shown outside of the class (this is a slight over simplification but time is pressing me!) 这是由于您的班级将该类型的值设置为Private而不是Public ,这意味着该值不能在班级之外显示(这有点过分简化,但是时间紧迫我!)

What you need to do is either: 您需要做的是:

  • Set your values accessability to being public 将您的价值观设置为public
  • OR , build setter and getter methods into your class so you can whip out these private values as often as you want ( oh matron!! ). 或者 ,在您的类中构建settergetter方法,以便您可以根据需要频繁地提取这些私有值( 哦,马特龙! )。

So: 所以:

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

    /***
     * Getter
     ***/ 
    function getType()
    {
        return $this->type;
    }

    /***
     * Setter
     ***/
    function setType($value){
         $this->type = $value;
    }
}

Then in your PDO: 然后在您的PDO中:

$exc->bindParam(':type', $fruit_object->getType(), PDO::PARAM_STR);

This will output your value to the script. 这会将您的值输出到脚本。

If you want a much simpler approach you can simply replace private $name; 如果您想要一种更简单的方法,则只需替换private $name; with public $name; 具有public $name; and then the named variables value will be accessible from outside the class : 然后可以从类外部访问命名变量值:

 $exc->bindParam(':name', $fruit_object->name, PDO::PARAM_STR);

If you use (?) will be next code 如果您使用(?)将是下一个代码

$exc = $dbh->prepare("INSERT INTO fruit(id, type, name) VALUES (?, ?, ?)");                               
$exc->bindParam(1,   $fruit_object->id,   PDO::PARAM_INT);
$exc->bindParam(2, $fruit_object->type, PDO::PARAM_STR);
$exc->bindParam(3, $fruit_object->name, PDO::PARAM_STR);
$exc->execute();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM