How to create multidimensional array for my playlist?
I want to create a playlist section for lyrics website.
For 开发者_Python百科creating a tracklist, is multidimensional array is best way to input? I have two inputs in my MD-array that is song and other is artist corresponding to that. I can create a textbox dynamically using JS. Please help me to create MD-array and input in Db using looping. Please provide basic idea along with code I will modify it later.
Tracks | Artist
_____________________
A | ar1
B | ar2
C | ar3
want somewhat this type of input to fill to DB.
PHP doesn't have multidimensional arrays, but nested arrays. they simulate dimensions. there are also objects in which you can hold the data sets. so you must use arrays or objects =)
you can have your data in many forms in your array. for e.g.
$myarray = array(0=>array('artist'=>'someone','tracks'=>array(tracks...)),
1=>array(...));
Here is a basic class you can use to use your database returned result as an array of object.
<?php
/*
* Default database class, stores connections and queries
* and all does db interaction
*/
class Database {
private static $connection;
private static $current_query;
function __construct() {
// do something
}
public static function open_connection() {
$db_server = 'localhost';
$db_user = 'db_user';
$db_pass = 'db_pass';
$db_name = 'db_name';
$connection = mysql_connect($db_server,$db_user,$db_pass);
if (!$connection){
// throw error
die ("Connection to database failed: ". mysql_error() ." $db_server,$db_user,$db_pass"); // debug
}
$db_select = mysql_select_db($db_name,$connection);
if (!$db_select){
// throw some error
//die("Database selection Failed: " .mysql_error());
}
self::$connection = $connection;
}
public static function close_connection() {
if (isset(self::$connection)){
mysql_close(self::$connection);
unset(self::$connection);
}
}
public function query($sql) {
if (!self::$connection){
self::open_connection();
}
self::$current_query = $sql;
try {
$result = mysql_query($sql,self::$connection);
} catch (Exception $e) {
self::close_connection();
// throw custom error
// The query failed for some reason. here is query :: self::$current_query
}
return $result;
}
private static function instantiate($record) {
$obj = new self;
foreach ($record as $k =>$value){
$obj->$k = $value;
}
return $obj;
}
public static function find_by_sql($sql){
if (!is_string($sql))
return false;
$result_set = self::query($sql);
$obj_arr = array();
while ($row = self::fetch_array($result_set))
{
$obj_arr[] = self::instantiate($row);
}
return $obj_arr;
}
}
now to access your data
$playlist = Database::find_by_sql("SELECT * FROM `playlist`");
// loop through your result
foreach($playlist as $play){
echo "<p>$play->tracks : $play->artist</p>";
}
That makes it easier for you to interact with your results set, maybe you should study the find_by_sql() and the instantiate() methods Goodluck :)
精彩评论