首页 > 解决方案 > `mysqli_insert_id` PHP 类

问题描述

我正在创建一个社交网站,我让人们可以选择上传一个或多个帖子。那部分工作正常。

我的问题是,如果有人上传没有图片的帖子,那么它会被提交给一个函数,一切都很好。但是,如果有人提交带有图片的帖子,唯一的问题是,我无法获得id帖子的内容,因此我可以将其放在图像的列之一中。

我知道问题是什么。当我尝试使用程序编程来上传帖子和图像时,我得到了 id,一切都很好。但是当我使用 OOP 上传帖子然后尝试获取 id 时它不起作用。没有错误或列中的值刚刚出现的任何内容0。有人能帮助我吗 ?

$post = new Post($con, $userLoggedIn);

$title = trim(strip_tags(filter_var($_POST['title_post'], FILTER_SANITIZE_STRING )));
$body = trim(strip_tags(filter_var($_POST['post_text'], FILTER_SANITIZE_STRING )));
$post->submitPost($title, $body, 'none', $imageName);

if (!$errors) {

        $id = mysqli_insert_id($con);

        $stmt = $con->prepare("INSERT INTO post_images (image, post_id) VALUES (?, ?)");
        $stmt->bind_param('si', $file_path, $id);

        // Loop through each file
        for( $i=0; $i < $file_count; $i++ ) {

            $file_name = $_FILES['files']['name'][$i];
            $file_size = $_FILES['files']['size'][$i];
            $file_tmp = $_FILES['files']['tmp_name'][$i];
        
            $imageFileType = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

            if ($file_size >= $maxsize) {

                $errors = "Your file is too large";

            } elseif ($imageFileType != "jpeg" && $imageFileType != "jpg" && 
                $imageFileType != "png" && $imageFileType != "gif") {

                $errors = "File type not allowed.";
            }
            //Make sure we have a file path
            if (!$errors /* && $file_tmp != "" */) {

                $picToUpload = $date_time . " -#- " . md5($file_name) . " -#- " . $_FILES['files']['name'][$i];
                $uploadPicture = move_uploaded_file($file_tmp, "uploads/" . $picToUpload);

                $file_path = "uploads/" . $picToUpload;
                $stmt->execute();
            }
        }
    }

Post.php:

