0

How can I correctly do select then insert the result in the $result?

$result = mysql_query("SELECT AVG(answervalue) 
                        FROM `tblanswer` 
                        WHERE questiontype = 'Methods' 
                         AND studentid = '$username' 
                         AND subjectname = '$server_subject' 
                         AND professorname = '$server_name', $connect);

$Query = "INSERT INTO tblevaluationgrade (result) VALUES ('$result')";
jitendrapurohit
  • 9,435
  • 2
  • 28
  • 39
Raniel Quirante
  • 315
  • 2
  • 15
  • you have an obvious syntax error, IF that's your real code. – Funk Forty Niner Jan 29 '16 at 12:42
  • Also note that `AVG` is not going to do much without a `GROUP BY` clause. – jeroen Jan 29 '16 at 12:47
  • PHPMyAdmin *is not* a database. It is a web interface for your MySQL database. – Jay Blanchard Jan 29 '16 at 13:24
  • Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Jan 29 '16 at 13:24

2 Answers2

5

Your query should be like:

INSERT INTO tblevaluationgrade(result_column) 
   (SELECT AVG(answervalue) FROM `tblanswer`   
     WHERE questiontype = 'Methods' AND studentid = '$username'   
       AND subjectname = '$server_subject' AND professorname = '$server_name')
Luthando Ntsekwa
  • 4,192
  • 6
  • 23
  • 52
5

You can do that in one query using INSERT ... SELECT syntax:

INSERT INTO tblevaluationgrade (result)
    SELECT AVG(answervalue) FROM `tblanswer` ...

And you should probably switch to PDO or mysqli and prepared statements as the mysql_* functions are deprecated and have been removed from php 7 and your query looks vulnerable to sql injection.

jeroen
  • 91,079
  • 21
  • 114
  • 132