MySQL / PHP:使用Ajax添加,更新和检索数据,但所有3个共享相同的php文件?可能吗?

时间:2022-09-15 09:31:27

So in a file I have a form of which you add in a database, another form of which you retrieve and another of which you update. All forms are sending information using javascript (ajax) to some php files.

所以在一个文件中我有一个你在数据库中添加的形式,另一种形式是你检索的,另一种形式是你更新的。所有表单都使用javascript(ajax)向一些php文件发送信息。

For example:

// Add data

//添加数据

function get(str) {
   if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
   }
   xmlhttp.onreadystatechange = function () {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
         document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
      }
   }
   xmlhttp.open("GET", "ajaxget.php?q=" + str, true);
   xmlhttp.send();
}

// Update data

//更新数据

function update() {
    var ud_id = $('.ud_id').attr('value');
    var ud_first = $('.ud_first').attr('value');
    var ud_last = $('.ud_last').attr('value');

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
        }
    }

    xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id + "&ud_first=" + ud_first + "&ud_last=" + ud_last , true);
    xmlhttp.send();
    return false;
}

// Add new data

//添加新数据

function add() {
    var add_ud_first = $('.add_ud_first').attr('value');
    var add_ud_last = $('.add_ud_last').attr('value');

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
        }
    }

    xmlhttp.open("GET", "ajaxadd.php?add_ud_first=" + add_ud_first + "&add_ud_last=" + add_ud_last , true);
    xmlhttp.send();
    return false;
}

As you can see all snippets send to ajaxget.php, ajaxupdate.php and ajaxadd.php accordingly. Can I combine those files so I have 1 php of which called by all snippets?

正如您所看到的,所有片段都相应地发送到ajaxget.php,ajaxupdate.php和ajaxadd.php。我可以组合这些文件,所以我有1个PHP由所有片段调用?

So for example, all snippets will call the ajax.php file and within that file, if the get() calls it, then do accordingly.

因此,例如,所有片段都将调用ajax.php文件并在该文件中,如果get()调用它,则相应地执行。

Does that make sense?

那有意义吗?

Here is one ajaxget.php file:

这是一个ajaxget.php文件:

<?php   include("connection.php");

$q=$_GET["q"];


$query="SELECT * FROM contacts WHERE id = '".$q."'";

$result = mysql_query($query);

while($row = mysql_fetch_array($result))
  {
  echo "Name: " . $row['first'] . " <br />";
  echo "Surname: " . $row['last'] . " <br />";
  }

mysql_close();
?>

4 个解决方案

#1


4  

Add a parameter to your request (either POST or GET) to determine the type of request it is.

在请求中添加一个参数(POST或GET)以确定它的请求类型。

For example if you send a GET parameter (?operation=insert) then in the PHP code you should use a switch/if-else to execute the correct code.

例如,如果您发送GET参数(?operation = insert),那么在PHP代码中您应该使用switch / if-else来执行正确的代码。

$allowed_operations = array('insert', 'update', 'delete');
if(    isset($_GET['operation']) 
    && in_array(isset($_GET['operation']), $allowed_operations)){
    switch($_GET['operation']){
        case 'insert':
            // do insert operation here
            break;
        case 'update':
            // do update operation here
            break;
        case 'delete':
            //do delete operation here
            break;
    }
}

Edit 1

  1. put all the code of ajaxget.php, ajaxupdate.php and ajaxadd.php in ajaxop.php or anything else.
  2. 将ajaxget.php,ajaxupdate.php和ajaxadd.php的所有代码放在ajaxop.php或其他任何内容中。

  3. Keep the ajaxget.php contents in a function ajax_get() and same for others.
  4. 将ajaxget.php内容保存在函数ajax_get()中,对其他函数保持相同。

  5. Change the xmlhttp.open so that it calls only ajaxop.php and in the URI add operation=get, operation=update etc according to you need.
  6. 更改xmlhttp.open以便它只调用ajaxop.php并在URI中添加operation = get,operation = update等根据您的需要。

  7. Map those parameters in the switch statement.
  8. 在switch语句中映射这些参数。

#2


2  

A very simple approach:

