我怎样才能翻译$ intNumField = mysql_num_fields($ objQuery);进入面向对象的Php

时间:2015-02-19 06:49:58

标签: php mysql

如何将mysql_num_fields()转换为面向对象的php以获取以下代码。

 $objConnect = mysql_connect("localhost","root","john123");
        $objDB = mysql_select_db("mydatabase");
        $strSQL = "SELECT * FROM `cman_tickets`";
        print_r($strSQL);
        //$strSQL = "SELECT * FROM `cman_tickets`";
        $objQuery = mysql_query($strSQL);
        $intNumField = mysql_num_fields($objQuery);
        $resultArray = array();
        while($obResult = mysql_fetch_array($objQuery))
        {
        $arrCol = array();
        for($i=0;$i<$intNumField;$i++)
        {
                $arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
        }
        array_push($resultArray,$arrCol);
        }

        mysql_close($objConnect);

        echo json_encode($resultArray);

1 个答案:

答案 0 :(得分:2)

要使用面向对象的php,你必须使用mysqli而不是mysql。

mysql_num_fields() 

可以替换为

mysqli_result::$field_count

因为不推荐使用mysql_ *函数,所以

    $objConnect =  new mysqli("localhost","root","john123","mydatabase");
    $strSQL = "SELECT * FROM `cman_tickets`";
    print_r($strSQL);

    $objQuery = $objConnect->query($strSQL);
    $intNumField = $objQuery->field_count; // to get the field count
    $resultArray = array();

    while($obResult = $objQuery->fetch_array())
    {

        $arrCol = array();
        for($i=0;$i<$intNumField;$i++)
        {
            $arrCol[$objQuery->fetch_field_direct($i)] = $obResult[$i];
         }
         array_push($resultArray,$arrCol);
    }

    echo json_encode($resultArray);