如何将mysqli_connect更改为mysql_connect和mysqli_fetch_assoc

时间:2012-08-30 14:46:51

标签: php mysql arrays function mysqli

我有这个联系

    <?php
    $db_host = 'localhost';
    $db_user = 'root';
    $db_pass = '';
    $db_name = 'databasename';
    $conn = mysql_connect($db_host,$db_user,$db_pass) or die(mysql_error());
    mysql_select_db($db_name,$conn);
    mysql_query("SET NAMES 'utf8'");
    mysql_query('SET CHARACTER SET utf8');
    ?>

但我的旧连接无法使用此代码

        //connect to database
$link = mysqli_connect('localhost','root','');
mysqli_select_db($link,'databasename');
//get all rows
$query = mysqli_query($link,'SELECT * FROM categories');
while ( $row = mysqli_fetch_assoc($query) )
{
    $menu_array[$row['catid']] = array('catname' => $row['catname'],'parentid' => $row['parentid']);
    $menu_array[$row['catid']] = array('catname' => $row['catname'],'parentid' => $row['parentid'],'catid'=>$row['catid']);
}
//recursive function that prints categories as a nested html unorderd list
function generate_menu($parent)
{
$has_childs = false;
//this prevents printing 'ul' if we don't have subcategories for this category
global $menu_array;
    //use global array variable instead of a local variable to lower stack memory requierment
    foreach($menu_array as $key => $value)
    {
        if ($value['parentid'] == $parent)
        {
            //if this is the first child print '<ul>'
            if ($has_childs === false)
            {
                //don't print '<ul>' multiple times
                $has_childs = true;
                echo '<ul>';
            }
            echo '<li><a href="category.php?catid='. $value['catid'] . '">' . $value['catname'] . '</a>';

我认为我的错误位于此代码之间..最后我需要将mysqli_connect替换为mysql_connect而不是

while ( $row = mysqli_fetch_assoc($query) )
{
    $menu_array[$row['catid']] = array('catname' => $row['catname'],'parentid' => $row['parentid']);
}

1 个答案:

答案 0 :(得分:2)

您应该考虑使用mysqli_connect和mysqli_select_db。

同时将$query = mysqli_query($link,'SELECT * FROM categories');更改为:

$query = mysqli_query($link,'SELECT * FROM `categories`');

我认为问题可能是连接,其他一切看起来很好,我不认为你可以使用正常的mysql_conn访问mysqli对象..

试一试

另外,不要改为mysql,现在已经太老了!查看mysqliphp data object两者都有详细记录