본문 바로가기
MySql

MySQL PHP (jQuery / AJAX)에서 MySQL에 삽입

by 베이스 공부 2020. 10. 16.
반응형

나는 많은 튜토리얼을 보았지만 너무 혼란스럽고 내가하고 싶은 일을하기 위해 그 튜토리얼에서 기존의 것들을 사용하는 방법을 얻지 못하고 내가 원하는 방식으로 작동하게 만든다.

텍스트 상자, 레이블 및 제출 버튼이 포함 된 매우 간단한 양식이 있습니다. 사용자가 양식에 무언가를 입력하고 제출을 클릭하면 php와 ajax (jquery 포함)를 사용하여 양식 결과를 mysql 데이터베이스에 삽입하고 싶습니다.

누군가 이것이 어떻게 이루어질 수 있는지 보여줄 수 있습니까? 아주 기본적인 것이 내가 시작하는 데 필요한 전부입니다. 도움을 주시면 감사하겠습니다.

감사합니다

 

해결 방법

 

안녕하세요, 어떻게 할 수 있는지에 대한 간단한 예입니다.

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 스크립트 :

<?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);
?>

이 중 어느 것도 테스트되지 않았습니다. 당신에게 도움이되기를 바랍니다.

 

참조 페이지 https://stackoverflow.com/questions/5143191

 

 

반응형

댓글