-2

I Have some trouble with php script.

I want to run mysql Query on php code when i click some link..

There is my code

<?php
function hello(){
    $browser=$_SERVER['HTTP_USER_AGENT'];

    $url="http://".$_SERVER[SERVER_NAME].$_SERVER[REQUEST_URI];

    $ip=$_SERVER['REMOTE_ADDR'];

    mysql_connect("localhost","root","") or die("cannot connect");
    mysql_select_db("kpp924");

    mysql_query("INSERT INTO logs(ip,url,link,browser,waktu) VALUES ('$ip','$url','http://www.google.com','$browser','this is waktu')");
    mysql_close();
}
?>

<a href="http://www.google.com" onclick="document.write('<?php hello() ?>');" >Click to save log</a>

This code got work, when i click on the link, the value inserted to the database. But my problem is, When i open the page, the function is running, an new data inserted to the database without clicking on the link.

is something wrong with my code?? can please anything tell me where is the mistake. or maybe someone can be solve it with javascript??

  • 1
    You can't call a server-side PHP function from client-side JavaScript like that. – Revent May 03 '13 at 20:39
  • Please create a PHP file to query the database, then have javascript link or ajax it. – Dave Chen May 03 '13 at 20:42
  • Possible duplicate of [Reference: Why does the PHP code in my JavaScript not work?](http://stackoverflow.com/questions/13840429/reference-why-does-the-php-code-in-my-javascript-not-work)... – War10ck May 03 '13 at 20:43
  • 1
    You're vulnerable to [SQL injection attacks](http://bobby-tables.com), have PHP syntax errors, and you should **NEVER** use the root mysql account for any public facing code – Marc B May 03 '13 at 20:47

1 Answers1

0

The main problem is this:

<a href=[..snip...]ment.write('<?php hello() ?>');" >Click to save log</a>
                               ^^^^^^^^^^^^^^^^

PHP is executed on the server. So when the page is being generated by PHP, the hello function is called. You cannot have the code work like this. Javascript will NEVER see hello() because PHP on the server will have replaced that <?php hello() ?> block with any warnings/errors generated by the function call.

You need an AJAX call to send the form data back to the server, or at least do a traditional form submission.

Marc B
  • 356,200
  • 43
  • 426
  • 500