Error: intentando obtener la propiedad ‘num_rows’ de un no objeto en C:\wamp64\www\online-exam-portal\code\manage-exam\_export-to-csv.php en la línea 85

programación

[ad_1]

Estoy intentando obtener información de la base de datos sobre todos los exámenes que toman los estudiantes y exportar los datos a Csv, pero aparece este error.

<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Trying to get property 'num_rows' of non-object in C:\wamp64\www\online-exam-portal\code\manage-exam\_export-to-csv.php on line 85</th></tr>

aquí está el código que escribí, export-to-csv.php para recuperar los datos,

PHP
  1  <?php
  2  require_once '../connect.php';
  3  require_once '../session.php';
  4  
  5  ini_set('display_errors', 1);
  6  ini_set('display_startup_errors', 1);
  7  error_reporting(E_ALL);
  8  
  9  // Check if the user is logged in
 10   //(!isset($_SESSION['user_id'])) {
 11      //Redirect or handle unauthorized access
 12      //header('Location: ../session.php')
 13     //exit();
 14  //}
 15  
 16  // Set the content-type to CSV and specify the filename for download
 17  header("Content-type: application/csv");
 18  header("Content-Disposition: attachment; filename=user_responses.csv");
 19  header("Pragma: no-cache");
 20  header("Expires: 0");
 21  
 22  // Get the user ID from the session
 23  $userID = $_SESSION['userID'];
 24  $examID = $_POST['examID'];
 25  
 26  //echo "<pre>" . $userID . "<pre/>";
 27  //exit();
 28  
 29  // Fetch user responses to questions
 30  $sql = "SELECT
 31              'Multi-choice' AS exam_type,
 32              mcq.question AS question_text,
 33              mcq.correct_answer AS correct_answer,
 34              mcqr.response AS chosen_option,
 35              mcqr.score AS marks
 36          FROM
 37              multi_choice_question mcq
 38              INNER JOIN multi_choice_response mcqr ON mcq.exam_id = mcqr.exam_id
 39                  AND mcq.question_no = mcqr.question_no
 40          WHERE
 41              mcqr.assignee_id = '$userID'
 42              AND mcq.exam_id = $examID
 43  
 44          UNION
 45  
 46          SELECT
 47              'Fill in the blank' AS exam_type,
 48              fiq.question AS question_text,
 49              fir.response AS chosen_option,
 50              fir.score AS marks
 51          FROM
 52              fill_in_question fiq
 53              INNER JOIN fill_in_response fir ON fiq.exam_id = fir.exam_id
 54                  AND fiq.question_no = fir.question_no
 55          WHERE
 56              fir.assignee_id = '$userID'
 57              AND fiq.exam_id = $examID
 58  
 59          UNION
 60  
 61          SELECT
 62              'Theory' AS exam_type,
 63              tq.question AS question_text,
 64              tr.response AS chosen_option,
 65              tr.score AS marks
 66          FROM
 67              theory_question tq
 68              INNER JOIN theory_response tr ON tq.exam_id = tr.exam_id
 69                  AND tq.question_no = tr.question_no
 70          WHERE
 71              tr.assignee_id = '$userID'
 72              AND tq.exam_id = $examID";
 73  
 74  $result = mysqli_query($conn, $sql);
 75  //echo "<pre>" . $result . "<pre/>";
 76  //exit();
 77  
 78  // Create the output file (without saving it)
 79  
 80  $dataFile = fopen('php://output', 'w');
 81  
 82  
 83  
 84  
 85  if ($result->num_rows > 0) {
 86  
 87      //if ($result) {
 88        //  if ($result ->num_rows > 0) {
 89      
 90  
 91  // Get the total possible mark
 92  $markResult = $conn->query("SELECT total_mark FROM exam WHERE exam_id = $examID");
 93  $totalMark = $markResult->fetch_assoc()['total_mark'];
 94  
 95    // Output the data
 96    while ($row = $result->fetch_assoc()) {
 97      fputcsv($dataFile, $row);
 98  // }
 99  }
100  
101      // Output the header
102      fputcsv($dataFile, array("QUESTION TYPE", "QUESTION", "CORRECT ANSWER", "CHOSEN OPTION", "SCORE(out of $totalMarks)"));
103  
104  }
105      else {
106      echo "0 results";
107  }
108  
109  // Close the file handle
110  fclose($dataFile);
111  
112  // Close the database connection
113  mysqli_close($conn);
114  ?>

