php:使用ajax插入数据库

时间:2022-09-26 08:47:43

actually working on Ubuntu (working PHP language), I have a PDF file that I convert into text, then I preg_match in order to extract the data I need.

实际上在Ubuntu(工作的PHP语言)上工作,我有一个PDF文件,我将它转换成文本,然后我preg_match以提取我需要的数据。

After this, I put my data lines into a drop-down list.

在此之后,我将数据行放入一个下拉列表。

PROBLEM : I want, using Ajax (as far as I understood), to get the selected option and save it into my database.

问题:我想使用Ajax(据我所知)获取所选的选项并将其保存到我的数据库中。

I've read many topic about this issue, in vain...

我读过很多关于这个问题的话题,但都是徒劳。

Here's a piece of my code, it may be more concret !

这是我的一段代码,它可能更具体!

My PHP File :

我的PHP文件:

$file = fopen($fichier_txt, 'r+');

if ($file)
{
    $lines = array();
    $pattern_GC = '/N°.*\d{4}(\s?\s?[\w\s]*)(\d{5})\s?(\w+)\W+/isU';
    $fichier_txt_content = file_get_contents($fichier_txt);
    $regex_GC = preg_match_all($pattern_GC, $fichier_txt_content, $match_GC);
// Match regroupant nom/prenom + adresse
$match_un = explode(PHP_EOL, $match_GC[1][0]);
$match_nom_prenom = $match_un[2];
$match_adresse = $match_un[3];
// Match CP
$match_deux = $match_GC[2][0];
// Match ville
$match_trois = $match_GC[3][0];

$opt = array($match_nom_prenom, $match_adresse, $match_deux, $match_trois);
$i = 0;?>
<html>
        <form>
            <select name="selectBox" class="drop" id="Combobox1" onchange="saveToDatabase(this.value)">
            <?php foreach($opt as $val) {?>
                <option value="$opt[$i]"><?=$val?></option>
            <?php } ?>
            </select>
        </form>
</html>

My formulaire_2_test.php file :

我的formulaire_2_test。php文件:

<?php
    // Database connection to save form lines (PDO)
            try
            {
                $PDO = new PDO('mysql:host=localhost;dbname=autofill_data', 'root', 'password');
            }
            catch (Exception $e)
            {
                die('Erreur : ' . $e->getMessage());
            }

        // Get selected option and save into database
            $selectedOpt = $_POST['selected'];
            //exit($selectedOpt); --> I put this line in comments since I don't use it everytime.


            $req = $PDO->prepare("INSERT INTO data_lines(idDistributeur, numLigne, libelle) VALUES(1, 2, :selectedOpt)");
            $req->bindParam(':selectedOpt', $selectedOpt);
            $req->execute($selectedOpt);
            $data = $req->fetchAll();
        }

    ?>