public function submitPost($title, $body, $user_to, $imageName) {

        $title = trim(strip_tags(filter_var($_POST['title_post'], FILTER_SANITIZE_STRING)));
        $body = trim(strip_tags(filter_var($body, FILTER_SANITIZE_STRING)));
        $check_empty = preg_replace('/\s+/', '', $body); //Deletes all spaces
        $check_empty_title = preg_replace('/\s+/', '', $title); //Deletes all spaces 
      
        if($check_empty != "" || $check_empty_title != "" || $imageName != "") {

            $body_array = preg_split("/\s+/", $body);
            $title_array = preg_split("/\s+/", $title);

            $body = implode(" ", $body_array);
            $title = implode(" ", $title_array);
            //Current date and time
            $date_added = date("Y-m-d H:i:s");
            //Get username
            $added_by = $this->user_obj->getUsername();

            //If user is on own profile, user_to is 'none'
            if($user_to == $added_by) {
                $user_to = "none";
            }

            //insert post 
            $query = $this->con->prepare("INSERT INTO posts (title, body, added_by, user_to, image) 
                VALUES (?, ?, ?, ?, ?)");
            $query->bind_param("sssss", $title, $body, $added_by, $user_to, $imageName);
            $query->execute();
            $returned_id = mysqli_insert_id($this->con);

            //Insert notification 

            if($user_to != 'none') {

                $notification = new Notification($this->con, $added_by);
                $notification->insertNotification($returned_id, $user_to, "profile_post");
            }

            //Update post count for user 
            $num_posts = $this->user_obj->getNumPosts();
            $num_posts++;

            $update_query = $this->con->prepare('UPDATE users SET num_posts = ? WHERE username = ?');
            $update_query->bind_param("is", $num_posts, $added_by );
            $update_query->execute();

            $stopWords = "i you are gay am a about above brandon tisson";

            $stopWords = preg_split("/[\s,]+/", $stopWords);

            $no_punctuation = preg_replace("/[^a-zA-Z 0-9] +/", "", $body);

            if (strpos($no_punctuation, "height") === false && strpos($no_punctuation, "width") 
                === false && strpos($no_punctuation, "http") === false) {

                $no_punctuation = preg_split("/[\s,]+/", $no_punctuation);

                foreach ($stopWords as $value ) {

                    foreach ($no_punctuation as $key => $value2) {

                        if (strtolower($value) == strtolower($value2) ) {

                            $no_punctuation[$key] = "";
                        }
                    }
                }

                foreach ($no_punctuation as $value) {

                    $this->calculateTrend(ucfirst($value));
                }
            }
        }
    }

所以总而言之,我试图从过程样式代码中的函数中获取帖子的 ID。

标签: phpmysqli

解决方案


您应该从返回帖子 ID submitPost()。否则,如果有其他插入(例如 in $notification->insertNotification()),它们将覆盖由 . 返回的 ID mysqli_insert_id($con)

使用它也好一点,$query->insert_id而不是mysqli_insert_id($this->con);因为它特定于该查询,而不是同一连接上的INSERT最新查询。INSERT

$post = new Post($con, $userLoggedIn);

$title = trim(strip_tags(filter_var($_POST['title_post'], FILTER_SANITIZE_STRING )));
$body = trim(strip_tags(filter_var($_POST['post_text'], FILTER_SANITIZE_STRING )));
$id = $post->submitPost($title, $body, 'none', $imageName);

if (!$errors) {
    $stmt = $con->prepare("INSERT INTO post_images (image, post_id) VALUES (?, ?)");
    $stmt->bind_param('si', $file_path, $id);

    // Loop through each file
    for( $i=0; $i < $file_count; $i++ ) {

        $file_name = $_FILES['files']['name'][$i];
        $file_size = $_FILES['files']['size'][$i];
        $file_tmp = $_FILES['files']['tmp_name'][$i];
        
        $imageFileType = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        if ($file_size >= $maxsize) {
            $errors = "Your file is too large";
        } elseif ($imageFileType != "jpeg" && $imageFileType != "jpg" && 
                  $imageFileType != "png" && $imageFileType != "gif") {
            $errors = "File type not allowed.";
        }
        //Make sure we have a file path
        if (!$errors /* && $file_tmp != "" */) {
            $picToUpload = $date_time . " -#- " . md5($file_name) . " -#- " . $_FILES['files']['name'][$i];
            $uploadPicture = move_uploaded_file($file_tmp, "uploads/" . $picToUpload);
            $file_path = "uploads/" . $picToUpload;
            $stmt->execute();
        }
    }
}
public function submitPost($title, $body, $user_to, $imageName) {
    $title = trim(strip_tags(filter_var($_POST['title_post'], FILTER_SANITIZE_STRING)));
    $body = trim(strip_tags(filter_var($body, FILTER_SANITIZE_STRING)));
    $check_empty = preg_replace('/\s+/', '', $body); //Deletes all spaces
    $check_empty_title = preg_replace('/\s+/', '', $title); //Deletes all spaces 
      
    if($check_empty != "" || $check_empty_title != "" || $imageName != "") {
        $body_array = preg_split("/\s+/", $body);
        $title_array = preg_split("/\s+/", $title);

        $body = implode(" ", $body_array);
        $title = implode(" ", $title_array);
        //Current date and time
        $date_added = date("Y-m-d H:i:s");
        //Get username
        $added_by = $this->user_obj->getUsername();

        //If user is on own profile, user_to is 'none'
        if($user_to == $added_by) {
            $user_to = "none";
        }

        //insert post 
        $query = $this->con->prepare("INSERT INTO posts (title, body, added_by, user_to, image) 
                VALUES (?, ?, ?, ?, ?)");
        $query->bind_param("sssss", $title, $body, $added_by, $user_to, $imageName);
        $query->execute();
        $returned_id = $query->insert_id;

        //Insert notification 

        if($user_to != 'none') {

            $notification = new Notification($this->con, $added_by);
            $notification->insertNotification($returned_id, $user_to, "profile_post");
        }

        //Update post count for user 
        $num_posts = $this->user_obj->getNumPosts();
        $num_posts++;

        $update_query = $this->con->prepare('UPDATE users SET num_posts = ? WHERE username = ?');
        $update_query->bind_param("is", $num_posts, $added_by );
        $update_query->execute();

        $stopWords = "i you are gay am a about above brandon tisson";

        $stopWords = preg_split("/[\s,]+/", $stopWords);

        $no_punctuation = preg_replace("/[^a-zA-Z 0-9] +/", "", $body);

        if (strpos($no_punctuation, "height") === false && strpos($no_punctuation, "width") 
            === false && strpos($no_punctuation, "http") === false) {

            $no_punctuation = preg_split("/[\s,]+/", $no_punctuation);

            foreach ($stopWords as $value ) {

                foreach ($no_punctuation as $key => $value2) {

                    if (strtolower($value) == strtolower($value2) ) {

                        $no_punctuation[$key] = "";
                    }
                }
            }

            foreach ($no_punctuation as $value) {

                $this->calculateTrend(ucfirst($value));
            }
        }
    }
    
    return $returned_id;
}

推荐阅读