繁体   English   中英

将javascript画布路径保存到数据库的正确方法

[英]Proper way to save a javascript canvas path into a database

使用php将javascript画布路径保存到mysql数据库的正确方法是什么?

路径可能看起来像这样:

array:3 [
  0 => array:3 [
    0 => "M"
    1 => 127.83333333333
    2 => 70.486111111111
  ]
  1 => array:5 [
    0 => "Q"
    1 => 127.83333333333
    2 => 70.486111111111
    3 => 128.33333333333
    4 => 70.486111111111
  ]
  2 => array:5 [
    0 => "Q"
    1 => 128.83333333333
    2 => 70.486111111111
    3 => 129.41666666667
    4 => 70.486111111111
  ]
  3 => array:5 [
    0 => "Q"
    1 => 130
    2 => 70.486111111111
    3 => 130.83333333333
    4 => 70.486111111111
  ]
]

但是在大多数情况下更大。 此外,可以有多个路径(数组)链接到一个实体,比如说user_id 什么是在我的数据库中管理此问题的好方法。 可以序列化数据或使用json_encode ,但是我不确定这是否真的json_encode

检查序列化php函数:

https://www.php.net/manual/zh/function.serialize.php

它返回数组(字符串)的可存储表示形式,可以将其保存在数据库中。 然后在需要时可以将其反序列化。

https://www.php.net/manual/zh/function.unserialize.php

不能将数组直接存储到数据库中。

您需要转换为字符串,然后存储在数据库中。

您可以使用JSON.stringify()将数组转换为字符串,然后发送到PHP文件以存储到数据库中。 进一步了解JSON.stringify()

假设您将所有这些值存储在一些javascript数组调用canvasValues

然后使用转换数组转换为字符串JSON.stringify(canvasValues)

现在,您可以对PHP文件进行AJAX调用,这会将画布数组值保存在数据库中。 我在这里使用AXIOS来调用* PHP文件。

axios.post("yourPhpFileName.php",{
  "arrayValues": JSON.stringify(canvasValues)
})
.then(function(response){
  console.log(response);
})
.catch(function(error){
  console.error(error);
});

现在在您的PHP文件中

if($_SERVER["REQUEST_METHOD"] === "POST"){
    $userInput = json_decode(file_get_contents("php://input"), TRUE);
    $arrValues = json_decode($userInput["arrayValues"], true);

    #now user foreach() to loop around your $arrValues variable
    foreach($arrValues as $key => $values){
         #now extract your data and do whatever you want
    }

    # Before saving $arrValues in DB, convert back to string using json_encode();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM