使用数组将PHP插入sql
下面的代码用于从php run_实例脚本获取返回值。但是,返回的值($instanceId)是数组格式的。我需要为$InstanceID数组中包含的每个值分别将这些值以及用户名和服务器名插入sql数据库中的行中。然而,让我感到困惑的是,我不知道如何将$InstanceID插入数据库中,这样用户名和服务器名就会一次又一次地插入,直到数组结束。非常感谢您的帮助使用数组将PHP插入sql,php,mysql,sql,arrays,amazon-web-services,Php,Mysql,Sql,Arrays,Amazon Web Services,下面的代码用于从php run_实例脚本获取返回值。但是,返回的值($instanceId)是数组格式的。我需要为$InstanceID数组中包含的每个值分别将这些值以及用户名和服务器名插入sql数据库中的行中。然而,让我感到困惑的是,我不知道如何将$InstanceID插入数据库中,这样用户名和服务器名就会一次又一次地插入,直到数组结束。非常感谢您的帮助 <?php session_start(); $name=mysql_real_escape_string($_SESSION['us
<?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);
?>
您真的,真的不应该使用mysql\u real\u escape\u string()或mysql\u query()或任何mysql函数。它们已被弃用,不安全,将来将从PHP中删除,破坏您的整个应用程序。请使用或来代替,以免您和您的用户感到头痛
使用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
必须对$result的内容进行迭代(循环),并对数组中的每个值发出“INSERT…”语句mysql\u real\u escape\u string()
已弃用,您不应该使用它。切换到准备好的语句。这种方法不起作用。代码在没有foreach的情况下运行良好,但是一旦插入foreach,它就会中断并显示一个白色屏幕。我修正了我的答案,它是有效的,只是插入$instanceID作为“数组”有什么想法吗?没关系。我明白了。再次感谢你的帮助。有什么问题吗?也许我应该再次更新我的答案。
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