Как правильно выполнить sql в скриптах с закрытыми классами

0

Отладка скрипта, обрабатывающего данные формы: несколько текстовых полей, две загрузки файлов (одна - изображение, а другая - документ). Скрипт работает с моим js файлом, чтобы изображение было обрезано перед загрузкой.

Я создал два sql-оператора в приведенном ниже скрипте, первый вставляет данные текстового поля в базу данных, затем извлекает уникальный и автоматически увеличиваемый номер строки ($ id), в который он был вставлен. Второй sql-оператор должен вставить URL-адрес изображения и документа в sql, в ту же строку, в которую был отправлен первый SQL-запрос.

Первый оператор sql работает, и файлы сохраняются на сервере в этом скрипте.

Второй sql-оператор не работает, и я думаю, потому что значение для $ id не передается извне класса CropAvatar.

Любые предложения о том, как получить второй оператор sql здесь для выполнения?

<?php
$title = $_POST['title'];
$titlee = mysql_real_escape_string($title);
$address = $_POST['address'];
$addresse = mysql_real_escape_string($address);
$sale_price = $_POST['sale_price'];
$sale_pricee = mysql_real_escape_string($sale_price);
require('../dbcon.php');
$sql="INSERT INTO listings (title, address, sale_price, date_added) VALUES ('$titlee', '$addresse', '$sale_pricee', 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, $id) {
    $this -> setSrc($src);
    $this -> setId($id);
    $this -> setData($data);
    $this -> setFile($file);
    $this -> crop($this -> src, $this -> dst, $this -> data);
}
        private $id;
        public function setId($id) {
                 $this->id = $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=$ID";
mysqli_query($con,$sql);
mysqli_close($con);
}
                        if ($result) {
                            $this -> src = $src;
                            $this -> type = $type;
                            $this -> extension = $extension;
                            $this -> setDst();
                        } 
                    }
                }
            } 
        }
        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) {
                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);
?>
Теги:
mysqli

1 ответ

3

Вы смешиваете библиотеки БД:

$sale_pricee = mysql_real_escape_string($sale_price);
                    ^----
mysqli_query($con,$sql);
     ^---

Библиотеки mysql (no "i") и mysqli (с "i") НЕ взаимозаменяемы, и вы не можете их смешивать/сопоставлять. Поскольку вы никогда не потрудились проверить, действительно ли ваши запросы действительно преуспели, вы просто ПРИНИМАЛИ, что ничто не может пойти не так. Плохое плохое предположение. ВСЕГДА предполагайте, что все будет терпеть неудачу, проверить, что это неудача, и рассматривать успех как приятный сюрприз.

Предполагая, что вы действительно хотите использовать версию "no-i", тогда всегда есть что-то вроде этого:

$result = mysql_query($sql) or die(mysql_error());
                           ^^^^^^^^^^^^^^^^^^^^^^

И обратите внимание, что mysql устарел. Вам больше не следует использовать его, и вместо этого следует использовать mysqli или PDO.

И вы STILL уязвимы для SQL-инъекций, напрямую используя параметр ['name'] $ _FILES в вашем запросе обновления.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню