【问题标题】:javascript variable to php and then to database [closed]javascript变量到php然后到数据库[关闭]
【发布时间】:2020-05-10 03:41:32
【问题描述】:

我有一个带有一些值的 javascript 变量。我必须将此变量保存在 PHP 中,然后保存到 sql 数据库中。在 PHP 和 script 标签中使用什么代码来实现这一点?

【问题讨论】:

标签: javascript php sql database


【解决方案1】:

使用应该使用 ajax 来完成这个任务。

使用以下代码-

你的 javascript-

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    //code goes here ...
    //console.log("Request Sent");
    //console.log(this.responseText);
  }
  xhttp.open("GET", "js_to_php.php?foo=bar&bar=foo", true); //edit this according to your variables
  xhttp.send();
}

您的 php 文件(例如 - js_to_php.php)-

<?php
if(isset($_GET['bar'])){    // this is to avoid errors if variable is not set
    $foo = $_GET['foo'];
    //echo "Got foo";         //this is optional, can be used to validate response
}
else{
    echo "Error: did not get foo"
}
if(isset($_GET['bar'])){    // this is to avoid errors if variable is not set
    $bar = $_GET['bar']
    //echo "Got bar";       //this is optional, can be used to validate response
}
else{
    echo "Error: did not get bar"
}

//Now you can call the query to the database
//Your code goes here...
?>

这样做是- javascript 向包含您的数据的 php 页面发送一个 get 请求。 php 脚本将该数据存储为一个变量,供以后使用。

注意:不要忘记在将数据传递到数据库之前对其进行清理,因为此代码对 sql 注入是不安全的!

您可以使用PDOmysqli_real_escape_string 清理数据

防止 SQL 注入的指南 -> https://www.esecurityplanet.com/threats/how-to-prevent-sql-injection-attacks.html

【讨论】:

  • 因为这是一个 php 新手,我会建议您提到的内容,除了不关注 sql 注入漏洞。当您开始编码时,这些概念可能会变得难以掌握。我将从“易受攻击的”代码开始,然后在基本代码工作后将其包装在经过清理的数据函数和准备好的语句中。
【解决方案2】:

我认为当今最典型的方法是拥有一个 API。

创建一个表单 -> 提交这个表单时在你的 API 中调用一个端点 -> 在 PHP 中使用 $_POST 或 $_GET 等全局变量捕获值 -> 然后你应该使用 PHP 对你的数据库进行插入查询.它可能看起来像这样:

INSERT INTO tableName VALUES ('yourValue')

我不是 PHP 和 SQL 数据库方面的专家,但希望您能发现我的回答对您有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 2013-05-18
    • 1970-01-01
    相关资源
    最近更新 更多