【问题标题】:Mysql select and insert using prepared statementMysql使用准备好的语句选择和插入
【发布时间】:2013-02-05 12:40:33
【问题描述】:

我的 mysql 查询工作正常

INSERT INTO donor_location (pc_id)
SELECT id
FROM pc
WHERE postcode= ?

即从邮政编码表中获取邮政编码 id,然后将该 id 插入到donor_location 表中。 我正在使用 mysqli 和准备好的语句

如果没有选择部分,它会很容易 - 类似于

$stmt = $mysqli->prepare("INSERT INTO donor_charity(
id) values (?)") ;

但是我完全不知道如何合并选择

【问题讨论】:

    标签: mysql sql select insert


    【解决方案1】:

    您所做的几乎相同,只是更改了查询位。
    要从charity_donor 中选择id 为25 的所有记录,您可以执行以下查询:

    SELECT *
    FROM   donor_charity
    WHERE  id = 25
    

    现在要查询这个,首先你必须准备它:

    $stmt = $mysqli->prepare("
        SELECT *
        FROM   donor_charity
        WHERE  id = ?
    ");
    

    现在要遍历结果,您必须绑定参数并执行查询。

    $stmt->bind_param('d', 25 ); // First param means the type of the value you're 
                                 passing. In this example, d for digit.
    $stmt->execute();
    

    然后你设置一个数组来保存查询返回的数据,

    $row = array();
    stmt_bind_assoc($stmt, $row);
    

    现在循环返回的数据。

    while ( $stmt->fetch () ) {
        print_r($row); // Should now contain the column.
    }
    

    有关文档,请参阅:
    准备:http://www.php.net/manual/en/mysqli.prepare.php
    绑定参数:http://www.php.net/manual/en/mysqli-stmt.bind-param.php
    执行:http://www.php.net/manual/en/mysqli-stmt.execute.php
    获取:http://www.php.net/manual/en/mysqli-stmt.fetch.php

    【讨论】:

      【解决方案2】:

      您需要在 Prepare 语句之后使用 Bind_param。

      $sql = "INSERT INTO donor_charity(
      id) values (?)
             ";
      /* create a prepared statement */
      if (!$stmt = $db->prepare($sql)) {
          echo 'Database prepare error';
          exit;
      }
      
       /* bind parameters for markers */
      $stmt->bind_param('ssssss', $id);
      
      $id = '123456';
      
       /* execute query */
      $stmt->execute();
      

      【讨论】:

        【解决方案3】:

        希望这篇文章对您有所帮助,它是如此简单。 http://www.java2s.com/Code/Java/Database-SQL-JDBC/InsertRecordsUsingPreparedStatement.htm

        【讨论】:

          猜你喜欢
          • 2015-02-26
          • 2016-09-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-02
          • 2017-05-23
          • 2016-03-07
          相关资源
          最近更新 更多