duanma8207 2019-05-21 12:34
浏览 110

如何在用户登录时将用户ID插入表中

I got MySQL Database with the tables users and pictures. Then I created a upload.php page where my logged in user can upload the pictures, that are later stored (id, name, path and user_fk) to the database. However, it shows me the error. Name and image input worked well but after I tried to insert users id, id didn't work well.

The error says :

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (pinterest.pictures, CONSTRAINT pictures_ibfk_1 FOREIGN KEY (user_fk) REFERENCES users (user_id)) in /Applications/MAMP/htdocs/pinterest/upload.php:23 Stack trace: #0 /Applications/MAMP/htdocs/pinterest/upload.php(23): PDOStatement->execute() #1 {main}Success

<?php
session_start();
require_once __DIR__.'/connect.php';
require_once 'top.php';
$sUserId = $_SESSION['txtUsername'];
?>
<div class="bigTitle"><h2>Welcome <?php echo $sUserId ?> here you can upload your pictures.</h2></div>

<?php
require_once __DIR__.'/connect.php';
if(isset($_POST['submit']))
{
    $sName = $_POST['name'];
    $img = $_FILES['image']['name'];
    $sUserId = $_SESSION['txtUsername'];

    try{
        $stmt = $db->prepare('INSERT INTO pictures VALUES (null, :sName, :sImage, :sUserId)');
        $stmt->bindValue(':sName', $sName);
        $stmt->bindValue(':sImage', $img);
        $stmt->bindValue(':sUserId', $sUserId);

        $stmt->execute();

    }catch (PDOEXception $ex){
        echo $ex;
    }
    move_uploaded_file($_FILES['image']['tmp_name'], "images/$img");
    echo 'Success';
}

?>

<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="text" name="name" placeholder="name">
<input type="file" name="image" placeholder="image upload">
<input type="submit" name="submit" value="Upload the picture">
</form>
?>

I'm curious if there is any problem with the session or with the tables in database.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
    • ¥20 软件测试决策法疑问求解答
    • ¥15 win11 23H2删除推荐的项目,支持注册表等
    • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
    • ¥15 qt6.6.3 基于百度云的语音识别 不会改
    • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
    • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
    • ¥15 lingo18勾选global solver求解使用的算法
    • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
    • ¥20 测距传感器数据手册i2c