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 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64