Best approach to add records into DB using php/ajax/mysql?

房东的猫 提交于 2019-12-24 03:23:06

问题


Wondering if someone can suggest a better approach to the current method I have of integrating php/js/mysql.

I use this method just fine for returning sample data, setting a unique value, etc, and it works just fine (with various authentication methods to slow an attack attempt). However, I want to now add relatively large amount of data and wondering if there is a better method?

Currently I do this:

JS

$.ajax( {
    type : "GET",
    url : "_dbGetSomeData",
    dataType : "html",
    success: function(data) {
        parseData(data);
    }
});

PHP

<?php 
include '_common.php'; 
include '_auth.php';

$INPUT_EMAIL= mysql_real_escape_string($_GET["e"]);
$INPUT_FINGERPRINT = $_SESSION[SESH_VAR_NAME];

//--- Do some SQL stuff in the DB
?>

This works fine for a one-off request for data or setting one value, but can I use this method to save more data? I don't really want to start messing about with a huge querystring posts to the _db PHP file.


回答1:


Here's an example of how you should do Ajax requests with jQuery/PHP/MySQL

JS

var postData = {
    first_name: 'Foo',
    last_name: 'Bar',
    phone: '1-555-432-1234'
};

$.post('path/to/ajax/url.php', postData)
 .done(function(response) {
    alert("Data Loaded: " + response);
 });

PHP

// Connect to MySQL
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

// We want do some validation on the data so we can make a function called
// `validate()` if you want.
$data = validate($_POST);

$stmt = $dbh->('INSERT INTO my_table (first_name, last_name, phone) 
    VALUES (:first_name, :last_name, :phone)');

$stmt->execute($data); 


来源:https://stackoverflow.com/questions/12027105/best-approach-to-add-records-into-db-using-php-ajax-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!