Lo que he probado:

intentando obtener la propiedad ‘num_rows’ de un no objeto en C:\wamp64

Solución 1

El problema es ese $result no contiene nada. Lo más probable es que la llamada SQL en la línea 74 haya fallado, pero olvidó verificarla.

Solución 2

Lo más probable es que su error se deba a que la ejecución de su consulta ‘mysqli_query($conn, $sql)’ está fallando y, como resultado, ‘$resultado’ no es un objeto con su propiedad ‘num_rows’. Debe verificar si la ejecución de su consulta es exitosa y agregar algo de manejo de errores para verificar qué está fallando. Asegúrese de que su objeto ‘$conn’ sea válido y esté conectado a la base de datos.

PHP
$result = mysqli_query($conn, $sql);

if (!$result) {
    die('Error : ' . mysqli_error($conn));
}

Solución 3

Gracias a todos por sus rápidas respuestas, pero creo que debería haber aclarado mi consulta desde el principio. Bueno, voy a compartir el volcado de la base de datos y el código que creé para transmitir la información. Lo que intento hacer es obtener toda la información sobre el examen. Necesito el número de pregunta, la pregunta, las opciones de respuesta, la respuesta de los estudiantes, el nombre y la identificación del estudiante y exportarlos a Csv o Pdf si es posible. Aquí está el volcado de la base de datos;

-- phpMyAdmin SQL Dump
-- version 4.9.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jan 22, 2023 at 05:22 PM
-- Server version: 10.4.8-MariaDB
-- PHP Version: 7.3.11

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `exam_portal`
--

-- --------------------------------------------------------

--
-- Table structure for table `assignment_status`
--

