Am trying to do a to-do list using PHP
but am getting this error Warning: Illegal string offset 'todo'
$userhastodo = "";
$toDo_Query = "SELECT * FROM `todo` WHERE `for`='".$_SESSION['id']."'";
$toDo_run_query = mysqli_query($link , $toDo_Query);
$toDo_num_rows = mysqli_num_rows($toDo_run_query);
if($toDo_num_rows >= 1){
$toDo_get_info = mysqli_fetch_array($toDo_run_query);
$toDo_info = $toDo_get_info;
foreach($toDo_info as $info){
echo $info['todo'];
}
}
else{
$userhastodo = "You have no lists here :( !";
}
that is in the top of my todo.php page
in the html part
<?php if(empty($toDo_get_info)):?>
<div class="empty">
<i class="fa fa-meh-o fa-5x"></i>
<h3>Strange, no lists found!</h3>
</div>
<?php else: ?>
<ul class="list">
<?php foreach($toDo_info as $info_in_toDo):?>
<li><span><?php echo $info_in_toDo['todo']?></span></li>
<?php endforeach;?>
</ul>
<?php endif;?>
how can i fix this ? it keeps warning me => Warning: Illegal string offset 'todo'
todo exists in my mysql database holding the data of a to-do activity
If you look at this section:
$toDo_get_info = mysqli_fetch_array($toDo_run_query);
$toDo_info = $toDo_get_info;
foreach($toDo_info as $info){
echo $info['todo'];
}
You see that you get one row from your result set, so $toDo_info is a one-dimensional array containing one complete row.
You loop over that row with your foreach so you will get all values from that row and these are strings, not arrays.
You only need:
echo $toDo_get_info['todo'];
Edit: To get all rows and echo all items, you need to fetch all rows:
while ($toDo_get_info = mysqli_fetch_array($toDo_run_query))
{
// add your html to add list items here as well
echo $toDo_get_info['todo'];
}
Try changing to this
foreach($toDo_info as $key => $info){
echo $info;
}
Better yet see #jeroen's answer...
Related
with a lot of help from some people on here I have been building an online catalogue for my work website, today I moved it from the dev server to the production server so that a couple of other guys can start testing things for me and I seem to be having an issue with the menu query. I get the following errors
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result,
boolean given in /websites/store/includes/menu.php
on line 15
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result,
boolean given in /websites/store/includes/menu.php on line 34
Warning: Invalid argument supplied for foreach()
in /websites/store/includes/menu.php on line 34
I have spent all day trying to work out what is going on here, the code works perfectly on the dev server but just throws errors on the production server
can anyone explain to me what is going on or how to fix it
Here is the code for the page
<?php
// Category Listing From Database
// Open MySql Database Connection
include ('sqlopen.php');
// SQL Query for Category Listing
$sql = mysqli_query($conn, " SELECT CategoryName, SubcategoryName, SubcategoryID
FROM Products GROUP BY SubcategoryID ORDER BY CategoryName");
// Create Array from Data
$menu = array();
while ($row = mysqli_fetch_assoc($sql)) {
// Creates First Level Array Items For Parent IDs
if (!in_array($row['CategoryName'], $menu['CategoryName'])) {
$menu['CategoryName'][] = $row['CategoryName'];
}
if (!empty($row['SubcategoryName']))
// Creates Second Level Array for Child IDs
$menu['SubcategoryName'][$row['CategoryName']][] = $row['SubcategoryName'];
// Creates Third Level Array for Category IDs
$menu['SubcategoryID'][$row['SubcategoryName']][$row['CategoryName']][] = $row['SubcategoryID'];
}
//__________________________________________________________________________________________________________
// Category Menu
?>
<ul id="storenav">
<?php
foreach ($menu['CategoryName'] as $cat) { ?>
<li><a class="sub" tabindex="1"><?php echo $cat ?></a><ul>
<?php
foreach ($menu['SubcategoryName'][$cat] as $subcat) {
foreach($menu['SubcategoryID'][$subcat][$cat] as $id) ?>
<li><a href='/store/prodlist.php?subcatid=<?php echo $id ?>'><?php echo $subcat ?></a></li>
<?php } ?>
</ul></li>
<?php } ?>
</ul>
<?php
//__________________________________________________________________________________________________________
// Open MySql Database Connection
include ('sqlclose.php');
?>
you assume the line
$sql = mysqli_query()
returns a resultset. however, if the query fails it returns FALSE, a boolean.
That's the case here.
write your code like:
`
if($sql = mysqli_query($conn, "your query here")){
$menu = array();
while($row = ...) {
}
}
else {
echo 'something went wrong'; // and more error handling.
}
?>
`
--
and why the query fails?
The part group by has little to do in this query, as no aggragation function is present (min(), max(), count() etc)
And even then: all columns should be mentioned in the part "group by"
See mysqli_error() to let Mysql tell you why that query failed.
First of all, You're not handling errors correctly. Better told, you're not even checking for them. Try the code below. It will return a better description of what is going wrong.
<?php
/**
* Created by: PhpStorm.
* Project: Stackoverflow
* File name: .php.
* User: Deathstorm
* Date: 23-6-2017.
* Time: 10:14.
* File Description: ...
*/
?>
<?php
// Category Listing From Database
// Open MySql Database Connection
include ('sqlopen.php');
// SQL Query for Category Listing
$sql = mysqli_query($conn, "SELECT CategoryName, SubcategoryName, SubcategoryID
FROM Products GROUP BY SubcategoryID ORDER BY CategoryName");
if ($conn->query($sql) === TRUE){
// Create Array from Data
$menu = array();
while ($row = mysqli_fetch_assoc($sql)) {
// Creates First Level Array Items For Parent IDs
if (!in_array($row['CategoryName'], $menu['CategoryName'])) {
$menu['CategoryName'][] = $row['CategoryName'];
}
if (!empty($row['SubcategoryName']))
// Creates Second Level Array for Child IDs
$menu['SubcategoryName'][$row['CategoryName']][] = $row['SubcategoryName'];
// Creates Third Level Array for Category IDs
$menu['SubcategoryID'][$row['SubcategoryName']][$row['CategoryName']][] = $row['SubcategoryID'];
}
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
//__________________________________________________________________________________________________________
// Category Menu
?>
<ul id="storenav">
<?php
foreach ($menu['CategoryName'] as $cat) { ?>
<li><a class="sub" tabindex="1"><?php echo $cat ?></a><ul>
<?php
foreach ($menu['SubcategoryName'][$cat] as $subcat) {
foreach($menu['SubcategoryID'][$subcat][$cat] as $id) ?>
<li><a href='/store/prodlist.php?subcatid=<?php echo $id ?>'><?php echo $subcat ?></a></li>
<?php } ?>
</ul></li>
<?php } ?>
</ul>
<?php
//__________________________________________________________________________________________________________
// Open MySql Database Connection
include ('sqlclose.php');
?>
I'm trying to echo out multiple rows from a sql database, but I get the error Warning. Illegal string offset 'Date' In....
$channel_check = mysql_query("SELECT content, Date FROM wgo WHERE Posted_By='$user' ORDER by `id` DESC;");
$numrows_cc = mysql_num_rows($channel_check);
if ($numrows_cc == 0) {
echo '';
// They don't have any channels so they need to create one?><h4>                                                                                                             You haven't posted anything yet. You can post what's going on in your life, how you're feeling, or anything else that matters to you.</h4>
<?php
}
else
{
?>
<div id="recentc">
</div>
<?php
echo"<h2 id='lp'> Latest Posts</h2>";
while($row = mysql_fetch_array($channel_check)) {
$channel_name = $row['content']['Date'];
?>
<div style="margin-top:60px;">
<hr style="margin-right:340px;width:600px; opacity:0;">
<?php echo "<div id='rpc'><h6> $channel_name</h6></div>";?>
</div>
<?php
}
}
?>
DATE is a datatype in SQL, you need to escape it with back ticks
SELECT content, `Date` FROM wgo WHERE Posted_By='$user' ORDER by `id` DESC
Also, you're accessing your row incorrectly. Rows are typically represented by a uni-dimensional array, so $row['content'] and $row['Date']
$row is 1-dimensional array with 2 fields: content and Date.
Try,
while ($row = mysql_fetch_array($channel_check)) {
print_r($row);
//$channel_name = $row['content']['Date'];
I have a slight problem here. I have the following code that I create a search query, and im trying to take "$row" array and create a new array called "$item" so I can echo the values inside my div statement. This code works, and I do echo the $item array with the 'follower_username' values, however only the last value gets echoed out. I have values inside my database Nathan, Brett, Nathan2 and it only echoes Nathan2, or the last value of the array $item.
Here is my code:
$result = mysqli_query($con,"SELECT * FROM followers
WHERE username='$username'");
?>
<?php
while ($row = mysqli_fetch_array($result))
{
$item = $row;
}
?>
<body>
<div id="contentwrap">
<div rel="scrollcontent2">
<?php echo $item['follower_username'];?> <img style="width: 50px; height: auto;"<?php echo '<img src="/user_photo/' . $item['follower_username'] . '.jpeg" />';?>
</div>
I hope I can get this resolved, it is bugging me! Thank you for any help!!
What you're doing is reassigning the value of item to the current row each time.
$row will be an object of table row values from the resulting query so if you want all the rows in an $item variable that would need to be an array to store each result, instead of storing the current row in the same variable for each row.
You will then need to iterate that array to display each result.
$i = 0;
$item = array();
while ($row = mysqli_fetch_array($result))
{
$item[$i] = $row;
$i++;
}
<div>
<?php
foreach ($item as $value)
{
echo $value['follower_username'];
}
?>
</div>
Below is an example to show some shorthand versions of the same idea:
$item = array();
while ($row = mysqli_fetch_array($result))
{
$item[] = $row;
}
<div>
<ul>
<?php foreach ($item as $value): ?>
<li><?php echo $value['follower_username']; ?></li>
<?php endforeach; ?>
</ul>
</div>
while ($row = mysqli_fetch_array($result))
What that does is grab the next row in the result set, and assign it to the variable $row. Each time the loop runs, it assigns the latest row to $item. So to store the whole result set, use
$item[] = $row.
I'm sure what you are trying to accomplish with our next line of code. To show all items you need something like
foreach($item as $singleItem)
{
echo $singleItem['follower_username']."<br>";
}
I was just quickly throwing together a script for an article website where I retrieve articles out of a database.
Here is my index.php script
<?php
// include header
require("include/header.php");
require("include/helperfunctions.inc.php");
?>
<!-- page content -->
<!-- left section -->
<section id="contentleft">
<?php require("include/functions.php");
displayArticles();
foreach ($articles as $article) : ;
?>
<h2>Recent Articles</h2>
<ul>
<li><?php echo htmlout($articles['id']) ; ?></li>
<li><?php echo htmlout($articles['title']) ; ?></li>
<li><?php echo htmlout($articles['summary']) ; ?></li>
</ul>
<?php endforeach; ?>
</section>
<!-- right content -->
<section id="contentright">
</section>
<?php
// include footer
require("include/footer.php");
?>
Here is the start of the function library
function displayArticles($order="publicationdate DESC"){
// connect to the database
include("include/db.inc.php");
$query = "SELECT id, title, summary FROM maths order by ". $order . " limit 10";
// query the database
$result = mysqli_query($link, $query);
// error checking
if(mysqli_connect_errno()){
// $error = "error fetching articles";
echo " could not connect: " . mysqli_connect_errno() . " ";
exit();
}
// loop through storing values into array
while($row = mysqli_fetch_array($result)){
$articles[] = array('id'=>$row['id'] , 'title'=>$row['title'],'summary'=>$row['summary']);
}
}
?>
I get this error:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\Apache24\htdocs\include\functions.php on line 17 Recent Articles Notice: Undefined variable: articles in C:\Apache24\htdocs\home.php on line 14 Warning: Invalid argument supplied for foreach() in C:\Apache24\htdocs\home.php on line 14
It looks like a scope issue with the $articles object. You create $articles in the displayArticles() function.. but outside of the function, your other code does not know about it. Try returning $articles inside displayArticles(), and replace your displayArticles(); call at the top of the first page with:
$articles = displayArticles();
Also, as panique in the comments pointed out, you are referencing the wrong object inside your foreach block. Remove the 's' at the end of each $articles[blah], so that it reads $article[blah].
I am trying to generate a grouped/stratified report using PHP and MySQL.
tbl_items has the following fields: (1) UserName and (2) ItemName
A single user can have multiple items listed.
I want to generate an output where the data is stratified by each user. For example:
*UserName #1
-ItemName 1
-ItemName 2
*UserName #2
-ItemName 3
*UserName #3
-ItemName 4
-ItemName 5
I keep playing with the code, trying to put a loop inside a loop...but can't figure out how to do it! This is what I have so far:
<?
$sql="SELECT * FROM $tbl_items";
$result=mysql_query($sql);
?>
<html>
<body>
<? php while($rows=mysql_fetch_array($result)){ ?>
Item: <? echo $rows['ItemName']; ?> (<? echo $rows['UserName']; ?>)
<?php } mysql_close(); ?>
</body>
</html>
Please help!
while($row=mysql_fetch_array($result))
{
$itemsByUser[$row['UserName']][] = $row;
}
foreach($itemsByUser as $user => $items)
{
echo $user . "<br>";
foreach($items as $array)
{
echo "-" . $array['ItemName'];
}
}
This first creates an array that is order by Username. This means each user has an element in the array that contains an array of the items that have been assigned to the user.
Then, we go over each user and print out all of the items.