2015-06-17 168 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