【问题标题】:INSERT through SELECT data from another table with additional manual data PHP SQL通过从另一个表中插入额外的手动数据 PHP SQL 的 SELECT 数据
【发布时间】:2021-09-01 22:01:26
【问题描述】:

我正在尝试从另一个表中插入数据,它不起作用我阅读了 StackOverflow 和 w3school 上的所有线程,但基于它我的 SQL 不起作用。 我正在尝试将表中可用的所有数据一一插入pincode WHERE state = US 我认为我的代码是正确的,但它没有插入数据。我从pincode table 和其他人中选择了大约三个列,因为我在 PHP 的执行数组中手动​​分配了参数

请帮忙,我如何将数据从pincode 插入到table_alloted

请帮忙..

表格 = 密码

ID pin_code district state
1 123456 distname1 US
2 123457 distname2 US
3 123458 distname3 US
4 123459 distname4 US

table = table_alloted

ID pin_code district state tech_id insert_dt
1 123456 distname1 US ts12563 17-06-2021
2 123457 distname2 US ts12563 17-06-2021
3 123458 distname3 US ts12563 17-06-2021
4 123459 distname4 US ts12563 17-06-2021

代码:

$sqlInsert= $con->prepare("INSERT INTO `table_alloted` (`tech_id `, `insert_dt`, `pin_code`, `district`, `state`) VALUES(:tech_id, :my_date, (SELECT `pin_code`, `district`, `state` FROM `pincode` WHERE `state` = :state)");
$sqlInsert->execute(array(
  ':tech_id' => 'ts12563',
  ':my_date' => date('d-m-Y'),
  ':state' => 'US'
));

【问题讨论】:

标签: php mysql sql select insert


【解决方案1】:

使用下面的查询

INSERT INTO `table_alloted` (`tech_id `, `insert_dt`, `pin_code`, `district`, `state`)
SELECT :tech_id, :my_date, `pin_code`, `district`, `state` FROM `pincode` WHERE `state` = :state

我不确定您在 PHP 中的语法,但在数据库中,上述查询会起作用。

【讨论】:

    【解决方案2】:

    根据@Amit Verma 查询的PHP代码如下:

    //Prepare statement
    $sqlInsert = $con->prepare(
        "INSERT INTO `table_alloted` (`tech_id`, `insert_dt`, `pin_code`, `district`, `state`) 
        SELECT :tech_id, :my_date, `pin_code`, `district`, `state` FROM `pincode` WHERE `state` = :state"
    );
    //Execute insert
    $sqlInsert->execute([
        ":tech_id" => "ts12563",
        ":my_date" => date("Y-m-d"),
        ":state" => "US",
    ]);
    //Check result
    $query = "SELECT * FROM `table_alloted`;";
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    print_r($rows);
    

    PHP & MySQL online playground

    【讨论】:

      猜你喜欢
      • 2019-07-18
      • 2012-11-25
      • 2022-01-12
      • 1970-01-01
      • 2023-03-17
      • 2011-11-27
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      相关资源
      最近更新 更多