dongzhuo1958 2014-04-28 22:20
浏览 20
已采纳

如何在页面点击上运行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>
  • 写回答

1条回答 默认 最新

  • dsfdgdsfd23212 2014-04-28 22:30
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥20 jupyter保存图像功能的实现
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键