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条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法