【问题标题】:Inserting values of array into MYSQL将数组的值插入MYSQL
【发布时间】:2013-07-15 12:11:53
【问题描述】:

我有一个文本文件,我将谁的值放入数组中, 这是php代码:

<?php
    $homepage = file_get_contents('hourlydump.txt');
    $x = explode('|', $homepage);
    $desc = array();
    $cat = array();
    $link = array();
    $m = 1;
    $n = 2;
    $p = 3;

    for ($i = 1; $i <= count($x) / 4; $i++) {
       $m = $m + 4;
       $desc[] = $x[$m];
       $n = $n + 4;
       $cat[] = $x[$n];
       $p = $p + 4;
       if ($x[$p])
          $link[] = $x[$p];
    }
    echo "<pre>";
    print_r($desc);
    print_r($cat);
    print_r($link);
?>

输出如下:

Array
(
    [0] => Kamal Heer - Facebook Official Video 720p Dual Audio [Hindi + Punjabi]76 mb by rANA.mkv
    [1] => 50 HD Game Wallpapers Pack- 1
)
Array
(
    [0] => Movies
    [1] => Other
)
Array
(
    [0] => http://kickass.to/kamal-heer-facebook-official-video-720p-dual-audio-hindi-punjabi-76-mb-by-rana-mkv-t7613070.html
    [1] => http://kickass.to/50-hd-game-wallpapers-pack-1-t7613071.html
)
//
//
//

请大家帮帮我,我不知道如何插入这三个数组 $desc、$cat 和 $link 的值 进入mysql表,列名为description,category,link

我知道简单的插入查询,但不知道如何处理这些数组。

【问题讨论】:

标签: php mysql arrays


【解决方案1】:

我将举一个例子说明如何建立基本的数据库连接并完成插入,这仅用于说明目的。您应该在一个类中重新组织此代码,以便每个插入语句都不会创建 PDO 对象,而是重新使用之前创建的对象。

 function insertItem($desc, $cat, $link) {
    $dbh = new PDO("mysql:host=host;dbname=db", $user, $pass);
    $sql = "INSERT INTO table (description, category, link) VALUES (:desc, :cat, :link)";

    $sth = $dbh->prepare($sql);
    $sth->bindValue(":desc", $desc);
    $sth->bindValue(":cat", $cat);        
    $sth->bindValue(":link", $link);
    $sth->execute();
  }

【讨论】:

  • +1 因为不易受到 SQL 注入的攻击。
【解决方案2】:

