简体   繁体   English

PHP使用数组插入sql

[英]PHP insert into sql with array

the following code works to grab a return value from a php run_instance script. 以下代码用于从php run_instance脚本中获取返回值。 However, the value returned ($instanceIds) is in an array format. 但是,返回的值($ instanceIds)采用数组格式。 I need to insert these values, along with the userName and serverName into an sql database in separate rows for each value that is contained within the $instanceIds array. 对于$ instanceIds数组中包含的每个值,我需要将这些值以及userName和serverName插入到单独行中的sql数据库中。 However, where I am getting confused is that I don't know how to insert the $instanceIds into the database in a way so that the userName and serverName are inserted over and over again until the end of the array. 但是,我感到困惑的是,我不知道如何以某种方式将$ instanceIds插入数据库,以便一次又一次地插入userName和serverName直到数组结束。 Any help is greatly appreciated 任何帮助是极大的赞赏

<?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);

?>
foreach ($instanceIds as $instanceId) {
    $server_record = mysql_query("INSERT INTO server_tbl "
        . "(userName, serverName, serverId, isRunning) "
        . "VALUES ('$name', 'runtest', '$instanceId', 'X'");
}
  1. You really, really should not use mysql_real_escape_string() or mysql_query() or any of the mysql functions. 你真的,真的不应该使用mysql_real_escape_string()或mysql_query()或任何mysql函数。 They are deprecated, insecure, and will be removed from PHP in the future, breaking your entire app. 它们已被弃用,不安全,并且将来会从PHP中删除,从而破坏整个应用程序。 Please save yourself and your users a lot of headache by using mysqli or PDO instead. 请使用mysqliPDO来节省您自己和用户的头痛。

  2. Use a foreach loop to iterate over the array. 使用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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM