如何在页面点击上运行PHP数据库操作? [重复]
This question already has an answer here:
I had a problem.I wanna do a query only when i click a button but without click it did the query the code is:
<html>
<head>
<title>prova del metodo post tramite javascript</title>
<script>
function scriviSQL(){
document.write("<?php
$con = mysql_connect('localhost','root');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('provadidb', $con);
$sql = 'INSERT INTO provatab (cognome,nome) VALUES("provdicognome","provadinome");';
mysql_query($sql,$con);
mysql_close($con);
?>");
}
</script>
<button id="conferma" onClick="scriviSQL();">Continua</button>
i tryed to put it in body or head i had the same problem, i tryed to create a function with php too but nothing... sorry for my bad english..
</div>
Web page javascript runs in the browser. It does not run on the server.
PHP runs on your server. It does not run in the browser.
Some PHP may run at the time the web page is requested in order to populate some data into the web page, but once the web page has been served to the browser, there is no more PHP. Your particular PHP is running when the web page is served which is why it runs immediately and doesn't wait for the click.
Because of the way this all works, you cannot use the construct you're trying to use where you are trying to execute PHP from the browser.
If you want to do a query on your server from a javascript function in the web page like your scriviSQL()
function, then you need to use an Ajax call to actually call your server and your server will have to be ready to receive and process that request.
I'd suggest you do some Googling for Ajax as you will find a ton of useful references. You can start with the Wikipedia article on Ajax which has a code example with javascript in the web page and PHP on the server.