MySQL PHP插入两个表事务

时间:2014-05-24 03:12:27

标签: php mysql sql transactions

我正在尝试插入两个不同的表,它的工作没有foreach语句但我似乎无法弄清楚一旦我添加了foreach我出错了...这是SQL / PHP查询:

$con=mysqli_connect($GLOBALS['db_host'],$GLOBALS['db_name'],$GLOBALS['db_password'],$GLOBALS['db_user']);


if (!$con) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}   
mysqli_autocommit($con, FALSE);

$i = 0;
$end = count($_POST['category_id']);    
$end2 = count($_POST['benefit_id']);


$sql="INSERT INTO store_locator_category_map (id,category_id)
VALUES ";
foreach ($_POST['category_id'] as $category_id) {
        if(++$i === $end) { 
        $sql .="('".$id."', '".$category_id."');";
        } else  $sql .="('".$id."', '".$category_id."'), ";
    }           
mysqli_query($con, $sql);

$sql2="INSERT INTO store_locator_benefit_map (id,benefit_id)
VALUES ";
foreach ($_POST['benefit_id'] as $benefit_id) {
        if(++$i === $end2) { 
        $sql2 .="('".$id."', '".$benefit_id."');";
        } else  $sql2 .="('".$id."', '".$benefit_id."'), ";
    }

mysqli_query($con, $sql2);

if (!mysqli_commit($con)) {
    print("Transaction commit failed\n");
    exit();
}

mysqli_close($con);         

1 个答案:

答案 0 :(得分:0)

如果没有看到$_POST['category_id']$_POST['benefit_id']值是什么,就很难回答。但是,假设这两个变量不是以可枚举类型(例如数组)形式出现的,那么这将是调查的即时原因。

例如,假设您的$_POST['category_id']是字符串“Some sample string”,如下所示:

ubuntu@linuxbox:~$ cat test.php
<?php
$x = "Some sample string";
foreach($x as $y) {
        echo $y;
}
ubuntu@linuxbox:~$ php test.php
PHP Warning:  Invalid argument supplied for foreach() in /home/ubuntu/test.php on line 3

在针对字符串运行foreach操作的情况下,它会导致平局失败。另一种可能的解释(可能在代码示例之外解决)是在此代码示例中未分配$id

另外,作为一个值得关注的问题,我会提醒您不要使用$_POST值并使用连接生成SQL,因为您将自己暴露给SQL注入攻击。除非您明确信任请求的来源,否则请考虑使用串联之前清理输入的一些方法。

相关问题