dpt62283 2017-04-06 17: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

  1. $cameArray = $_POST['cameArray'];
  2. 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,

  1. $cameArray = $_POST['cameArray']; //then $cameArray is sentArray
  2. 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-06 17:42
    关注

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

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

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

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部