【问题标题】:Using class variables in SQL statements with $this->var通过 $this->var 在 SQL 语句中使用类变量
【发布时间】:2015-02-11 14:59:22
【问题描述】:

以下脚本处理表单数据并将其保存到 sql 表中:文本字段和图像 url。图像也保存到服务器。我正在执行两个 PDO 连接。第一个(在脚本开头)上传所有文本字段。然后通过 $id=$conn->lastInsertId(); 检索该行第二个 PDO 连接(第 75 行)使用图像 url(变量 $listing_img)更新该行($this->id)

****此脚本运行完成并回显所有 json_encoded 响应数据。****

但是第二个 PDO 不起作用(第 77 行),变量 $listing_img 的值没有被输入。

我认为它不起作用,因为变量 'id' 在 SQL 语句中是不可见的 $this->id

<?php
//process pdf file upload
if (isset($_FILES["flyer"]["name"]))
    ;
{
    $allowedExtsf = array("pdf");
    $tempf = explode(".", $_FILES["flyer"]["name"]);
    $extensionf = end($tempf);
    if (($_FILES["flyer"]["type"] == "application/pdf") && ($_FILES["flyer"]["size"] < 524288000) && in_array($extensionf, $allowedExtsf)) {

        if (file_exists("../flyers/" . $_FILES["flyer"]["name"])) {
            //if file exists, delete the file on the server
            unlink("../flyers/" . $_FILES["flyer"]["name"]);
        }
        //move currrent pdf to the flyers folder
        move_uploaded_file($_FILES["flyer"]["tmp_name"], "../flyers/" . $_FILES["flyer"]["name"]);
        //Make url of pdf file
        $ad_link = "http://www.website.com/flyers/" . $_FILES["flyer"]["name"];

        //SQL statement 1, insert all form fields, file url and current date time
    } else {
        $ad_link = NULL;
    }
    require ('../dbcon2.php');
    //Connection 1
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn -> prepare("INSERT INTO listings (title, address, lot_size, zoning, build_size, sale_price, lease_price, comment, transaction, ad_link, date_added) VALUES (:title, :address, :lot_size, :zoning, :build_size, :sale_price, :lease_price, :comment, :transaction, :ad_link, now())");
    //Bind
    $stmt -> bindParam(':title', $_POST['title']);
    $stmt -> bindParam(':address', $_POST['address']);
    $stmt -> bindParam(':lot_size', $_POST['lot_size']);
    $stmt -> bindParam(':zoning', $_POST['zoning']);
    $stmt -> bindParam(':build_size', $_POST['build_size']);
    $stmt -> bindParam(':sale_price', $_POST['sale_price']);
    $stmt -> bindParam(':lease_price', $_POST['lease_price']);
    $stmt -> bindParam(':comment', $_POST['comment']);
    $stmt -> bindParam(':transaction', $_POST['transaction']);
    $stmt -> bindParam(':ad_link', $ad_link);
    $stmt -> execute();
    $id = $conn -> lastInsertId();
    $title = $_POST['title'];
    $address = $_POST['address'];
    $lot_size = $_POST['lot_size'];
    $zoning = $_POST['zoning'];
    $build_size = $_POST['build_size'];
    $sale_price = $_POST['sale_price'];
    $lease_price = $_POST['lease_price'];
    $comment = $_POST['comment'];
    $transaction = $_POST['transaction'];
    $conn = null;
}
//Create class
class CropAvatar {
    private $id;
    private $src;
    private $title;
    private $address;
    private $lot_size;
    private $zoning;
    private $build_size;
    private $sale_price;
    private $lease_price;
    private $comment;
    private $transaction;
    private $data;
    private $file;
    private $dst;
    private $type;
    private $extension;
    //location to save original image
    private $srcDir = '../0images/listimg/orig';
    //location to save cropped image
    private $dstDir = '../0images/listimg/mod';
    private $msg;
    //Add to consttruct
    function __construct($src, $data, $file, $id, $title, $address, $lot_size, $zoning, $build_size, $sale_price, $lease_price, $comment, $transaction) {
        $this -> setSrc($src);
        $this -> setData($data);
        $this -> setFile($file);
        $this -> setId($id);
        $this -> setTitle($title);
        $this -> setAddress($address);
        $this -> setLot_size($lot_size);
        $this -> setZoning($zoning);
        $this -> setBuild_size($build_size);
        $this -> setSale_price($sale_price);
        $this -> setLease_price($lease_price);
        $this -> setComment($comment);
        $this -> setTransaction($transaction);
        $this -> crop($this -> src, $this -> dst, $this -> data, $this -> id, $this -> title, $this -> address, $this -> lot_size, $this -> zoning, $this -> build_size, $this -> sale_price, $this -> lease_price, $this -> comment, $this -> transaction);
    }

    public function __get($id) {
        if (property_exists($this, $id)) {
            return $this -> $id;
        }
    }

    public function setId($id) {
        $this -> id = $id;
    }

    public function setTitle($title) {
        $this -> title = $title;
    }

    public function setAddress($address) {
        $this -> address = $address;
    }

    public function setLot_size($lot_size) {
        $this -> lot_size = $lot_size;
    }

    public function setZoning($zoning) {
        $this -> zoning = $zoning;
    }

    public function setBuild_size($build_size) {
        $this -> build_size = $build_size;
    }

    public function setSale_price($sale_price) {
        $this -> sale_price = $sale_price;
    }

    public function setLease_price($lease_price) {
        $this -> lease_price = $lease_price;
    }

    public function setComment($comment) {
        $this -> comment = $comment;
    }

    public function setTransaction($transaction) {
        $this -> transaction = $transaction;
    }

    //NNEED TO SET THE VARIABLES

    private function setSrc($src) {
        if (!empty($src)) {
            $type = exif_imagetype($src);
            if ($type) {
                $this -> src = $src;
                $this -> type = $type;
                $this -> extension = image_type_to_extension($type);
                $this -> setDst();
            }
        }
    }

    private function setData($data) {
        if (!empty($data)) {
            $this -> data = json_decode(stripslashes($data));
        }
    }

