简体   繁体   中英

MySQL / PHP ( Foreign key mistake? )

I got a problem ^^
My PHP-function doesn't want to save into my MySQL table,
but it saves it to my selected folder. (Connection works (tested), Inserting stuff into another table works too from this position.)
I think it has something to do with the foreign key, since when I execute as example this command

INSERT INTO TBilder (BildPfad, BildFreigabe, UserId)VALUES ('asd', 0, 10005);  

it works. It does everything as intended.

<div class="image_upload_div">
<form action= "#" class="dropzone"></form>
</div>

<?php
                    if (!empty($_FILES)) {
                        if (!is_dir($dir . "users") && !is_writable($dir. "users")) {
                            mkdir($dir . "users");
                        }
                        $temp = $_FILES['file']['tmp_name'];
                        $users = $dir . "users" . $ds;
                        $destination = $users . $_SESSION['userid'] . $ds;
                        $target = $destination . $_FILES['file']['name'];
                        if (!is_dir($destination) && !is_writable($destination)) {
                            mkdir($destination);
                        }

                        move_uploaded_file($temp, $target);

                        $stmt = $pdo->prepare("INSERT INTO TBilder (BildPfad, BildFreigabe, UserId) VALUES (:pfad, :freigabe, :user)");
                        $stmt->bindparam(":pfad", $target);
                        $stmt->bindparam(":freigabe", 0);
                        $stmt->bindparam(":user", $id);
                        $stmt->execute();

                    }

And my whole database:

DROP DATABASE SonderDB;
CREATE DATABASE SonderDB; 
use SonderDb;

DROP TABLE IF EXISTS TUsers;

CREATE TABLE IF NOT EXISTS TUsers (
  UserId INT AUTO_INCREMENT,
  UserName VARCHAR(255) NOT NULL,
  UserPassword VARCHAR(255) NOT NULL,
  PRIMARY KEY (UserId)) 
  AUTO_INCREMENT = 10000,
  ENGINE = InnoDB;



DROP TABLE IF EXISTS TBilder ;

CREATE TABLE IF NOT EXISTS TBilder (
  BildId INT AUTO_INCREMENT,
  BildPfad VARCHAR(255) NOT NULL,
  BildFreigabe INT,
  UserId INT,
  PRIMARY KEY (BildId),
  FOREIGN KEY (UserId) REFERENCES TUsers(UserId) ON UPDATE CASCADE)
  AUTO_INCREMENT = 10000
ENGINE = InnoDB;
  • Because BildFreigabe und UserId are defined as INT , they should be prepared as such (see getInputParameterDataType() in my code). I believe 80% that this was your problem.
  • I would also keep an eye on BildPfad , because it's defined as NOT NULL .
  • If I may, I would recommend the use of exception handling, especially on db operations.

I wrote more code, in order to give you a global view, if you wish. Good Luck.


<?php

try {
    $pdo = getConnection();

    $sql = 'INSERT INTO TBilder (BildPfad, BildFreigabe, UserId) VALUES (:pfad, :freigabe, :user)';
    $stmt = $pdo->prepare($sql);

    if (!$stmt) {
        throw new Exception('The SQL statement can not be prepared!');
    }

    // Bind parameters by checking their datta type too!
    $stmt->bindparam(":pfad", $target, getInputParameterDataType($target));
    $stmt->bindparam(":freigabe", $freigabe, getInputParameterDataType(0));
    $stmt->bindparam(":user", $user, getInputParameterDataType($user));

    //********************************************************************
    // Try with bindValue(), if it's not working with bindParam().
    // It should. I normally work with bindValue().
    //********************************************************************
    // $stmt->bindValue(':pfad', $target, getInputParameterDataType($target));
    // $stmt->bindValue(':freigabe', $freigabe, getInputParameterDataType(0));
    // $stmt->bindValue(':user', $user, getInputParameterDataType($user));
    //********************************************************************

    if (!$stmt->execute()) {
        throw new Exception('The PDO statement can not be executed!');
    }

    $inserted = $stmt->rowCount() > 0 ? TRUE : FALSE;

    echo $inserted ? 'Inserted successfully' : 'Not inserted!';
} catch (PDOException $pdoException) {
    echo '<pre>' . print_r($pdoException, true) . '</pre>';
    exit();
} catch (Exception $exception) {
    echo '<pre>' . print_r($exception, true) . '</pre>';
    exit();
}

function getConnection() {
    $conn = new PDO('mysql:host=localhost;port=36;dbname=[...]', '[...]', '[...]');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $conn->setAttribute(PDO::ATTR_PERSISTENT, true);
    return $conn;
}

function getInputParameterDataType($value) {
    $dataType = PDO::PARAM_STR;
    if (is_int($value)) {
        $dataType = PDO::PARAM_INT;
    } elseif (is_bool($value)) {
        $dataType = PDO::PARAM_BOOL;
    }
    return $dataType;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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