如何调用php函数通过javascript函数更新mysql表中的数据?

0qx6xfy6  于 2021-06-15  发布在  Mysql
关注(0)|答案(3)|浏览(332)

我正在尝试使用javascript函数将数据更新到mysql数据库中。当我单击一个标签时,这个函数将调用php中的另一个函数来更新数据。如果我点击一个标签,代码就完成了。你能帮帮我吗?
我试图通过调用publicatephonephp函数在sql表phone中插入数据,但没有插入数据。这是我的密码:

**javascript函数:

function answer1yes(clicked) {

    var s = document.getElementById("answer1oui").checked;

    if (s = "true"){

    <?php include('functions.php'); ?>

    var x="<?php publicatePhone(); ?>";

    alert(x);

    return false;

    }else{

        alert('not checked');

    }
}

**文件functions.php:

<?php function publicatePhone(){

$con=mysql_connect("localhost","root","hihi51978");

mysql_select_db("script_database2");

//$publicate = "INSERT INTO phone (phone_number, publicate_number) VALUES 
('212661132084', 'yes')";

$publicate = "UPDATE phone SET publicate_number = 'yes' WHERE 

phone_number='212661132084'";

$publicate_result = mysql_query($publicate);

if ($publicate_result==true){echo 'request executed successfelly';} 

else {echo 'request not executed';}

}

?>

**形式:

<div id="answer1"style="margin: 20%;">

Show my phone number on website's result:

<form action="<?php $_SERVER['PHP_SELF'];?>" method="post" />

<p><label name="labelyes" style="background-color: #035d54; padding: 6px 

30px 6px 30px; border-radius: 35px;" onclick="Javascript:answer1yes()" > 

<input style="display: none;" type="radio" id="answer1oui" name="question1"

value="yes">Yes</label><p>

</form>

</div>

代码显示“request executed successfelly”,但请求没有更新我的电话表

ssm49v7z

ssm49v7z1#

好吧,我就是这么想的:
表单.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="form.js"></script>
    <title>Form</title>
</head>
<body>
    <div id="answer1" style="margin: 20%;">
        Show my phone number on website's result:
        <!-- You only need a "post" and "action" attribute when you are -->
        <!-- submitting this form with an: <input type="submit" value=""> -->
        <form>
            <button onclick="showPhoneNumberOnResults(true)">yes</button>
            <button onclick="showPhoneNumberOnResults(false)">no</button>
        </form>
</body>
</html>

表单.js:

function showPhoneNumberOnResults(answer) {
    if (answer) {
        alert('Show number');
        $.ajax({
            type: 'POST',
            url: 'process_answer',
            data: { answer: answer },
            success: (date) => console.log(data),
            error: (xhr, status, error) => console.error(xhr.responseText)
        });
    } else {
        alert('Don\'t show number');
    }
}

这个(参数)=>{statements}东西叫做“lambda expression”,它只是编写函数的一种简短形式。
process\u answer.php:

<?php

require_once 'database_connect.php';

$dbConnection->query(/* insert your UPDATE statement */);

数据库\u connect.php:

<?php

$HOST = 'localhost';
$DATABASE = 'script_database2';
$USER = 'root';
$PASSWORD = 'hihi51978';

try {
    $dbConnection = new PDO('mysql:host='.$HOST.';dbname='.$DATABASE, $USER, $PASSWORD);
    // set the PDO error mode to exception
    $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

我用的是pdo。它只是提供了一个接口,您可以在其中使用各种不同的数据库,而不仅仅是mysql。您可以在此处阅读更多信息:http://php.net/manual/en/intro.pdo.php.
是的,顺便说一句,我认为你想用的词是“发布”而不是“发布”。:p
圣诞问候。

zte4gxcn

zte4gxcn2#

所以,您的问题是$publicate\u result看起来是真的,但是它没有正确地更新sql表(或者根本没有更新)?
如果是这样的话:$publicate\u result的实际值是多少?可能它有一个错误值,php类型将其转换为true,因为变量不是空的。
当你回显变量$publicate\u结果时,它会说什么?
(你可以试试

echo var_dump($publicate_result);

获取有关变量值的更多信息)

0dxa2lsx

0dxa2lsx3#

我的意思是,我认为通过javascript调用php函数最常见的做法是使用xmlhttprequests,这也是我的建议。
工作原理如下:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
       document.getElementById("demo").innerHTML = xhttp.responseText;
    }
};
xhttp.open("GET", "filename", true);
xhttp.send();

资料来源:https://www.w3schools.com/xml/xml_http.asp
当然,如果您想使用jquery(我建议在使用xmlhttprequests时使用jquery),执行xmlhttprequest的语法要简单得多:

$.ajax({
    type: 'POST',
    url: 'yourfile.php',
    data: {
        // someData
    },
    success: (data) => {
        // Code that will be executed after a successful
        // finish of the request

        // data: stuff that was echoed in PHP
    },
    error: (xhr, status, error) => {
        // Code that will be executed after a non successful
        // finish of the request

        // This line will display an error to your console,
        // which holds the PHP-error-code
        console.error(xhr.responseText);
    }
});

资料来源:https://jquery.com/
请注意,当您执行xmlhttp或ajax请求(简单来说基本相同)时,它是异步的,这意味着$.ajax()命令之后的代码将立即执行,即使请求尚未完成。
因此,如果希望在请求完成后立即执行代码,则必须将代码放在success或error回调函数中。
如果您想在您的案例中看到如何使用ajax请求的更具体的示例,请询问。
谨致问候

相关问题