CREATE TABLE `assignment_status` (
  `status_id` int(11) NOT NULL,
  `value` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `assignment_status`
--

INSERT INTO `assignment_status` (`status_id`, `value`) VALUES
(1, 'Awaiting approval'),
(2, 'Declined'),
(6, 'Graded'),
(4, 'In progress'),
(3, 'Ready'),
(5, 'Turned in');

-- --------------------------------------------------------

--
-- Table structure for table `course`
--

CREATE TABLE `course` (
  `course_code` varchar(8) NOT NULL,
  `course_name` varchar(256) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `course`
--

INSERT INTO `course` (`course_code`, `course_name`) VALUES
('CSC307', 'Computer Architecture and Organization'),
('GST301', 'Entrepreneurial Studies II'),
('CSC334', 'Numerical Analysis'),
('CSC303', 'Object Oriented Programming'),
('CSC305', 'Operating Systems II'),
('CSC309', 'Sytem Analysis and Design'),
('CSC313', 'Web Programming');

-- --------------------------------------------------------

--
-- Table structure for table `exam`
--

CREATE TABLE `exam` (
  `exam_id` int(11) NOT NULL,
  `instructor_id` varchar(16) NOT NULL,
  `course_code` varchar(8) NOT NULL,
  `title` varchar(45) NOT NULL,
  `type_id` int(11) NOT NULL,
  `no_of_questions` int(11) NOT NULL,
  `status_id` int(11) NOT NULL DEFAULT 1,
  `invite_prefix` varchar(5) NOT NULL,
  `total_mark` float NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `exam`
--

INSERT INTO `exam` (`exam_id`, `instructor_id`, `course_code`, `title`, `type_id`, `no_of_questions`, `status_id`, `invite_prefix`, `total_mark`) VALUES
(32, '171103026', 'CSC313', 'Quiz', 2, 1, 2, 'zmB1s', 150),
(34, '171103018', 'CSC313', 'Quiz II', 1, 1, 1, 'EnXAS', 0),

-- --------------------------------------------------------

--
-- Table structure for table `exam_assignment`
--

CREATE TABLE `exam_assignment` (
  `exam_id` int(11) NOT NULL,
  `assignee_id` varchar(16) NOT NULL,
  `total_score` float DEFAULT NULL,
  `status_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `exam_assignment`
--

INSERT INTO `exam_assignment` (`exam_id`, `assignee_id`, `total_score`, `status_id`) VALUES
(32, '171103007', NULL, 5),
(32, '171103010', 100, 6),
(32, '171103018', 98, 2),


-- --------------------------------------------------------

--
-- Table structure for table `exam_status`
--

CREATE TABLE `exam_status` (
  `status_id` int(11) NOT NULL,
  `value` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `exam_status`
--

INSERT INTO `exam_status` (`status_id`, `value`) VALUES
(2, 'Closed'),
(1, 'Open');

-- --------------------------------------------------------

--
-- Table structure for table `exam_type`
--

CREATE TABLE `exam_type` (
  `type_id` int(11) NOT NULL,
  `value` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `exam_type`
--

INSERT INTO `exam_type` (`type_id`, `value`) VALUES
(2, 'Fill in the blank'),
(1, 'Multi-choice'),
(3, 'Theory');

-- --------------------------------------------------------

--
-- Table structure for table `fill_in_question`
--

CREATE TABLE `fill_in_question` (
  `exam_id` int(11) NOT NULL,
  `question_no` int(11) NOT NULL,
  `question` varchar(256) NOT NULL,
  `mark` float NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `fill_in_question`
--

INSERT INTO `fill_in_question` (`exam_id`, `question_no`, `question`, `mark`) VALUES
(32, 1, 'PHP stands for ___', 15),
(36, 1, 'What\'s SSTF? ___', 100),


-- --------------------------------------------------------

--
-- Table structure for table `fill_in_response`
--

CREATE TABLE `fill_in_response` (
  `exam_id` int(11) NOT NULL,
  `question_no` int(11) NOT NULL,
  `assignee_id` varchar(16) NOT NULL,
  `response` varchar(45) DEFAULT NULL,
  `score` float DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `fill_in_response`
--

INSERT INTO `fill_in_response` (`exam_id`, `question_no`, `assignee_id`, `response`, `score`) VALUES
(32, 1, '171103018', 'Personal Home Page', 7.5),
(41, 1, '171103018', 'false', NULL),

-- --------------------------------------------------------

--
-- Table structure for table `level`
--

CREATE TABLE `level` (
  `level_id` int(11) NOT NULL,
  `value` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `level`
--

INSERT INTO `level` (`level_id`, `value`) VALUES
(1, '100'),
(2, '200'),
(3, '300'),
(4, '400'),
(5, '500');

-- --------------------------------------------------------

--
-- Table structure for table `multi_choice_question`
--

CREATE TABLE `multi_choice_question` (
  `exam_id` int(11) NOT NULL,
  `question_no` int(11) NOT NULL,
  `question` varchar(256) NOT NULL,
  `correct_answer` varchar(1) NOT NULL,
  `a` varchar(256) NOT NULL,
  `b` varchar(256) NOT NULL,
  `c` varchar(256) NOT NULL,
  `d` varchar(256) NOT NULL,
  `mark` float NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `multi_choice_question`
--

INSERT INTO `multi_choice_question` (`exam_id`, `question_no`, `question`, `correct_answer`, `a`, `b`, `c`, `d`, `mark`) VALUES
(34, 1, 'What\'s HTML?', 'B', 'Hypertext\'s markdown language', 'Hypertext markup language', 'Hyperthreaded machine link', 'Hyperthreaded motor link', 10),
(38, 3, 'What was the last thing we did in class?', 'A', 'Presentation', 'Revision', 'Normal class', 'Lab class', 35),

-- --------------------------------------------------------

--
-- Table structure for table `multi_choice_response`
--

CREATE TABLE `multi_choice_response` (
  `exam_id` int(11) NOT NULL,
  `question_no` int(11) NOT NULL,
  `assignee_id` varchar(16) NOT NULL,
  `response` varchar(1) DEFAULT NULL,
  `score` float DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `multi_choice_response`
--

INSERT INTO `multi_choice_response` (`exam_id`, `question_no`, `assignee_id`, `response`, `score`) VALUES
(39, 1, '171103026', 'a', 20),
(39, 2, '171103026', 'c', 0),


-- --------------------------------------------------------

--
-- Table structure for table `notification`
--

CREATE TABLE `notification` (
  `notification_id` int(10) UNSIGNED NOT NULL,
  `recipient_id` varchar(16) NOT NULL,
  `status_id` int(11) UNSIGNED NOT NULL DEFAULT 1,
  `type_id` int(11) UNSIGNED NOT NULL,
  `sender_id` varchar(16) NOT NULL,
  `exam_id` int(11) NOT NULL,
  `time_stamp` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `notification`
--

INSERT INTO `notification` (`notification_id`, `recipient_id`, `status_id`, `type_id`, `sender_id`, `exam_id`, `time_stamp`) VALUES
(19, '171103018', 2, 2, '171103026', 47, '2020-01-05 00:39:59'),
(20, '171103018', 2, 3, '171103026', 41, '2020-01-05 00:48:14'),

-- --------------------------------------------------------

--
-- Table structure for table `notification_status`
--

CREATE TABLE `notification_status` (
  `status_id` int(10) UNSIGNED NOT NULL,
  `value` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `notification_status`
--

INSERT INTO `notification_status` (`status_id`, `value`) VALUES
(1, 'Unviewed'),
(2, 'Viewed');

-- --------------------------------------------------------

--
-- Table structure for table `notification_type`
--

CREATE TABLE `notification_type` (
  `type_id` int(10) UNSIGNED NOT NULL,
  `value` varchar(45) NOT NULL,
  `msg_template` varchar(64) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `notification_type`
--

INSERT INTO `notification_type` (`type_id`, `value`, `msg_template`) VALUES
(1, 'Invite', '[User] has invited you to take [Exam]'),
(2, 'Accepted invite', '[User] has accepted your invite to take [Exam]'),
(3, 'Declined invite', '[User] has declined your invite to take [Exam]'),
(4, 'Joined by code', '[User] has joined [Exam] by invite code'),
(5, 'Started exam', '[User] has started [Exam]'),
(6, 'Completed exam', '[User] has completed [Exam]'),
(7, 'Graded exam', '[User] has graded [Exam]'),
(8, 'Closed exam', '[User] has closed [Exam]');

-- --------------------------------------------------------

--
-- Table structure for table `theory_question`
--

CREATE TABLE `theory_question` (
  `exam_id` int(11) NOT NULL,
  `question_no` int(11) NOT NULL,
  `question` varchar(256) NOT NULL,
  `mark` float NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `theory_question`
--

INSERT INTO `theory_question` (`exam_id`, `question_no`, `question`, `mark`) VALUES
(40, 1, 'What is your name?', 20),
(40, 2, 'What is my surname?', 30),
(47, 1, 'What is numerical analysis?', 50),
(55, 1, 'What is structure?', 15),
(55, 2, 'What is function?', 15);

-- --------------------------------------------------------

--
-- Table structure for table `theory_response`
--

CREATE TABLE `theory_response` (
  `exam_id` int(11) NOT NULL,
  `question_no` int(11) NOT NULL,
  `assignee_id` varchar(16) NOT NULL,
  `response` varchar(256) DEFAULT NULL,
  `score` float DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `theory_response`
--

INSERT INTO `theory_response` (`exam_id`, `question_no`, `assignee_id`, `response`, `score`) VALUES
(47, 1, '171103026', 'A mathematical course', 7),
(55, 1, '171103018', 'organization and interconnection of pc components', 10),
(55, 1, 'mubaraqwahab', 'Struct', 0),
(55, 2, '171103018', 'what the components do as part of structure', 12),
(55, 2, 'mubaraqwahab', 'A user defined function', 0);

-- --------------------------------------------------------

--
-- Table structure for table `user`
--

CREATE TABLE `user` (
  `user_id` varchar(16) NOT NULL,
  `first_name` varchar(45) NOT NULL,
  `last_name` varchar(45) NOT NULL,
  `email` varchar(45) NOT NULL,
  `password` varchar(45) NOT NULL,
  `level_id` int(11) DEFAULT NULL,
  `profile_picture` varchar(45) DEFAULT NULL,
  `recovery_key` varchar(8) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `user`
--

INSERT INTO `user` (`user_id`, `first_name`, `last_name`, `email`, `password`, `level_id`, `profile_picture`, `recovery_key`) VALUES
('171103007', 'Isa', 'Elleman', 'isaelleman@gmail.com', 'IsahE123', 3, NULL, NULL),
('171103010', 'Isiaq', 'Ibrahim', 'isiaq@yahoo.com', 'qwerty123', 3, NULL, NULL),
('171103018', 'Mustapha', 'Ibrahim', 'mikabu38@gmail.com', 'f4b37afc59e0792a3ea73192c96eb554', 3, '6bb000002217edf20324947d1d8eb5b1.jpg', NULL),

--
-- Indexes for dumped tables
--

--
-- Indexes for table `assignment_status`
--
ALTER TABLE `assignment_status`
  ADD PRIMARY KEY (`status_id`),
  ADD UNIQUE KEY `assignment_status_value_UNIQUE` (`value`);

--
-- Indexes for table `course`
--
ALTER TABLE `course`
  ADD PRIMARY KEY (`course_code`),
  ADD UNIQUE KEY `course_name_UNIQUE` (`course_name`);

--
-- Indexes for table `exam`
--
ALTER TABLE `exam`
  ADD PRIMARY KEY (`exam_id`),
  ADD KEY `exam_course_code_idx` (`course_code`),
  ADD KEY `exam_type_id_idx` (`type_id`),
  ADD KEY `exam_instructor_id_idx` (`instructor_id`),
  ADD KEY `exam_status_id` (`status_id`);

--
-- Indexes for table `exam_assignment`
--
ALTER TABLE `exam_assignment`
  ADD PRIMARY KEY (`exam_id`,`assignee_id`),
  ADD KEY `assignment_assignee_id_idx` (`assignee_id`),
  ADD KEY `assignment_status_id_idx` (`status_id`);

--
-- Indexes for table `exam_status`
--
ALTER TABLE `exam_status`
  ADD PRIMARY KEY (`status_id`),
  ADD UNIQUE KEY `exam_status_value_UNIQUE` (`value`);

--
-- Indexes for table `exam_type`
--
ALTER TABLE `exam_type`
  ADD PRIMARY KEY (`type_id`),
  ADD UNIQUE KEY `exam_type_value_UNIQUE` (`value`);

--
-- Indexes for table `fill_in_question`
--
ALTER TABLE `fill_in_question`
  ADD PRIMARY KEY (`exam_id`,`question_no`);

--
-- Indexes for table `fill_in_response`
--
ALTER TABLE `fill_in_response`
  ADD PRIMARY KEY (`exam_id`,`question_no`,`assignee_id`),
  ADD KEY `fill_in_response_assignee_id_idx` (`assignee_id`);

--
-- Indexes for table `level`
--
ALTER TABLE `level`
  ADD PRIMARY KEY (`level_id`),
  ADD UNIQUE KEY `level_value_UNIQUE` (`value`);

--
-- Indexes for table `multi_choice_question`
--
ALTER TABLE `multi_choice_question`
  ADD PRIMARY KEY (`exam_id`,`question_no`);

--
-- Indexes for table `multi_choice_response`
--
ALTER TABLE `multi_choice_response`
  ADD PRIMARY KEY (`exam_id`,`question_no`,`assignee_id`),
  ADD KEY `multi_choice_response_assignee_id_idx` (`assignee_id`);

--
-- Indexes for table `notification`
--
ALTER TABLE `notification`
  ADD PRIMARY KEY (`notification_id`),
  ADD KEY `notification_status_id` (`status_id`),
  ADD KEY `notification_sender_id` (`sender_id`),
  ADD KEY `notification_type_id` (`type_id`),
  ADD KEY `notification_recipient_id` (`recipient_id`),
  ADD KEY `exam_id` (`exam_id`);

--
-- Indexes for table `notification_status`
--
ALTER TABLE `notification_status`
  ADD PRIMARY KEY (`status_id`);

--
-- Indexes for table `notification_type`
--
ALTER TABLE `notification_type`
  ADD PRIMARY KEY (`type_id`),
  ADD UNIQUE KEY `msg_template_UNIQUE` (`msg_template`);

--
-- Indexes for table `theory_question`
--
ALTER TABLE `theory_question`
  ADD PRIMARY KEY (`exam_id`,`question_no`);

--
-- Indexes for table `theory_response`
--
ALTER TABLE `theory_response`
  ADD PRIMARY KEY (`exam_id`,`question_no`,`assignee_id`),
  ADD KEY `theory_response_assignee_id_idx` (`assignee_id`);

--
-- Indexes for table `user`
--
ALTER TABLE `user`
  ADD PRIMARY KEY (`user_id`),
  ADD UNIQUE KEY `email_UNIQUE` (`email`) USING BTREE,
  ADD KEY `user_level_id_idx` (`level_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `assignment_status`
--
ALTER TABLE `assignment_status`
  MODIFY `status_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;

--
-- AUTO_INCREMENT for table `exam`
--
ALTER TABLE `exam`
  MODIFY `exam_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=56;

--
-- AUTO_INCREMENT for table `exam_status`
--
ALTER TABLE `exam_status`
  MODIFY `status_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- AUTO_INCREMENT for table `exam_type`
--
ALTER TABLE `exam_type`
  MODIFY `type_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;

--
-- AUTO_INCREMENT for table `level`
--
ALTER TABLE `level`
  MODIFY `level_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;

--
-- AUTO_INCREMENT for table `notification`
--
ALTER TABLE `notification`
  MODIFY `notification_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=103;

--
-- AUTO_INCREMENT for table `notification_status`
--
ALTER TABLE `notification_status`
  MODIFY `status_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;

--
-- AUTO_INCREMENT for table `notification_type`
--
ALTER TABLE `notification_type`
  MODIFY `type_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;

--
-- Constraints for dumped tables
--

--
-- Constraints for table `exam`
--
ALTER TABLE `exam`
  ADD CONSTRAINT `exam_course_code` FOREIGN KEY (`course_code`) REFERENCES `course` (`course_code`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `exam_instructor_id` FOREIGN KEY (`instructor_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `exam_status_id` FOREIGN KEY (`status_id`) REFERENCES `exam_status` (`status_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `exam_type_id` FOREIGN KEY (`type_id`) REFERENCES `exam_type` (`type_id`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `exam_assignment`
--
ALTER TABLE `exam_assignment`
  ADD CONSTRAINT `assignment_assignee_id` FOREIGN KEY (`assignee_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `assignment_exam_id` FOREIGN KEY (`exam_id`) REFERENCES `exam` (`exam_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `assignment_status_id` FOREIGN KEY (`status_id`) REFERENCES `assignment_status` (`status_id`) ON UPDATE CASCADE;

--
-- Constraints for table `fill_in_question`
--
ALTER TABLE `fill_in_question`
  ADD CONSTRAINT `fill_in_question_exam_id` FOREIGN KEY (`exam_id`) REFERENCES `exam` (`exam_id`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `fill_in_response`
--
ALTER TABLE `fill_in_response`
  ADD CONSTRAINT `fill_in_response_assignee_id` FOREIGN KEY (`assignee_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `fill_in_response_id` FOREIGN KEY (`exam_id`,`question_no`) REFERENCES `fill_in_question` (`exam_id`, `question_no`) ON DELETE CASCADE;

--
-- Constraints for table `multi_choice_question`
--
ALTER TABLE `multi_choice_question`
  ADD CONSTRAINT `multi_choice_question_exam_id` FOREIGN KEY (`exam_id`) REFERENCES `exam` (`exam_id`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `multi_choice_response`
--
ALTER TABLE `multi_choice_response`
  ADD CONSTRAINT `multi_choice_response_assignee_id` FOREIGN KEY (`assignee_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `multi_choice_response_id` FOREIGN KEY (`exam_id`,`question_no`) REFERENCES `multi_choice_question` (`exam_id`, `question_no`) ON DELETE CASCADE;

--
-- Constraints for table `notification`
--
ALTER TABLE `notification`
  ADD CONSTRAINT `notification_ibfk_1` FOREIGN KEY (`exam_id`) REFERENCES `exam` (`exam_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `notification_recipient_id` FOREIGN KEY (`recipient_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `notification_sender_id` FOREIGN KEY (`sender_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `notification_status_id` FOREIGN KEY (`status_id`) REFERENCES `notification_status` (`status_id`),
  ADD CONSTRAINT `notification_type_id` FOREIGN KEY (`type_id`) REFERENCES `notification_type` (`type_id`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `theory_question`
--
ALTER TABLE `theory_question`
  ADD CONSTRAINT `theory_question_exam_id` FOREIGN KEY (`exam_id`) REFERENCES `exam` (`exam_id`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `theory_response`
--
ALTER TABLE `theory_response`
  ADD CONSTRAINT `theory_response_assignee_id` FOREIGN KEY (`assignee_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `theory_response_id` FOREIGN KEY (`exam_id`,`question_no`) REFERENCES `theory_question` (`exam_id`, `question_no`) ON DELETE CASCADE;

--
-- Constraints for table `user`
--
ALTER TABLE `user`
  ADD CONSTRAINT `user_level_id` FOREIGN KEY (`level_id`) REFERENCES `level` (`level_id`) ON DELETE CASCADE ON UPDATE SET NULL;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;



and this is my code;

<pre><!--?php
require_once '../connect.php';
require_once '../session.php';

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Check if the user is logged in
 //(!isset($_SESSION['user_id'])) {
    //Redirect or handle unauthorized access
   // header('Location: ../session.php')
   //exit();
//}

// Set the content-type to CSV and specify the filename for download
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=user_responses.csv");
header("Pragma: no-cache");
header("Expires: 0");

// Get the user ID from the session
$userID = $_SESSION['userID'];
$examID = $_POST['examID'];

//echo "<pre-->" . $userID . "<pre>";
//exit();

// Fetch user responses to questions
$sql = "SELECT
            'Multi-choice' AS exam_type,
            mcq.question AS question_text,
            mcq.correct_answer AS correct_answer,
            mcqr.response AS chosen_option,
            mcqr.score AS marks
        FROM
            multi_choice_question mcq
            INNER JOIN multi_choice_response mcqr ON mcq.exam_id = mcqr.exam_id
                AND mcq.question_no = mcqr.question_no
        WHERE
            mcqr.assignee_id = '$userID'
            AND mcq.exam_id = $examID

        UNION

        SELECT
            'Fill in the blank' AS exam_type,
            fiq.question AS question_text,
            fir.response AS chosen_option,
            fir.score AS marks
        FROM
            fill_in_question fiq
            INNER JOIN fill_in_response fir ON fiq.exam_id = fir.exam_id
                AND fiq.question_no = fir.question_no
        WHERE
            fir.assignee_id = '$userID'
            AND fiq.exam_id = $examID

        UNION

        SELECT
            'Theory' AS exam_type,
            tq.question AS question_text,
            tr.response AS chosen_option,
            tr.score AS marks
        FROM
            theory_question tq
            INNER JOIN theory_response tr ON tq.exam_id = tr.exam_id
                AND tq.question_no = tr.question_no
        WHERE
            tr.assignee_id = '$userID'
            AND tq.exam_id = $examID";

$result = mysqli_query($conn, $sql);

if (!$result) {
    echo mysqli_error($conn);
    exit();
}
//echo "<pre>" . $result . "<pre>";
//exit();

// Create the output file (without saving it)

$dataFile = fopen('php://output', 'w');




if ($result->num_rows > 0) {

    //if ($result) {
      //  if ($result ->num_rows > 0) {
    
   // Output the header      
   fputcsv($dataFile, array("QUESTION TYPE", "QUESTION", "CORRECT ANSWER", "CHOSEN OPTION", "SCORE(out of $totalMarks)"));
    
}
// Get the total possible mark
$markResult = $conn->query("SELECT total_mark FROM exam WHERE exam_id = $examID");
$totalMark = $markResult->fetch_assoc()['total_mark'];

 // Output the data
 while($row = $result->fetch_assoc()) {
    fputcsv($dataFile, $row);
  }

 
    else {
    echo "0 results";
}

// Close the file handle
fclose($dataFile);

// Close the database connection
mysqli_close($conn);
?>




and this is the error that i am getting;

Parse error: syntax error, unexpected 'else' (T_ELSE), expecting end of file in C:\wamp64\www\online-exam-portal\code\manage-exam\_export-to-csv.php on line 109

[ad_2]

コメント

Título y URL copiados