And now here is my Ajax script (i'm new in JS and I know some enormeous mistakes may pop in front of you, sorry about that, and about my french naming...)

现在这是我的Ajax脚本(我是JS的新手,我知道有些错误可能会出现在你面前,抱歉,我的法语名字…)

Ajax : (located in my php file)

Ajax:(位于我的php文件中)

<style>
    .ui-autocomplete
    {
        cursor:pointer;
        height:120px;
        overflow-y:scroll;
    }
</style>

<script>

    function saveToDatabase(selectedValue)
    {
        var select = selectedValue;
        select = $(this).serialize();
        $('#Combobox1').on("change", function ()
        {
            // POST to php script
            $.ajax
            ({
                type: 'POST',
                url: 'formulaire_2_test.php',
                data:{selected:this.value}
            }).then(function(data){alert(data)});
        });
    }

    $(document).ready(function()
    {
        saveToDatabase();
    });

</script>

I tested my PDO connection with rough values, and it does work, but I wonder how I could pass my php variable into it (I'm not sure about using $_POST to retrieve this data since I don't refresh any page...) I also tried with INSERT into table VALUES(:name, 2, 3) but it didn't work either... Am I heading in the right direction ? How would you consider doing this ?

我用粗略的值测试了PDO连接,它确实有效,但是我想知道如何将php变量传递给它(我不确定是否要使用$_POST来检索数据,因为我不刷新任何页面…)我还尝试了插入到表值(:name, 2,3)中,但它也不起作用……我的方向对吗?你会怎么考虑?

PS : My next step after this would be to remove the selected option from the following dropdown lists (in order to save the user some precious minutes as he fills a subscription form).

PS:在此之后,我的下一步将是从下面的下拉列表中删除所选的选项(以便在用户填写订阅表单时节省一些宝贵的时间)。

EDIT Nov 24th : I need my "Fais ton choix" option to appear on my dropdown as a default value, but not in the list options : php:使用ajax插入数据库

11月24日:我需要我的“Fais ton choix”选项作为默认值出现在我的下拉列表中,但不在列表选项中:

My last issue : I want to remove the selected option of the dropdown, so it won't appear in another following dropdown. Here's the code I tried (doesn't work) :

我的最后一个问题:我想删除下拉菜单的选择选项,所以它不会出现在下拉菜单中。这是我试过的代码(不管用):

function removeSelected(value)
        {
                $('.drop').change('select', function ()
                {
                    // Definition des variables
                    var value = this.value;
                    var id = this.id;
                    //  We del selects with a != id containing options with the same value of the selected one.
                    $("select:not(#" + id + ") option[value='" + value + "']").hide()
                });
        }

I also tried with .remove() instead of .hide() without success !

我还尝试了.remove()而不是.hide(),但没有成功!

Thanks in advance,

提前谢谢,

Regards,

问候,

Stelio Kontos.

Stelio Kontos。

2 个解决方案

#1


1  

Put the PHP code that follows this comment: // Database connection to save form lines (PDO) into a different file. From your jQuery ajax function, set the url to this new PHP file. Also change data: 'selected=' + select to data: {selected: select}.

将以下注释://数据库连接的PHP代码保存到另一个文件中。从jQuery ajax函数中,将url设置为这个新的PHP文件。还可以更改数据:'selected=' + select to data: {selected:}。

Now in your PHP file (the new one) set $selectedOpt = $_POST['selected'];.

现在在PHP文件中(新的)设置$selectedOpt = $_POST['selected'];

The last bit of your PHP code should look this this:

PHP代码的最后一部分应该如下所示:

$req = $PDO->prepare("INSERT INTO data_lines(idDistributeur, numLigne, libelle) VALUES(1, 2, :selectedOpt)");
$req->bindParam(':selectedOpt', $selectedOpt);
$req->execute();

Edit: javascript fixes

编辑:javascript修复

Your JS should be:

你的JS应该:

$(document).ready(function () {
    $('#Combobox1').on('change', function () {
        $.ajax({
            method: 'POST',
            url: 'save-selection.php',
            data: {
                // this is a reference to the select box, which means
                // this.value is the value of the select box
                selected: this.value
            }
        }).then(function (data) {
            alert(data);
        });
    });
});

Regarding your updated requirement, you can just add $(this).children(':selected').remove(); under your ajax call. No need for another change listener. However, when a user selected an option, it will instantly remove it so the select box will only ever show the first option. Try it and you will see what I mean.

关于您的更新需求,您可以添加$(this).children(':selected').remove();在你的ajax调用。不需要另一个更改侦听器。然而,当用户选择一个选项时,它会立即删除它,因此选择框只显示第一个选项。试试吧,你会明白我的意思的。

#2


1  

You can't directly send information from Javascript to PHP. You have to use some REST API or some HTTP webservice that manages HTTP request and then insert into your database.

您不能直接将信息从Javascript发送到PHP。您必须使用一些REST API或一些HTTP webservice来管理HTTP请求,然后将其插入到数据库中。

You can program a REST API like this and then simply use $_POST['selected'] to retrieve the parameter of the POST request you did with JQuery.

您可以编写这样的REST API,然后简单地使用$_POST['selected']来检索您使用JQuery所做的POST请求的参数。

Also, I recommend you to use minAjax

另外,我建议您使用minAjax

#1


1  

Put the PHP code that follows this comment: // Database connection to save form lines (PDO) into a different file. From your jQuery ajax function, set the url to this new PHP file. Also change data: 'selected=' + select to data: {selected: select}.

将以下注释://数据库连接的PHP代码保存到另一个文件中。从jQuery ajax函数中,将url设置为这个新的PHP文件。还可以更改数据:'selected=' + select to data: {selected:}。

Now in your PHP file (the new one) set $selectedOpt = $_POST['selected'];.

现在在PHP文件中(新的)设置$selectedOpt = $_POST['selected'];

The last bit of your PHP code should look this this:

PHP代码的最后一部分应该如下所示:

$req = $PDO->prepare("INSERT INTO data_lines(idDistributeur, numLigne, libelle) VALUES(1, 2, :selectedOpt)");
$req->bindParam(':selectedOpt', $selectedOpt);
$req->execute();

Edit: javascript fixes

编辑:javascript修复

Your JS should be:

你的JS应该:

$(document).ready(function () {
    $('#Combobox1').on('change', function () {
        $.ajax({
            method: 'POST',
            url: 'save-selection.php',
            data: {
                // this is a reference to the select box, which means
                // this.value is the value of the select box
                selected: this.value
            }
        }).then(function (data) {
            alert(data);
        });
    });
});

Regarding your updated requirement, you can just add $(this).children(':selected').remove(); under your ajax call. No need for another change listener. However, when a user selected an option, it will instantly remove it so the select box will only ever show the first option. Try it and you will see what I mean.

关于您的更新需求,您可以添加$(this).children(':selected').remove();在你的ajax调用。不需要另一个更改侦听器。然而,当用户选择一个选项时,它会立即删除它,因此选择框只显示第一个选项。试试吧,你会明白我的意思的。

#2


1  

You can't directly send information from Javascript to PHP. You have to use some REST API or some HTTP webservice that manages HTTP request and then insert into your database.

您不能直接将信息从Javascript发送到PHP。您必须使用一些REST API或一些HTTP webservice来管理HTTP请求,然后将其插入到数据库中。

You can program a REST API like this and then simply use $_POST['selected'] to retrieve the parameter of the POST request you did with JQuery.

您可以编写这样的REST API,然后简单地使用$_POST['selected']来检索您使用JQuery所做的POST请求的参数。

Also, I recommend you to use minAjax

另外,我建议您使用minAjax