一个非常简单的方法:

<?php

$action = 'list';

$arrActions = array ('list', 'add', 'update', 'delete');

if(isset($_GET['action']) && in_array($_GET['action'],$arrActions)) {
 include('ajax_action_'.$_GET['action'].'.php');
} else {
 include('ajax_action_list.php');
}

?>

With a simple file iike this you can 'route' your requests to other files ahd have those deal with them internally. There is a lot more to consider, but if you're starting out, keep it simple like this and then you'll be able to pick up elements you need specifically for your application in due time.

使用简单的文件,您可以将您的请求“路由”到其他文件,并在内部处理这些文件。还有很多事情需要考虑,但是如果你刚开始的话,请保持这样简单,然后你就能够在适当的时候为你的应用程序专门挑选你需要的元素。

UPDATE

An issue was raised about number of files:

提出了一个关于文件数量的问题:

This might help:

这可能有所帮助:

<?php

include("connection.php");

class controller {
  private $arrMethods = array('get','list','add','update','delete');

  public function __construct() {
   if(isset($_GET['action'])) {
    $method = 'do'.ucwords($_GET['action']); // list=>List, add=>Add, etc
    if(method_exists($method,$this)) {
      $this->$method();
    }
  }

  public function doGet () {

     $q=(int)(isset($_GET['q']) ? $_GET["q"] : 0);

     if(0 < (int)$q) {

        $query="SELECT * FROM `contacts` WHERE `id` = '$q'"; // limit to 1?
        $result = mysql_query($query);

        if($result && mysql_error()=='' && mysql_num_rows($result) > 0) {
           while($row = mysql_fetch_array($result)) {
              echo "Name: " . stripslashes($row['first']) . " <br />";
              echo "Surname: " . stripslashes($row['last']) . " <br />";
          }
        }

        mysql_close();
     }
  }

  public function doList () {

  } 

  public function doAdd () {

  }

  public function doEdit () {

  }

  public function doDelete () {

  }
}

$objController = new controller();

?>

This now becomes your gateway script with each function separated out.

这现在成为您的网关脚本,每个功能都分开了。

Does this give you a better starting point?

这会给你一个更好的起点吗?

#3


1  

add an argument ?action=add, or whatever. Your php script can check it and call an appropriate function with the q argument. But before you do anything else, google "SQL injection attack"

添加一个参数?action = add,或者其他什么。您的PHP脚本可以检查它并使用q参数调用适当的函数。但在你做任何其他事情之前,谷歌“SQL注入攻击”

<?php
$action = $_GET['action']
if $action == 'add' {
  // add code
}
elseif $action == 'update' {
  // update code
}
elseif $action == 'delete' {
  // delete code
}

#4


0  

It kinda looks like you are trying to build something like a REST api. I suggest you check this one: http://www.slimframework.com, and other sources for information about RESTful interfaces. Modifying the data between browser and server use REST api will also have the added benefit when front-end JavaScript frameworks like Backbone will semi-automatically understand it with minimal hassle.

看起来你正在尝试构建类似REST api的东西。我建议您查看这个:http://www.slimframework.com,以及其他有关RESTful接口的信息来源。修改浏览器和服务器之间的数据使用REST api还可以在Backbone等前端JavaScript框架以最小的麻烦半自动理解它时获得额外的好处。

Just sayin'.

#1


4  

Add a parameter to your request (either POST or GET) to determine the type of request it is.

在请求中添加一个参数(POST或GET)以确定它的请求类型。

For example if you send a GET parameter (?operation=insert) then in the PHP code you should use a switch/if-else to execute the correct code.

例如,如果您发送GET参数(?operation = insert),那么在PHP代码中您应该使用switch / if-else来执行正确的代码。

$allowed_operations = array('insert', 'update', 'delete');
if(    isset($_GET['operation']) 
    && in_array(isset($_GET['operation']), $allowed_operations)){
    switch($_GET['operation']){
        case 'insert':
            // do insert operation here
            break;
        case 'update':
            // do update operation here
            break;
        case 'delete':
            //do delete operation here
            break;
    }
}

Edit 1

