将包含多个数组的数组放入mysql表中

时间:2013-07-13 07:38:15

标签: php mysql arrays

我有什么:

包含30个键的数组,某些键只包含一个值,而其他键包含多个键(一个键包含28个值)。首先,我甚至不知道这是否有效。但我尝试使用我在这里找到的其他例子只是为了使其无效。

像这样说

'name' => somemovie
cast => person1, person2, person3, person4, person5, person6
poster => poster1, poster2, poster3
year => someyear

依旧等等

我的问题是:是否可以将它们放在mysql表中,如果是这样的话?我正在使用PHP 5.3。

这是我的代码,以及我几年前使用的下半部分,对于一个简单的数组,它运行良好。不再那么多了。

$imdb = new Imdb();
$movieArray = $imdb->getMovieInfo("$cat");
     extract ($movieArray);
$mysqli = new mysqli("localhost", "custom_xxxx", "xxxxxxxxxx", "custom_xxxx");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$result = mysqli_insert_array("imdb", $movieArray);

if( $result['mysqli_error'] ) {
    echo "Query Failed: " . $result['mysqli_error'];
} else {
    echo "Query Succeeded! <br />";
    echo "<pre>";
    print_r($result);
    echo "</pre>";
}

?>

2 个答案:

答案 0 :(得分:0)

如果你只想将数组存储为对象而不想在其上运行sql查询,那么序列化对象并将其保存为二进制mysql。

序列化:http://php.net/manual/de/arrayobject.serialize.php

mysql-binary:http://dev.mysql.com/doc/refman/5.1/de/binary-varbinary.html

答案 1 :(得分:0)

您可以使用序列化功能,但我建议不要使用它。创建三个具有以下列的表,这些列将取决于您的数据模型,但它将是这样的:

  • movies(movie_id,year,poster_id,actor_id) - 在这里存储电影
  • actors(actor_id,name,dob) - 在此处存储演员信息。
  • posters(movie_id) - 在此处存储海报信息。

现在,用于数据输入数据库。你需要这样的东西:

$imdb = new Imdb();
$movieArray = $imdb->getMovieInfo("$cat");
     extract ($movieArray);
$mysqli = new mysqli("localhost", "custom_xxxx", "xxxxxxxxxx", "custom_xxxx");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
//the following code assumes $movieArray  like this:
// $movieArray = Array(
//'name' => somemovie,
//'cast' => array(person1, person2, person3, person4, person5, person6)
//'poster' => array(poster1, poster2, poster3)
//'year' => someyear)
foreach($movieArray as $row){
          foreach($row['cast'] as $name){
                    mysqli_query("INSERT INTO actor values($name['name'], $name['dob'])");
          }
          foreach($row['poster'] as $name){
           //insert into poster table 
          }

          //add foreach loop for each table.
}
if( $result['mysqli_error'] ) {
    echo "Query Failed: " . $result['mysqli_error'];
} else {
    echo "Query Succeeded! <br />";
    echo "<pre>";
    print_r($result);
    echo "</pre>";
}

这不是实际代码,因为你没有显示数组结构,但我想你会明白这个想法。基本上,对于多维数组,您需要使用foreach循环和放大器使用insert语句将数据插入数据库表。

要进行检索,您需要使用SELECT语句。最后,如果你没有接触SQL&amp;数据库,请检查SQL Introduction