PHP PDO and Mysql [closed]

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

Leave a Comment