  1. put all the code of ajaxget.php, ajaxupdate.php and ajaxadd.php in ajaxop.php or anything else.
  2. 将ajaxget.php,ajaxupdate.php和ajaxadd.php的所有代码放在ajaxop.php或其他任何内容中。

  3. Keep the ajaxget.php contents in a function ajax_get() and same for others.
  4. 将ajaxget.php内容保存在函数ajax_get()中,对其他函数保持相同。

  5. Change the xmlhttp.open so that it calls only ajaxop.php and in the URI add operation=get, operation=update etc according to you need.
  6. 更改xmlhttp.open以便它只调用ajaxop.php并在URI中添加operation = get,operation = update等根据您的需要。

  7. Map those parameters in the switch statement.
  8. 在switch语句中映射这些参数。

#2


2  

A very simple approach:

一个非常简单的方法:

<?php

$action = 'list';

$arrActions = array ('list', 'add', 'update', 'delete');

if(isset($_GET['action']) && in_array($_GET['action'],$arrActions)) {
 include('ajax_action_'.$_GET['action'].'.php');
} else {
 include('ajax_action_list.php');
}

?>

With a simple file iike this you can 'route' your requests to other files ahd have those deal with them internally. There is a lot more to consider, but if you're starting out, keep it simple like this and then you'll be able to pick up elements you need specifically for your application in due time.

使用简单的文件,您可以将您的请求“路由”到其他文件,并在内部处理这些文件。还有很多事情需要考虑,但是如果你刚开始的话,请保持这样简单,然后你就能够在适当的时候为你的应用程序专门挑选你需要的元素。

UPDATE

An issue was raised about number of files:

提出了一个关于文件数量的问题:

This might help:

这可能有所帮助:

<?php

include("connection.php");

class controller {
  private $arrMethods = array('get','list','add','update','delete');

  public function __construct() {
   if(isset($_GET['action'])) {
    $method = 'do'.ucwords($_GET['action']); // list=>List, add=>Add, etc
    if(method_exists($method,$this)) {
      $this->$method();
    }
  }

  public function doGet () {

     $q=(int)(isset($_GET['q']) ? $_GET["q"] : 0);

     if(0 < (int)$q) {

        $query="SELECT * FROM `contacts` WHERE `id` = '$q'"; // limit to 1?
        $result = mysql_query($query);

        if($result && mysql_error()=='' && mysql_num_rows($result) > 0) {
           while($row = mysql_fetch_array($result)) {
              echo "Name: " . stripslashes($row['first']) . " <br />";
              echo "Surname: " . stripslashes($row['last']) . " <br />";
          }
        }

        mysql_close();
     }
  }

  public function doList () {

  } 

  public function doAdd () {

  }

  public function doEdit () {

  }

  public function doDelete () {

  }
}

$objController = new controller();

?>

This now becomes your gateway script with each function separated out.

这现在成为您的网关脚本,每个功能都分开了。

Does this give you a better starting point?

这会给你一个更好的起点吗?

#3


1  

add an argument ?action=add, or whatever. Your php script can check it and call an appropriate function with the q argument. But before you do anything else, google "SQL injection attack"

添加一个参数?action = add,或者其他什么。您的PHP脚本可以检查它并使用q参数调用适当的函数。但在你做任何其他事情之前,谷歌“SQL注入攻击”

<?php
$action = $_GET['action']
if $action == 'add' {
  // add code
}
elseif $action == 'update' {
  // update code
}
elseif $action == 'delete' {
  // delete code
}

#4


0  

It kinda looks like you are trying to build something like a REST api. I suggest you check this one: http://www.slimframework.com, and other sources for information about RESTful interfaces. Modifying the data between browser and server use REST api will also have the added benefit when front-end JavaScript frameworks like Backbone will semi-automatically understand it with minimal hassle.

看起来你正在尝试构建类似REST api的东西。我建议您查看这个:http://www.slimframework.com,以及其他有关RESTful接口的信息来源。修改浏览器和服务器之间的数据使用REST api还可以在Backbone等前端JavaScript框架以最小的麻烦半自动理解它时获得额外的好处。

Just sayin'.