У меня проблема с обновлением строки таблицы MySQL - PullRequest
0 голосов
/ 15 декабря 2018

Я запрашиваю базу данных MySQL, используя позиционные (анонимные) заполнители PDO.И я пытаюсь обновить ранее добавленный курс.Когда я выбираю курс из списка и редактирую его, я ожидаю, что курс будет обновлен в базе данных, но это не так.Моя серверная среда - WampServer в Windows 10. Ниже приводится « modify-course.php »:

<?php

// configuration
require("../includes/config.php");

// query admin table to retrieve current admin's profile    
//select a particular admin by id

// query users table to retrieve current admin's profile
if (array_key_exists('aid', $_GET)) {

// select a particular admin by id
$stmt = $pdo->prepare("SELECT * FROM admin WHERE aid=?");
$stmt->execute([$_GET["aid"]]); 
$admin = $stmt->fetch(); # get admin data

if (!$admin)
{
   header("Location: login.php");
}


// query users table to retrieve admin homepage's contents
// $users = query("SELECT * FROM users WHERE id = ?");


//Class import for image uploading
//classes is the map where the class file is stored (one above the root)
include ("../classes/upload/upload_class.php");         

//select a particular course by id
if (array_key_exists('cid', $_GET)) {

// select a particular course by id
$stmt = $pdo->prepare("SELECT * FROM courses WHERE cid=?");
$stmt->execute([$_GET["cid"]]); 
$course = $stmt->fetch(); # get course data

if ($_SERVER["REQUEST_METHOD"] == "POST")
{

    // validate submission
    if (empty($_POST["c_name"]))
    {
         echo "Provide the course name.";
    }
    if (empty($_POST["duration"]))
    {
        echo "Provide the course duration.";
    }
    if (empty($_POST["code"]))
    {
        echo "Provide the course code.";
    }
    if (empty($_POST["fees"]))
    {
        echo "Enter total fees for the course.";
    }

        // validate course name         
        if(isset($_POST['c_name'])){
            $name = ($_POST["c_name"]);

        if (!preg_match("/^[a-zA-Z0-9]*$/", $name))
        {
            echo "A course name must contain only letters and/or numbers.";
        }
        if (strlen($_POST["c_name"]) < 20 || strlen($_POST["c_name"]) > 50)
        {
            echo "A course name must be from 20 to 50 characters.";
        }
        }
        // validate course duration
        $duration = ($_POST["duration"]);

        if (!preg_match("/^[a-zA-Z0-9]*$/", $duration))
        {
            echo "Invalid course duration.";
        }
        // validate course ID
        $code = ($_POST["code"]);

        if (!preg_match("/^[a-zA-Z0-9]*$/", $code))
        {
            echo "A course ID can only contain letters and numbers.";
        }
        if (strlen($_POST["code"]) < 3 || strlen($_POST["code"]) > 10)
        {
            echo "A course code must be from 3 to 10 characters.";
        }
        if ($_POST["code"] === false)
        {
            echo "The course code has already been taken.";
        }

    //This is the directory where images will be saved 
    $max_size = 1024*250; // the max. size for uploading

    $my_upload = new file_upload;

    $my_upload->upload_dir = "../images/courses/"; // "files" is the folder for the uploaded files (you have to create this folder)
    $my_upload->extensions = array(".png", ".gif", ".jpeg", ".jpg"); // specify the allowed extensions here
    // $my_upload->extensions = "de"; // use this to switch the messages into an other language (translate first!!!)
    $my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100)
    $my_upload->rename_file = true;
    if(isset($_FILES['image'])) {
    $my_upload->the_temp_file = $_FILES['image']['tmp_name'];
    $my_upload->the_file = $_FILES['image']['name'];
    $my_upload->http_error = $_FILES['image']['error'];
    }
    $my_upload->replace = "y";
    $my_upload->do_filename_check = "n"; // use this boolean to check for a valid filename
    if ($my_upload->upload()) // new name is an additional filename information, use this to rename the uploaded file
    {
        $full_path = $my_upload->upload_dir.$my_upload->file_copy;
        $imagename = $my_upload->file_copy;
    }
    else
    {
        $imagename = "";
    }

    if (!empty($_POST["c_name"]))
    {
        $result = "UPDATE courses SET c_name=?, title=?, meta_keywords=?, meta_description=?, short_desc=?, c_desc=?, duration=?, code=?, fees=?, image=? WHERE cid=?";
        $stmt= $pdo->prepare($result);
        $stmt->execute([$c_name, $c_title, $meta_keywords, $meta_description, $short_desc, $c_desc, $duration, $code, $fees, $image]);

        // if username is in database
        if ($stmt === false)
        {
            echo "There was an error modifying this course.";
        }

        // update courses' DB table to reference the image's new file name
        //query(sprintf("UPDATE courses SET image = '%s' WHERE id = $id", $my_upload->file_copy));


        // find out course ID
        //$rows = $pdo->query("SELECT LAST_INSERT_ID() AS id");
        //$id = $rows[0]["id"];

        // redirect to list courses page
        header("Location: list-courses.php");
    }


}
}

}
// render the header
include("templates/header.php");

// render modify course template
include("templates/modify-course_template.php");

// render the footer
include("templates/footer.php");

?>

Ваша помощь будет принята с благодарностью.Заранее спасибо.

1 Ответ

0 голосов
/ 15 декабря 2018

Если у вас есть два отдельных идентификатора, вы должны отправить два разных параметра запроса.В приведенных конкретных примерах программа будет перенаправлять на login.php, если идентификатора 2 или 3 не существует в таблице admin.

Вызывающий должен отправить строку запроса, например, aid={a}&cid={c} (вместо id={num}), где aid - это идентификатор таблицы администратора, а cid - это идентификатор таблицы курса.Затем весь связанный код необходимо изменить, чтобы использовать соответствующий параметр.

Вторая проблема заключается в том, как @atoms описывает в комментариях.$stmt->execute не отправляет достаточно значений;идентификатор отсутствует.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...