【问题标题】:PHP insert into sql with arrayPHP用数组插入sql
【发布时间】:2014-03-26 15:44:16
【问题描述】:

以下代码用于从 php run_instance 脚本中获取返回值。但是,返回的值 ($instanceIds) 是数组格式。对于 $instanceIds 数组中包含的每个值,我需要将这些值以及 userName 和 serverName 插入到单独的行中的 sql 数据库中。但是,我感到困惑的是,我不知道如何以某种方式将 $instanceIds 插入数据库,以便一次又一次地插入 userName 和 serverName 直到数组末尾。非常感谢任何帮助

<?php
session_start();
$name=mysql_real_escape_string($_SESSION['username']);

include 'mysql_connect.php';

// Select the database to use
mysql_select_db("database",$con);

// Describe the now-running instance to get the public URL
$result = $ec2Client->describeInstances(array(
    'InstanceIds' => $instanceIds,
));


$server_record = mysql_query("INSERT INTO server_tbl (userName, serverName, serverId, isRunning) VALUES ('$name', 'runtest', '$instanceIds', 'X'");

print_r($instanceIds);

?>

【问题讨论】:

  • 您必须迭代(循环)$result 的内容并为数组中的每个值发出“INSERT ...”语句
  • mysql_real_escape_string() 已弃用,您不应使用它。切换到准备好的语句。

标签: php mysql sql arrays amazon-web-services


【解决方案1】:
foreach ($instanceIds as $instanceId) {
    $server_record = mysql_query("INSERT INTO server_tbl "
        . "(userName, serverName, serverId, isRunning) "
        . "VALUES ('$name', 'runtest', '$instanceId', 'X'");
}

【讨论】:

  • 这种方法行不通。代码在没有 foreach 的情况下运行良好,但是一旦插入 foreach,它就会中断并只显示一个白屏。
  • 对不起,我输入了太多的连接符号。我修正了我的答案
  • 它有效,它只是将 $instanceID 作为“数组”插入有什么想法吗?
  • 没关系。弄清楚了。再次感谢您的帮助。
  • 出了什么问题?也许我应该再次更新我的答案。
【解决方案2】:
  1. 你真的,真的不应该使用 mysql_real_escape_string() 或 mysql_query() 或任何 mysql 函数。它们已被弃用、不安全,并且将来会从 PHP 中删除,从而破坏您的整个应用程序。请改用mysqliPDO,以免为您和您的用户带来很多麻烦。

  2. 使用 foreach 循环遍历数组。

    foreach ($instanceIds as $id){
        $sql = "INSERT INTO server_tbl (userName, serverName, serverId, isRunning) VALUES ('$name', 'runtest', '$id', 'X')";
    
        //do your insert here with the above SQL statement, depending on whether you use mysqli or PDO
    

【讨论】:

    猜你喜欢
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多