    private function setFile($file) {
        $errorCode = $file['error'];
        if ($errorCode === UPLOAD_ERR_OK) {
            $type = exif_imagetype($file['tmp_name']);
            if ($type) {
                $dir = $this -> srcDir;
                if (!file_exists($dir)) {
                    mkdir($dir, 0777);
                }
                $currdate = date('YmdHis');
                $extension = image_type_to_extension($type);
                $src = $dir . '/' . $currdate . $extension;
                if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_JPEG || $type == IMAGETYPE_PNG) {
                    if (file_exists($src)) {
                        unlink($src);
                    }
                    $result = move_uploaded_file($file['tmp_name'], $src);
                    $listing_img = "http://www.website.com/0images/listimg/mod/" . $currdate . $extension;
                    if ($result) {
                        //Connection 2 - Update sql row according to row id with the url of cropped image
                        require ('../dbcon2.php');
                        $conn2 = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
                        $conn2 -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                        $sql2 = "UPDATE listings SET listing_img=:listing_img WHERE id=:id";
                        $q = $conn2 -> prepare($sql2);
                        $q -> execute(array(':id' => $this -> id, ':listing_img' => $listing_img));
                        $this -> src = $src;
                        $this -> type = $type;
                        $this -> extension = $extension;
                        $this -> setDst();
                    } else {
                        $this -> msg = 'Failed to save image file';
                    }
                } else {
                    $this -> msg = 'Please upload image with the following types only: JPG, PNG, GIF';
                }
            } else {
                $this -> msg = 'Please upload image file';
            }
        } else {
            $this -> msg = $this -> codeToMessage($errorCode);
        }
    }

    private function setDst() {
        $dir = $this -> dstDir;
        if (!file_exists($dir)) {
            mkdir($dir, 0777);
        }
        $this -> dst = $dir . '/' . date('YmdHis') . $this -> extension;
    }

    private function crop($src, $dst, $data) {
        if (!empty($src) && !empty($dst) && !empty($data)) {
            switch ($this -> type) {
                case IMAGETYPE_GIF :
                    $src_img = imagecreatefromgif($src);
                    break;
                case IMAGETYPE_JPEG :
                    $src_img = imagecreatefromjpeg($src);
                    break;
                case IMAGETYPE_PNG :
                    $src_img = imagecreatefrompng($src);
                    break;
            }
            if (!$src_img) {
                $this -> msg = "Failed to read the image file";
                return;
            }
            $dst_img = imagecreatetruecolor(220, 220);
            $result = imagecopyresampled($dst_img, $src_img, 0, 0, $data -> x, $data -> y, 220, 220, $data -> width, $data -> height);
            if ($result) {
                switch ($this -> type) {
                    case IMAGETYPE_GIF :
                        $result = imagegif($dst_img, $dst);
                        break;
                    case IMAGETYPE_JPEG :
                        $result = imagejpeg($dst_img, $dst);
                        break;
                    case IMAGETYPE_PNG :
                        $result = imagepng($dst_img, $dst);
                        break;
                }

                if (!$result) {
                    $this -> msg = "Failed to save the cropped image file";
                }
            } else {
                $this -> msg = "Failed to crop the image file";
            }

            imagedestroy($src_img);
            imagedestroy($dst_img);
        }
    }

    private function codeToMessage($code) {
        switch ($code) {
            case UPLOAD_ERR_INI_SIZE :
                $message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                break;
            case UPLOAD_ERR_FORM_SIZE :
                $message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                break;
            case UPLOAD_ERR_PARTIAL :
                $message = 'The uploaded file was only partially uploaded';
                break;
            case UPLOAD_ERR_NO_FILE :
                $message = 'No file was uploaded';
                break;
            case UPLOAD_ERR_NO_TMP_DIR :
                $message = 'Missing a temporary folder';
                break;
            case UPLOAD_ERR_CANT_WRITE :
                $message = 'Failed to write file to disk';
                break;
            case UPLOAD_ERR_EXTENSION :
                $message = 'File upload stopped by extension';
                break;
            default :
                $message = 'Unknown upload error';
        }
        return $message;
    }

    public function getResult() {
        return !empty($this -> data) ? $this -> dst : $this -> src;
    }

    public function getMsg() {
        return $this -> msg;
    }

    public function getId() {
        return $this -> id;
    }

    public function getTitle() {
        return $this -> title;
    }

    public function getAddress() {
        return $this -> address;
    }

    public function getLot_size() {
        return $this -> lot_size;
    }

    public function getZoning() {
        return $this -> zoning;
    }

    public function getBuild_size() {
        return $this -> build_size;
    }

    public function getSale_price() {
        return $this -> sale_price;
    }

    public function getLease_price() {
        return $this -> lease_price;
    }

    public function getComment() {
        return $this -> comment;
    }

    public function getTransaction() {
        return $this -> transaction;
    }

}

$crop = new CropAvatar($_POST['avatar_src'], $_POST['avatar_data'], $_FILES['avatar_file'], $id, $title, $address, $lot_size, $zoning, $build_size, $sale_price, $lease_price, $comment, $transaction);
$response = array('state' => 200, 'message' => $crop -> getMsg(), 'result' => $crop -> getResult(), 'id' => $crop -> getId(), 'title' => $crop -> getTitle(), 'address' => $crop -> getAddress(), 'lot_size' => $crop -> getLot_size(), 'zoning' => $crop -> getZoning(), 'build_size' => $crop -> getBuild_size(), 'sale_price' => $crop -> getSale_price(), 'lease_price' => $crop -> getLease_price(), 'comment' => $crop -> getComment(), 'Transaction' => $crop -> getTransaction());

echo json_encode($response);
?>

关于如何执行第二条 SQL 语句的任何建议?

除了修复之外,我还试图理解为什么 $this->id 没有提取 id(如果这实际上是问题所在),而它在 JSON 中的回显效果很好?

【问题讨论】:

  • 您不能(直接)在类的实例中从类外部访问变量。这就是为什么函数能够传入参数的原因......
  • @developerwjk 我如何在其中获取 id?或者你有没有找到更好的地方来运行第二条 sql 语句?
  • 再看一遍,你将$id 传递给CropAvatar 的构造函数,所以你已经知道我上面所说的了。我只能说这段代码非常混乱。您应该改进缩进并在操作中间以外的某个地方定义类,并且可能使其更易于阅读会帮助您找到错误。此外,不要在类的外部和内部使用相同的变量名,因为这可能会让人感到困惑。比如可能给类成员加上前缀,比如$m_id 而不仅仅是$id。
  • 实际错误是servername等的db变量在类中不可见。无论如何,您不应该建立第二个 PDO 连接。你应该已经将$conn 传递给类并使用它。
  • 您可以像使用 dbcon2.php 一样包含带有 require 的类 至少您应该在开始对该页面的函数式编程之前定义它。

标签: php pdo this private


【解决方案1】:

您的问题在这里:

$sql2 = "UPDATE listings SET listing_img=$listing_img WHERE id=$this->id";
$q = $conn2->prepare($sql2); 
$q->execute($sql2); //Executing the sql string ????

从您的第一个查询中,我可以看出您知道如何准备,所以也这样做:

$sql2 = "UPDATE listings SET listing_img=:listing_img WHERE id=:id";
$q = $conn2->prepare($sql2); 
$q->execute(array(':id'=>$this->id, ':listing_img'=>$listing_img));

【讨论】:

  • 我喜欢这种方法,但我遇到了一些错误...致命错误:未捕获异常 'PDOException' 并带有消息 'SQLSTATE[42000]:语法错误或访问违规:1064 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在 /crop-avatar 的第 1 行的“//www.website.com/0images/listimg/mod/20141212211339.jpeg WHERE id=NULL”附近使用正确的语法.php:178 堆栈跟踪:似乎 $q->execute(array(':id'=>$this->id));返回一个空值?
  • @Rhillz 我现在忘记了你的一个参数检查
  • 在 '$listing_img' WHERE id=:id" 周围放回刻度;更正了语法问题,但 id 仍然为空,我很困惑
  • @Rhillz 是你需要的最后一个 insertid,为什么你在类的顶部有代码
  • @Rhillz 什么是$this -&gt; crop() 函数它没有在那个类中定义
【解决方案2】:

这是你的第一个问题:

$sql2 = "UPDATE listings SET listing_img=$listing_img WHERE id=$this->id";
                                         ^^^^^^^^^^^^

$listing_img是一个字符串,所以没有引号,你的sql语句会失败。

你为什么不像你在第一个 sql 语句中那样使用准备好的语句?这会解决你所有的问题。

另请注意,execute() 方法将带有要绑定参数的数组作为其第一个参数(如果您没有手动绑定变量)。您正在发送您的 sql 字符串,除了没有必要的事实之外,它也可能会导致错误。

顺便说一句,您还可以轻松共享您的 PDO 连接,这样您只需要一个。

【讨论】:

  • 如果我绑定 $q->bindParam(':id', $this->id);那么在sql中我应该在哪里id =“:id”,因为:id现在也是一个字符串?您是否有共享 PDO 连接的参考(当一个在课堂外,另一个在课堂内时)。非常感谢您的帮助
  • @Rhillz 不,看看你的第一个sql语句,绑定变量时不要在任何地方使用引号。您可以将 PDO 连接作为参数发送给例如您的构造函数并将其设置为类变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
  • 2016-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-12
相关资源
最近更新 更多