Reputation: 37
I am making a simple blog in php and getting this error -
Illegal string offset 'name' in C:\xampp\htdocs\simple\index.php on line 28 and 29
<?php
foreach ( $posts as $post ) {
if ( ! category_exists('name', $post ['name'] ) ) { //line 28
$post['name'] = 'Uncategorised';
}
?>
I know the string offset questions have been asked here a lot but still I could not figure out how to fix this one. Please help.
Here is the function category_exists
function category_exists($field,$value)
{
$field=mysql_real_escape_string($field);
$value=mysql_real_escape_string($value);
$query=mysql_query("SELECT COUNT(1) FROM categories WHERE {$field}= '{$value}'");
echo mysql_error();
return (mysql_result($query,0)=='0')? false : true;
}
This part of code hopefully will help you understand the $posts
variable:
$posts=get_posts();
function get_posts($id=null,$cat_id=null){
$posts=array();
$query=mysql_query("SELECT posts.id AS post_id, categories.id AS category_id, title, contents, date_posted, categories.name FROM posts INNER JOIN categories ON categories.id = posts.cat_id ORDER BY post_id DESC");
while($row=mysql_fetch_assoc($query))
{
$posts=$row;
}
return $posts;
}
I have the following attributes of posts table -
id,title,cat_id,contents,date_posted.
For the categories table:
id and name.
Upvotes: 1
Views: 132
Reputation: 37069
Your variable $post probably is not an array. Try this first:
foreach ( $posts as $post ) {
var_dump($post);
}
If you see that it is an array, great! Use it as an array. It is very likely that $post will be a string. Therefore when you try to use $post['name'], PHP tells you that 'name' is not an offset for $post string. Had you used $post[0], that'd give you the first character and 0 would be legal offset...but 'name' wouldn't be a legal offset.
Upvotes: 2