2015-05-24 64 views
0

我的PHP腳本有問題。我想插入數據到我的數據庫中,但它返回的唯一信息是錯誤。子查詢返回多行?無法在數據庫中寫入

代碼:

<?php 
require_once('ConnectionHandler.php'); 

Class CreateTask 
{ 

    public function createNewTask($description, $subject, $type, $enddate, $priority) 
    { 

     $query = 'INSERT INTO task (description, subject_id, task_type_id, enddate, priority) VALUES (?, (SELECT id_subject FROM subject WHERE name = ?), (SELECT id_task_type FROM task_type WHERE type = ?), ?, ?)'; 

     $statement = ConnectionHandler::getConnection()->prepare($query); 
     $statement->bind_param('siisi', $description, $subject, $type, $enddate, $priority); 

     if (!$statement->execute()) { 
      throw new Exception($statement->error); 
     } else { 
      return true; 
     } 
    } 

} 

?> 

在ConnectionHandler它設置連接到數據庫。

錯誤:

Fatal error: Uncaught exception 'Exception' with message 'Subquery returns more than 1 row' in E:\xampp\htdocs\lib\CreateTask.php:16 Stack trace: #0 E:\xampp\htdocs\homelogedin.php(21): CreateTask->createNewTask('fgdgdsg', 'Mathematics', 'Exam', '2015-05-31', '3') #1 E:\xampp\htdocs\pages\index.php(4): require_once('E:\\xampp\\htdocs...') #2 E:\xampp\htdocs\lib\CentralDesign.php(35): require_once('E:\\xampp\\htdocs...') #3 E:\xampp\htdocs\index.php(9): CentralDesign->loadPage() #4 {main} thrown in E:\xampp\htdocs\lib\CreateTask.php on line 16 

回答

0

你就不能使用INSERT INTO的方式。在這種情況下Subquerys是不允許的。但是,標量表達式將向招:

INSERT INTO task (description, subject_id, task_type_id, enddate, priority) 
SELECT 'desc', A.id_subject, B.id_task_type, '2015-05-05', 2 
FROM 
    (SELECT id_subject FROM subject WHERE name = 'Blau') A, 
    (SELECT id_task_type FROM task_type WHERE type = 'typ1') B 

最好的問候,binzram

PS: 下一次拿律旅程我的辦公桌上。