我有这些信息,如何将其输入我的数据库?

时间:2016-12-23 13:39:25

标签: php mysqli

我想出了如何运行Arp-scan并在页面上显示结果。现在我需要将信息插入到Mysql DB中。我知道如何插入单个记录,但我很难知道如何在db中获取许多记录。似乎无法绕过它。这是我的代码

    <?php
    $link = mysqli_connect("localhost", "user", "password", "mydb");
    // Check connection
    if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
    }
    error_reporting(E_ALL);
        ini_set('display_errors', '1');
    $output = shell_exec("sudo arp-scan --interface=eth0 --localnet --numeric --          quiet| grep -e 80:82:87");
foreach (explode("\n", $output) as $host)
{
    list($ip, $mac) = array_pad(explode("\t", $host),2,null);

    echo "$ip  $mac<br>";
}
// attempt insert query execution

$sql = "INSERT INTO phones (ipadd, mac) VALUES ('$ip', '$mac')";
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}

mysqli_close($link);
?>

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

<?php

$values = array();
foreach (explode("\n", $output) as $host)
{
    list($ip, $mac) = array_pad(explode("\t", $host),2,null);
    $values[] = '("'.$ip.'", "'.$mac.'")';
}
// attempt insert query execution

$sql = "INSERT INTO phones (ipadd, mac) VALUES ".implode(',', $values);
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}

mysqli_close($link);

它将以下列格式创建一个字符串数组:

("IP", "MAC")

稍后使用逗号

连接它们
("IP", "MAC"),("IP2", "MAC2")

并添加到查询中