-1

I want to display an alert box showing a message with PHP. If I not use alert box I get the right answer such "update subject set semester=2 where id=171 ". But after I change into alert box the answer i get in the alert box only "update subject set $f=$data where id=$did" and it does not update in database.

Here is my PHP code:

 if ($tag == 2) {
        $query = '<script type=text/javascript> alert("update subject set $f=$data where id=$did")</script>';
        $result = mysql_query($query);
        print "$query";
      }
elsa
  • 17
  • 4
  • yes, it will not updated because it is not a valid query. can you explain exactly what you want? – urfusion Sep 14 '16 at 05:45
  • 1. Don't use the deprecated `mysql_*`-functions. They are deprecated since PHP 5.5 and completely removed in PHP 7. Use MySQLi or PDO instead. 2. You are wide open to [SQL Injections](http://php.net/manual/en/security.database.sql-injection.php) and should really use [Prepared Statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) instead of concatenating your queries, which can be used if you use the above mentioned MySQLi or PDO. – M. Eriksson Sep 14 '16 at 06:08

3 Answers3

1

Change the quotations. Learn the difference between single and double quotes. Also, you can't update using that which is an invalid query with Javascript statement. Instead use:

if ($tag == 2) {
    $query = "update subject set $f=$data where id=$did";
    $result = mysql_query($query);
    echo "<script type=text/javascript>alert('$query')</script>";
}

Note : mysql_ extensions are deprecated, use mysqli or PDO

Community
  • 1
  • 1
Thamilhan
  • 13,040
  • 5
  • 37
  • 59
0

What you are passing to the deprecated mysql_query function was not valid sql and would cause an error, I suspect you were trying something along these lines?

if ($tag == 2) {
    $sql="update `subject` set `$f`='$data' where `id`='$did'";
    $query = '<script type=text/javascript> alert('$sql')</script>';

    $result = mysql_query($sql);

    echo $query;
}
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
0

If you want a success message you should do:

if ($tag == 2) {
    $query = 'update subject set $f=$data where id=$did")';
    $result = mysql_query($query);
    if($result)
       echo "<script type=text/javascript> alert('message')</script>";
    }
}