您可以使用 for 语句。

 for($x =0, $num = count($desc); $x < $num; $x++){
     // build you query 
     $sql = "INSERT into your_table (description, category, link) values ".
            "(".$db->quote($desc[$x]).",".$db->quote($cat[$x]).",".
                $db->quote($link[$x].")";
     $db->query($sql);
 }

当然,您必须使用适合您选择的数据库 api 的清理/引用方法。

【讨论】:

    【解决方案3】:

    将数组变成字符串

    $description = json_encode($desc);
    $category = json_encode($cat);
    $link = json_encode($link);
    

    然后将这些值插入数据库

    获取时

    使用json_decode再次从字符串中获取数组

    【讨论】:

      【解决方案4】:

      试试这个。我假设只有这些值可以插入

      for($i = 0;$i<2;$++) {
      mysqli_query("INSER INTO tablename values(description,category,link) VALUES('$desc[$i]'
      ,'$cat[$i]','$link[$i]')");
      }
      

      【讨论】:

        【解决方案5】:

        这是一个简单的示例,用于从您检索文件的网站按原样读取文件,并将其插入数据库以清理数据:

        <?php
        // fill with your data
        $db_host = 'localhost';
        $db_user = '';
        $db_pass = '';
        $db_name = '';
        $db_table = 'myTable';
        
        $file = "hourlydump.txt.gz";
        if($filehandle = gzopen($file, "r"))
        {
            $content = gzread($filehandle, filesize($file));
            gzclose($file);
        }
        else
            die('Could not read the file: ' . $file);
        
        $con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
        if($con->connect_error)
            die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
        
        $sql = "INSERT INTO $db_table (description, category, link) VALUES (?, ?, ?)";
        if (!$insert = $con->prepare($sql))
            die('Query failed: (' . $con->errno . ') ' . $con->error);
        
        foreach (explode("\n", $content) as $line)
        {
            list($md5hash,$desc,$cat,$link,$torrent) = explode("|", $line);
            if (!$insert->bind_param('sss',$desc,$cat,$link))
                echo 'Binding parameters failed: (', $insert->errno, ') ', $insert->error;
        
            if (!$insert->execute())
                echo 'Insert Error ', $insert->error;
        }
        
        $insert->close();
        $con->close();
        

        注意:您可能需要检查文件是否已成功加载,是否存在来自爆炸的字段以防止进一步的问题,但通常这应该可以正常工作。

        此外,您可能希望更改 $sql 以反映您的 MySQL 表以及顶部的 $db_table

        更新:插入所有值更改此:

        $sql = "INSERT INTO $db_table (description, category, link) VALUES (?, ?, ?)";
        

        收件人:

        $sql = "INSERT INTO $db_table (md5, description, category, link, torrent) VALUES (?, ?, ?, ? ,?)";
        

        还有这个:

        if (!$insert->bind_param('sss',$desc,$cat,$link))
        

        收件人:

        if (!$insert->bind_param('sssss',$md5hash,$desc,$cat,$link,$torrent))
        

        注意s 上方的每个项目你需要一个s 你有 5 个项目所以 5 s 的 S 表示字符串,D 双精度,I 整数,B blob you can read more at about it here.

        还要注意$sql,我们将在bind_param 上使用每个项目,我们有一个?

        【讨论】:

        • 还有一件事...此代码工作正常...用于插入这三个值...但是当我尝试插入所有五个值时...它显示为查询错误失败:(1136)列计数与第 1 行的值计数不匹配有什么想法...?
        • 我试过了,但它说...插入错误列'torrent'不能为空
        • @YugeshMLuv 这意味着您文件上的行没有种子值。它不会停止插入其他结果,如果字段不存在,它只会跳到下一个结果。在list($md5hash,$desc,$cat,$link,$torrent) = explode("|", $line); 行之后添加此echo $desc, " - ", $torrent, "\n";,您将知道它在哪里没有$torrent 值,并且还会看到进度。
        • 非常感谢....我在我的数据库中启用了空值...并且它工作得很好...:)
        • 嘿...我遇到了另一个问题....上面的查询可以完美地处理少量数据...但是当我尝试处理大量数据时..它给我带来了麻烦..它将数据插入到第2461行...之后它停止...我尝试删除该行以查看它是否有一些有问题的数据...然后它在第2462行之后停止...你知道怎么了...?我试图改变最大执行时间和最大允许数据包数据没有真正起作用......问题仍然存在......
        【解决方案6】:

        您可以在进行计算时构建查询:

        $query = "INSERT INTO `table` (`description`, `category`, `link`) VALUES ";
        for ($i = 1; $i <= count($x) / 4; $i++) {
           $m = $m + 4;
           $query .= "('".$x[$m];
           $n = $n + 4;
           $query .= "','".$x[$n];
           $p = $p + 4;
           if ($x[$p]) $query .= "','".$x[$p]."'),";
           else $query .= "',NULL),";
        }
        $query = substr($query, 0, -1);//get rid of last comma
        mysqli_query($query);
        

        如果需要,您还可以将数组与查询一起构建:

        $query = "INSERT INTO `table` (`description`, `category`, `link`) VALUES ";
        for ($i = 1; $i <= count($x) / 4; $i++) {
           $m = $m + 4;
           $desc[] = $x[$m];
           $query .= "('".$x[$m];
           $n = $n + 4;
           $cat[] = $x[$n];
           $query .= "','".$x[$n];
           $p = $p + 4;
           if ($x[$p]){
               $link[] = $x[$n];
               $query .= "','".$x[$p]."'),";
           } else {
               $link[] = $x[$n];
               else $query .= "',NULL),";
        }
        $query = substr($query, 0, -1);//get rid of last comma
        mysqli_query($query);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-10-31
          • 2014-07-21
          • 1970-01-01
          • 2016-05-26
          • 2013-03-05
          • 1970-01-01
          • 1970-01-01
          • 2015-06-18
          相关资源
          最近更新 更多