Php 将数组插入MySQL数据库(意外的T_字符串)
我尝试将数组中的值添加到DB中,尝试了许多variuos示例,但仍然没有成功。通过其他方法,我可以只在DB中插入最后一个数组值。。任何帮助都将不胜感激Php 将数组插入MySQL数据库(意外的T_字符串),php,mysql,arrays,Php,Mysql,Arrays,我尝试将数组中的值添加到DB中,尝试了许多variuos示例,但仍然没有成功。通过其他方法,我可以只在DB中插入最后一个数组值。。任何帮助都将不胜感激 $max=count($_SESSION['cart']); for($i=0;$i<$max;$i++){ $pid=$_SESSION['cart'][$i]['productid']; $ppid=get_product_id($pid); $ppav=get_product_name($pid); $price=get_price(
$max=count($_SESSION['cart']);
for($i=0;$i<$max;$i++){
$pid=$_SESSION['cart'][$i]['productid'];
$ppid=get_product_id($pid);
$ppav=get_product_name($pid);
$price=get_price($pid);
$date=date('Y-m-d');
$orderid=mysql_insert_id();
$customerid=mysql_insert_id();
$array['cust_id'] = $customerid;
$array['prod_id'] = $ppid;
$array['prod_name'] = $ppav;
$array['price'] = $price;
$array['date'] = $date;
$sql1 = array();
foreach( $array as $row ) {
$sql1[] = '('null', '.$row['cust_id'].', '.$row['prod_id'].', '.$row['prod_name']', '.$row['price'].', '.$row['date'].')';
}
mysql_query('INSERT INTO orders (id, cust_id, prod_id, prod_name, price, date) VALUES '.implode(',', $sql1));
}
$max=count($\会话['cart']);
对于($i=0;$i)
应该是
$sql1[] = "(null, '" . $row['cust_id'] . "', '" . etc....
您正在生成错误的PHP字符串,导致语法错误。请注意,此代码易受SQL注入的攻击。即使此数据最初似乎来自数据库,您仍然可以自己注入。在$sql1语句中不需要“for null”:
尝试:
正如Daniel A.White指出的,您的代码非常容易受到SQL注入的影响,但下面是您提供的代码的一个工作版本:
<?php
$max = count($_SESSION['cart']);
for($i = 0; $i < $max; $i++) {
$pid = $_SESSION['cart'][$i]['productid'];
$ppid = get_product_id($pid);
$ppav = get_product_name($pid);
$price = get_price($pid);
$date = date('Y-m-d');
$orderid = mysql_insert_id();
$customerid = mysql_insert_id();
$array['cust_id'] = $customerid;
$array['prod_id'] = $ppid;
$array['prod_name'] = $ppav;
$array['price'] = $price;
$array['date'] = $date;
$sql1 = array();
foreach($array as $row) {
$sql1[] = '(NULL, '.$row['cust_id'].', '.$row['prod_id'].', "'.$row['prod_name'].'", ' . $row['price'] . ', "' . $row['date'] . '")';
}
mysql_query('INSERT INTO orders (id, cust_id, prod_id, prod_name, price, date) VALUES ' . implode(',',$sql1));
}
?>
此外,我建议您使用一个像样的代码编辑器(我使用的是免费的版本更好的编辑器),或者至少使用一个带有错误突出显示的编辑器,以防止类似的常见错误。警告您的代码非常容易受到sql注入攻击。您的错误在这里顺便说一句:$sql1[]='('null',
您好,我知道,我会在这之后马上解决sql注入问题。谢谢
$sql1[] = '(null, '.$row['cust_id'] ...
<?php
$max = count($_SESSION['cart']);
for($i = 0; $i < $max; $i++) {
$pid = $_SESSION['cart'][$i]['productid'];
$ppid = get_product_id($pid);
$ppav = get_product_name($pid);
$price = get_price($pid);
$date = date('Y-m-d');
$orderid = mysql_insert_id();
$customerid = mysql_insert_id();
$array['cust_id'] = $customerid;
$array['prod_id'] = $ppid;
$array['prod_name'] = $ppav;
$array['price'] = $price;
$array['date'] = $date;
$sql1 = array();
foreach($array as $row) {
$sql1[] = '(NULL, '.$row['cust_id'].', '.$row['prod_id'].', "'.$row['prod_name'].'", ' . $row['price'] . ', "' . $row['date'] . '")';
}
mysql_query('INSERT INTO orders (id, cust_id, prod_id, prod_name, price, date) VALUES ' . implode(',',$sql1));
}
?>