sql >> Database teknologi >  >> RDS >> Mysql

Indsættelse i MySQL fra PHP (jQuery/AJAX)

Hej her er bare et hurtigt eksempel på hvordan man kan gøre det:

HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>Quick JQuery Ajax Request</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <!-- include the jquery lib -->
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            var ajaxSubmit = function(formEl) {
                // fetch where we want to submit the form to
                var url = $(formEl).attr('action');

                // fetch the data for the form
                var data = $(formEl).serializeArray();

                // setup the ajax request
                $.ajax({
                    url: url,
                    data: data,
                    dataType: 'json',
                    success: function() {
                        if(rsp.success) {
                            alert('form has been posted successfully');
                        }
                    }
                });

                // return false so the form does not actually
                // submit to the page
                return false;
            }
        </script>

    </head>
    <body>

        <form method="post" action="process.php"
              onSubmit="return ajaxSubmit(this);">
            Value: <input type="text" name="my_value" />
            <input type="submit" name="form_submit" value="Go" />
        </form>

    </body>
</html>

Process.php scriptet:

<?php

function post($key) {
    if (isset($_POST[$key]))
        return $_POST[$key];
    return false;
}

// setup the database connect
$cxn = mysql_connect('localhost', 'username_goes_here', 'password_goes_here');
if (!$cxn)
    exit;
mysql_select_db('your_database_name', $cxn);

// check if we can get hold of the form field
if (!post('my_value'))
    exit;

// let make sure we escape the data
$val = mysql_real_escape_string(post('my_value'), $cxn);

// lets setup our insert query
$sql = sprintf("INSERT INTO %s (column_name_goes_here) VALUES '%s';",
                'table_name_goes_here',
                $val
);

// lets run our query
$result = mysql_query($sql, $cxn);

// setup our response "object"
$resp = new stdClass();
$resp->success = false;
if($result) {
    $resp->success = true;
}

print json_encode($resp);
?>

Bemærk venligst, at intet af dette er blevet testet. Jeg håber, det hjælper dig.



  1. IntentService fryser min applikations-UI

  2. Løsninger til INSERT OR UPDATE på SQL Server

  3. Oracle 9i, Oracle 10g og Oracle 11g Developer Suite Selvstudie til formularer og rapporter

  4. Skæring af flere arrays i PostgreSQL