如何将数组插入MySql数据库

时间:2017-01-18 09:34:59

标签: php mysql arrays

我有一个foreach来从我的网站上详细说明一些值,我想将它们插入到mysql数据库中。

我的问题在于我有一个阵列,因为在这种情况下我不知道如何对待它们。

这是我的代码:

   ...

$titles = $html->find("a[class=in-match]"); // 1 per match
$result = $html->find("td[class=h-text-center]/a"); // 1
$best_bets = $html->find("td[class=table-matches__odds colored]/span/span/span"); // 1
$odds = $html->find("td[class=table-matches__odds]"); // 2

function print_odd($odd) {
    if (array_key_exists('data-odd', $odd->attr)) {
        return $odd->attr['data-odd'];
    }

    return $odd->children(0)->children(0)->children(0)->attr['data-odd'];
}

$c=0; $b=0; $o=0; $z=0; // two counters
foreach ($titles as $match) {
    list($num1, $num2) = explode(':', $result[$c++]->innertext); // <- explode
    $num1 = intval($num1);
    $num2 = intval($num2);
    $num3 = ($num1 + $num2);
    if ($num3 > 1) {
        $over15 = "OK";
    } else {
        $over15 = "NO";
    }

    echo "<tr><td class='rtitle'>".
        "<td class='first-cell'>".$match->innertext."</td> ".            
        "<td>".$match->innertext."</td><td> ".$num1.'</td><td> : </td><td>'.$num2 .  " / " .  // <- example use
        "<td class='first-cell'>".$num3 ."</td> "  .
        "<td class='first-cell'>".$over15 ."</td> "  .
        "<td class='odds'>".print_odd($odds[$b++]) . ";" .
            "".print_odd($odds[$b++]) . ";" .
            "".print_odd($odds[$b++]) . "</td>" .
            "</td></tr><br/>";


    $servername = "xx.xxx.xxx.xxx";
    $username = "xxx";
    $password = "xxx";
    $dbname = "xxxxxxxx";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    $sql = "INSERT INTO risultati (titles, scorehome, scoreaway, best_bets)
    VALUES ('$match', '$num1', '$num2', '$odds');";

    if ($conn->multi_query($sql) === TRUE) {
        echo "New records created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    $conn->close();

当我跑步时,我没有得到3&#34; $赔率&#34;

感谢您的关注

编辑所以,我用我的代码保存了几乎所有数据,但我遇到了$ odds的问题(你可以看到我的函数print_odd)。怎么能救他们?

1 个答案:

答案 0 :(得分:0)

尝试这个概念......谢谢

$columns = implode(", ",array_keys($insData));
$escaped_values = array_map('mysql_real_escape_string', array_values($insData));
$values  = implode(", ", $escaped_values);
$sql = "INSERT INTO `fbdata`($columns) VALUES ($values)";