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!

图片转代码服务由CSDN问答提供 功能建议

UPDATE !! 我的代码实际上有效运行。 原始问题如下。 如果您仍然好奇,请阅读问题,然后返回阅读我的更新。

我的不好,数据库实际上可以在代码运行后成功更新。 我不小心将表中的数据类型设置为INT但我的初衷是varchar。

但是从HenryDev的回答我设法通过php中的post方法找到获取的数组变为STRING类型但数组类型 。 我用

  $ cameArray = $ _POST ['cameArray']; 
echo gettype($ cameArray); 
   
 
 <  p>在我的屏幕上输出“string”,因此内爆不会起作用哦(参见关于HenryDev答案的讨论)。 
 
 

然而,如果你设置了他的答案将作为一个魅力 PHP中的数组并将其内爆,它会返回一个数组的“字符串类型”!

UPDATE !! 我的代码实际上有效运行。 原始问题如下。 如果您仍然好奇,请阅读问题,然后返回阅读我的更新。

这是我原来的问题

所以我有一个非常基本的问题,但我在网上找到的教程和答案对我的情况来说有点复杂。

我有一个JS数组,如

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

我想将此数组插入 数据库作为表的一个字段。 我使用ajax将此数组发送到PHP,然后在PHP中执行查询。 例如,

  $ cameArray = $ _POST ['cameArray'];  //然后$ cameArray是sentArray 
 
mysqli_query($ con,“INSERT INTO thisTable(arrayField)VALUES($ cameArray)”); 
   
 
 

然后我 希望数据库中的值显示为“1,2,3”,但问题是数据库中的值只显示为单个“2”。 表中的类型是varchar。

没有任何JSON对象只涉及纯文本。 我怎么能这样做? 谢谢!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题