<?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();
}
?>
I'm creating a CRUD with jQuery and PHP and I'm almost sure the error is in this file, I cannot create data, and the echos "Product was created." and "Unabled to create product." are not displaying anywhere. I was wondering if you could help
Here's a rough answer which should resolve the injection issue, the non-executing query issue, and the incorrect insert
syntax. I don't have your DB so I can't confirm this is fully functional but it should be closer..
<?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();
}
?>
Notice the insert
syntax used here. At the start you define the columns
INSERT INTO classificacao(nota, semestre, aluno_id, utilizador_id)
Then you pass the values in after the values
. Each value is separated by a comma.
VALUES (?, ?, ?, ?)
You don't pass the columns in there. The ?
are placeholders for the values going to the DB.
Links for further reading:
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