2015-06-17 211 views
-5
<?php 
// include to get database connection 
include_once 'config/db.php'; 

try{ 
    $a_id = "SELECT a.id FROM aluno a, utilizador u WHERE a.utilizador_id = u.id 
    AND u.nome =" . $_POST['nome']; 
    $prof = 1; 

    $query = "INSERT INTO classificacao(nota, semestre, dt_classif, 
    aluno_id, utilizador_id) VALUES (nota=:nota, semestre=:semestre, dt_classif=DEFAULT , 
    aluno_id=:aluno_id, utilizador_id=:utilizador_id)"; 

    $stmt = $con->prepare($query); 

    $stmt->bindParam(":nota", $_POST['nota']); 
    $stmt->bindParam(":semestre", $_POST['semestre']); 
    $stmt->bindParam(":aluno_id", $a_id); 
    $stmt->bindParam(":utilizador_id", $prof); 

    // execute the query 
    if($stmt->execute()){ 
     echo "Product was created."; 
    }else{ 
     echo "Unable to create product."; 
    } 
} 
catch(PDOException $exception){ 
    echo "Error: " . $exception->getMessage(); 
} 

?> 

我用jQuery和PHP創建了一個CRUD,我幾乎可以確定錯誤出現在這個文件中,我無法創建數據,並且回聲「產品已創建」。和「無法創建產品」。沒有顯示在任何地方。我在想,如果你能幫助PHP PDO和Mysql

+0

我們怎麼知道?你不說錯了什麼?你有錯誤嗎? 「有什麼不對勁」沒有說什麼。 – Rasclatt

+0

請閱讀手冊http://php.net/pdo.prepared-statements和http://php.net/manual/en/pdo.error-handling.php,您的查詢全部錯誤。 –

+0

@ Fred-ii-我的查詢全錯了嗎? – RUIFERNANDE5

回答

0

這裏是應該解決的注入問題,非執行查詢的問題,以及不正確的語法insert一個粗略的答案。我沒有你的數據庫,所以我不能確認這是全功能的,但它應該更接近..

<?php 
// include to get database connection 
include_once 'config/db.php'; 
try{ 
    $a_id = "SELECT a.id as aid FROM aluno a, utilizador u WHERE a.utilizador_id = u.id 
    AND u.nome = ?"; 
    $stmt = $con->prepare($query); 
    $stmt->execute(array($_POST['nome'])); 
    while ($row = $stmt->fetch_assoc()) { 
     $aids[] = $row['aid']; 
     $a_id = $row['aid']; 
    } 
    // what are you doing if there are more than one record? 
    // current execution will only have the last id as $a_id 
    $prof = 1; 
    $query = "INSERT INTO classificacao(nota, semestre, aluno_id, utilizador_id) 
       VALUES (?, ?, ?, ?)"; 
    $stmt = $con->prepare($query); 
    // execute the query 
    if($stmt->execute(array($_POST['nota'], $_POST['semestre'], $a_id, $prof))){ 
     echo "Product was created."; 
    }else{ 
     echo "Unable to create product."; 
    } 
} 
catch(PDOException $exception){ 
    echo "Error: " . $exception->getMessage(); 
} 
?> 

注意這裏使用的insert語法。一開始你定義的列

INSERT INTO classificacao(諾塔,semestre,aluno_id,utilizador_id)

然後,你將在values後的值。每個值由逗號分隔。

VALUES(?,?,?,?)

你不及格列在那裏。 ?是去往數據庫的值的佔位符。

鏈接進一步閱讀:

How can I prevent SQL injection in PHP?
http://dev.mysql.com/doc/refman/5.6/en/insert.html
https://dev.mysql.com/doc/refman/5.0/en/update.html
http://php.net/manual/en/pdo.prepared-statements.php

+0

非常感謝你的隊友,解決了我的問題,我一定會檢查出來的! – RUIFERNANDE5