使用PHP阵列将数据插入到MYSQL [英] insert data into MYSQL using PHP array

查看:111
本文介绍了使用PHP阵列将数据插入到MYSQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

喜我尝试插入使用数组中的MySQL数据,可以有人请看看我的code,我似乎无法使其工作。

hi im trying to insert data in mysql using array, can someone please look at my code, i cant seem to make it work.

这是我的post.php中

this is my post.php

/* POST.PHP */
$post_id = somefunction();
$title = $_POST['title'];
$body = $_POST['body'];

$myarray = array('','$title','$body','$rowId');
insertToDB($myarray);

这是我的function.php里

and this is inside my function.php

function insertToDB($myArray) {
    $db = dbConnect(); 
    $query = "INSERT INTO `posts`(`id`, `title`, `body`, `post_id`) VALUES ";
    $valuesArr = $array();

foreach($myarray as $row) {
         $id = (int)$row[0]; // as my primary, auto increment
         $title = mysql_real_escape_string($row[1]);
         $body = mysql_real_escape_string($row[2]);
         $post_id = (int)$row[3];

         $valuesArr[] = "(`id`, `title`, `body`, `post_id`)";
         }

         $sql .=implode(',', $valuesArr);
         $db->query($sql);
}

请注意,我的的$ id =(int)的$行[0]; 是主要的,自动递增

please note that my $id = (int)$row[0]; is primary and auto increment.

推荐答案

用钥匙和值构建阵列

$myarray = array("id"=>'',"title"=>$title,"body"=>$body,"pid"=>$rowId);

和使用 PDO 而不是的mysql _ * 函数(德preciated)。

and Use PDO instead of mysql_* functions (depreciated).

$sql=$dbh->prepare("INSERT INTO `posts`(`id`, `title`, `body`, `post_id`) VALUES (:id,:title,:body,:pid)");
foreach($myarray as $row=>$value){
 $sql->bindValue(":".$row,$value);
}
$sql->execute();

更多关于 PDO HTTP:// WWW .php.net /手动/ EN / book.pdo.php

这篇关于使用PHP阵列将数据插入到MYSQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