Wednesday, 28 August 2013

PHP - Use Field Names as Variable

PHP - Use Field Names as Variable

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

No comments:

Post a Comment