用php将mysql数据添加到手风琴中

时间:2013-06-15 18:43:56

标签: php jquery mysql

[代码]

<?php
mysql_connect("","","") or die("Could not connect to localhost");
mysql_select_db("") or die( "Could not connect to database");

$names[] = mysql_query("SELECT * FROM list ORDER BY name ASC");

// The list wasn't sorted, if you don't want sorting you can just remove this line.
asort($names);

// Prepare list for accordion.
$accordionData = [];
foreach($names as $name) {
  $accordionData[substr($name, 0, 1)][] = $name;
}

?>
<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Accordion - Collapse content</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css" />
  <script>
  $(function() {
    $( "#accordion" ).accordion({
      collapsible: true,
      active: false
    });
  });
  </script>
</head>
<body>
<div id="accordion">
<?php
// Print accordion, change the echoes to reflect your accordion html.
foreach($accordionData as $index => $names) {
?>

  <h3><?php echo strtoupper($index); ?></h3>
  <div>
  <?php
  foreach($names as $name) {
  ?>
    <p><?php echo ucfirst($name); ?></p>
  <?php
  }
  ?>
  </div>
  <?php
}
?>
</div>

我收到两个错误:

  

警告:substr()期望参数1为字符串,资源为   第14行的C:\ xampp \ htdocs \ test.php

     

警告:ucfirst()期望参数1为字符串,资源为   第49行的C:\ xampp \ htdocs \ test.php

如果我把名字从数组中删除,我怎么能把名字输入手风琴?

2 个答案:

答案 0 :(得分:0)

使用mysql_fetch_*函数来处理mysql_query返回的资源。

$qry = mysql_query("SELECT * FROM list ORDER BY name ASC");

while ($data = mysql_fetch_assoc($qry))
  echo $data['name']; // contains list.name from your db

此外,您更喜欢使用PDO,因为自5.3以来不推荐使用mysql_ *。看看它there

答案 1 :(得分:0)

mysql_query()函数运行SQL语句,并且(如果这是SELECT语句)返回结果。您必须使用mysql_fetch_array()mysql_fetch_assoc()等合适的函数处理此结果。

$result = mysql_query("SELECT * FROM list ORDER BY name ASC");

$names = mysql_fetch_assoc($result);

然后在循环中使用带有字段键的$names数组(while)。例如,$names["name"]获取当前行的名称字段值。

<div id="accordion">
    <?php
        // Print accordion, change the echoes to reflect your accordion html.
        while($names = mysql_fetch_assoc($result))
        {
            echo "<h3>" . substr(strtoupper($names["name"]),0,1) . "</h3>";
            //first letter of the name
            echo "<div>";

            foreach($names as $name) 
            {
                echo  "<p>" . ucfirst($name) . "</p>";
            }
            echo "</div>";
        }
    ?>
</div>

是的,我们知道mysql_*已被弃用。