dpt62283 2017-04-07 01:23
浏览 63
已采纳

使用PHP将JS数组插入MySQL的最简单方法

UPDATE!! My code is actually valid to run. The original question is below. If you are still curious please read the question and then back to read my update.

My bad, the db actually can get updated successfully after the code runs. I accidentally set the datatype in the table as INT but my initial intention, varchar.

But from HenryDev's answer I managed to find the acquired array by post method in php becomes STRING type but array type. I used

$cameArray = $_POST['cameArray'];
echo gettype($cameArray);

to output "string" on my screen, so implode would not work oh that(see the discussions on HenryDev's answer).

However his answer will work as a charm if you set up an array in PHP and implode it, it will give you back a "string type" of your array!

UPDATE!! My code is actually valid to run. The original question is below. If you are still curious please read the question and then back to read my update.

Here is my original question

So I have a very basic question but the tutorials and answers I found online are kinda complicated for my situation.

I have a JS array like

var sentArray = ['1','2','3'];

I want to insert this array into the database as one field of a table. I use ajax to send this array to PHP and then execute the query in PHP. For instance,

$cameArray = $_POST['cameArray']; //then $cameArray is sentArray

mysqli_query($con, "INSERT INTO thisTable (arrayField) VALUES ($cameArray)");

And then I want the value in the database shown as "1, 2, 3", but the problem is the value in the database is simply shown as a single "2". The type in table is varchar.

No any JSON object involved just pure text. How could I do that? Thanks!

  • 写回答

2条回答 默认 最新

  • dongyou6909 2017-04-07 01:42
    关注

    Here's a quick solution. If you want to store the array as an string simply do this in your PHP code.

    $array = array('1', '2', '3'); // Your array  
    $cameArray = implode(",", $array);
    
    echo $cameArray; // "1,2,3"    
    

    Now you can store the variable $cameArray in your Data Base. Hope it helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?