php - 在私有(private)类中执行sql语句的问题

标签 php mysql sql-server

下面的脚本处理表单数据。我有两个 sql 语句,一个在私有(private) php 类 CropAvatar 之外,将文本字段数据插入到 sql,另一个在 CropAvatar 类内的 sql 语句,将两个文件 URL 插入到 sql。 我希望第二个 sql 语句将文件 URL 输入到前一个 sql 语句插入的最后一行。 我目前正在通过

定义该 id
 $id = mysqli_insert_id();

但是,如果我将“WHERE id=$id”添加到第二个 sql 语句中,它不起作用,该语句看不到 id 的值。我相信这可能是因为第一个语句位于私有(private)类 CropAvatar 之外,而第二个语句位于该类内部。如何将 $id 传递到私有(private)类中才能使其工作?

    <?php
    $title = $_POST['title'];
    $address = $_POST['address'];
    $sale_price = $_POST['sale_price'];
    $lease_price = $_POST['lease_price'];
    $build_size = $_POST['build_size'];
    $lot_size = $_POST['lot_size'];
    $zoning = $_POST['zoning'];
    $comment = $_POST['comment'];
    $transaction = $_POST['transaction'];
    require('../dbcon.php');
    $sql="INSERT INTO listings (title, address, lot_size, zoning, build_size, sale_price, lease_price, comment,transaction, date_added) VALUES ('$title', '$address', '$lot_size', '$zoning', '$build_size', '$sale_price', '$lease_price', '$comment', '$transaction', now())";
    mysqli_query($con,$sql);
    $id = mysqli_insert_id();
        class CropAvatar {
            private $src;
            private $data;
            private $file;
            private $dst;
            private $type;
            private $extension;
            private $srcDir = '../0images/listimg/orig';
            private $dstDir = '../0images/listimg/mod';
            private $msg;

    function __construct($src, $data, $file, $insert_id) {
        $this -> setSrc($src);
        $this -> setInsertId($insert_id);
        $this -> setData($data);
        $this -> setFile($file);
        $this -> crop($this -> src, $this -> dst, $this -> data);
    }
            private $insert_id;

            public function setInsertId($insert_id) {
                     $this->insert_id = $insert_id;
    }
            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;
    $allowedExtsf = array("pdf");
    $tempf = explode(".", $_FILES["flyer"]["name"]);
    $extensionf = end($tempf);

    if (($_FILES["flyer"]["type"] == "application/pdf")
    && ($_FILES["flyer"]["type"] <2000000000)
    && in_array($extensionf, $allowedExtsf)) 
    {
        $flyername=$_FILES["flyer"]["name"];

        if ($_FILES["flyer"]["error"] > 0) 
        {
        echo "Return Code: " . $_FILES["flyer"]["error"] . "<br>";
        }   
            else 
            {
                if (file_exists("../flyers/" . $_FILES["flyer"]["name"])) 
                {
                 echo $_FILES["flyer"]["name"] . " already exists. ";
                }
                    else 
                    {
                    move_uploaded_file($_FILES["flyer"]["tmp_name"],"../flyers/" . $_FILES["flyer"]["name"]);
                     }
            }
          $ad_link="http://www.website.com/flyers/" . $_FILES["flyer"]["name"];
          require('../dbcon.php');
    $sql="UPDATE listings SET ad_link='$ad_link', listing_img='$listing_img' WHERE id=$this->insert_id";
    mysqli_query($con,$sql);
    mysqli_close($con);
    }


                            if ($result) {
                                $this -> src = $src;
                                $this -> type = $type;
                                $this -> extension = $extension;
                                $this -> setDst();


                            } else {
                                 $this -> msg = 'Failed to save file';
                            }
                        } else {
                            $this -> msg = 'Please upload image with the following types: 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;
            }
        }

    $crop = new CropAvatar($_POST['avatar_src'], $_POST['avatar_data'], $_FILES['avatar_file'], $id);
        $response = array(
            'state'  => 200,
            'message' => $crop -> getMsg(),
            'result' => $crop -> getResult()
        );

        echo json_encode($response);
    ?>

最佳答案

只需将其添加到 __construct 方法参数中即可:

function __construct($src, $data, $file, $insert_id) {
    $this -> setSrc($src);
    $this -> setInsertId($insert_id);
    $this -> setData($data);
    $this -> setFile($file);
    $this -> crop($this -> src, $this -> dst, $this -> data);
}

因此,您需要在创建 CropAvatar 对象时传递它:

$crop = new CropAvatar($_POST['avatar_src'], $_POST['avatar_data'], $_FILES['avatar_file'], $id);

您还需要在 CropAvatar 类中定义局部变量和 setter:

private $insert_id;

public function setInsertId($insert_id) {
    $this->insert_id = $insert_id;
}

然后您可以在任何需要的地方将其引用为 $this->insert_id

关于php - 在私有(private)类中执行sql语句的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26720743/

相关文章:

mysql - 如何创建一个 SQL 触发器来抓取传递到激活触发器的查询中的数据?

mysql - SQL 中的多个 IF 语句

sql - 获取在任何日期创建的表的列表?

sql-server - "XQuery [nodes()]: The XQuery syntax ' 联合 ' is not supported."

php - mysql 使用select 时出错?

javascript - 有人可以解释一下我的 JavaScript 函数中发生了什么吗?

mysql - 优化 MySQL 表以选择日期范围内的多行

php - 搜索一个<td>,并编辑另一个<td>的内容

php - Symfony 3 在 config.yml 中更改 asset_url 的目标

php - 将 MySQL 数据从旧 PHP 应用程序迁移到 Rails 应用程序