douxianji6104 2013-08-28 20:49
浏览 88
已采纳

PHP - 使用字段名称作为变量

I am getting the error "Warning: mysql_field_name() expects parameter 1 to be resource, object given in... on line 28"

I am fairly new to PHP, but what I am trying to accomplish is read a HTML file and replace a custom tag with the value of the record. The tag structure is |+FIELD-NAME-Record#+| For example if my sql returns two records for the "Name" field it will look for the following two tags |+Name1+| and |+Name2+| in the HTML file and replace it with the two returned values. Say Adam and Jim.

Below is the code that I have so far.

$c = '|+Name1+|<br>|+Name2+|';

echo(ReplaceHTMLVariables(mysqli_query($con,"SELECT * FROM nc_names"),$c));

function ReplaceHTMLVariables($results, $content){
    while($row = mysqli_fetch_array($results)){
        //Define a variable to count what record we are on
        $rNum = 1;

        //Loop through all fields in the record
        $field = count( $row );    
        for ( $i = 0; $i < $field; $i++ ) {
            //Use the field name and record number to create variables to look for then replace with the current record value
            $content = str_replace("|+".mysql_field_name( $results, $i ).$rNum."+|",$row[$i],$content);
        }

        //move to next record
        $rNum++;
    }
    return $content;
}

Line 28 references this line

$content = str_replace("|+".mysql_field_name( $results, $i ).$rNum."+|",$row[$i],$content);

  • 写回答

2条回答 默认 最新

  • dongzhuo5185 2013-08-28 21:11
    关注

    You're mixing MySQL with MySQLi, and you don't really need to do all that if you pull mysqli_fetch_assoc() instead:

    function ReplaceHTMLVariables($results, $content)
    {
        //Define a variable to count what record we are on
        $rNum = 1;
    
        /*** Using Mysqli::fetch_assoc() ***/
        while( $row = mysqli_fetch_assoc( $results ) )
        {
            //Loop through all fields in the record
            /*** Variable $value passed by reference for performance ***/
            foreach( $row as $fieldName => &$value ) {
                $content = str_replace("|+".$fieldName.$rNum."+|",$value,$content);
            }
    
            ++$rNum; /*** Faster than $rNum++ **/
        }
        return $content;
    }
    

    mysqli_fetch_assoc() Pulls the data as an associative array, with the field name as the index key.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线