How to check if my foreach loop has a bug? - php

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].

Related

I have a problem with accessing "comments" table in databases with PHP

I have a code that have an access to my database's "comments" table. I did a connection variable and created all the stuff in order to get table. But I when save and refresh the page, it is showing this error below. What's the problem?
<?php
// connection
$connection = mysqli_connect(
$config['db']['server'],
$config['db']['username'],
$config['db']['password'],
$config['db']['name']
);
if ($connection == false)
{
echo 'Error!<br>';
echo mysqli_connect_error();
exit();
}
// comments
$сomments = mysqli_query($connection, "SELECT * FROM `comments` ORDER BY `articles_id` DESC LIMIT 5");
while ($com = mysqli_fetch_assoc($comments))
{
?>
<article class="article">
<div class="article__image" style="background-image: url(https://www.gravatar.com/avatar/<?php echo md5($com['email']); ?>?s=125);"></div>
<div class="article__info">
<?php echo $com['author']; ?>
<div class="article__info__preview"><?php echo mb_substr(strip_tags($com['text']), 0, 100, 'utf-8') . ' ...'; ?></div>
</div>
</article>
<?php
}
?>
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given in W:\domains\itblog.kg\includes\sidebar.php on line 56 . What is the problem?
The problem is that the query ($comments = mysqli_query(...) is returning a null value. This means that there has been some problem with the query.
Try changing the code like this:
$сomments = mysqli_query($connection, "SELECT * FROM `comments` ORDER BY `articles_id` DESC LIMIT 5");
// start new
if (!$comments) {
echo "Error - " . mysqli_error($connection);
} else
// end new
while ($com = mysqli_fetch_assoc($comments))
{
?>
<article class="article">
...
(Note that you should also surround the whole while loop with braces {}, as it is the else clause, to avoid future errors. But it should work like that.)
The script should report the error it is seeing and it should allow you to fix the query.
Edit - I'd bet that the comments table does not have an articles_id column - probably it should be article_id.

PHP7 - MySQLI Error handling issues after moving site to a new server

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

Warning: mysqli_query(): Couldn't fetch mysqli [duplicate]

This question already has an answer here:
mysqli_query(): Couldn't fetch mysqli error [duplicate]
(1 answer)
Closed 2 years ago.
I am new to PHP and not familiar with many of its rules, so this could possibly be a stupid question.
I have a database with top level categories and subcategories combined into one table. I want to first print out all the top-level categories, and then printout the subcategories associated with that category.
Here is my code:
<?php
session_start();
include_once "/mysqli_connect.php";
$categories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'category'");
mysqli_close($conn);
?>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<div id="wrap" class="animate">
<?php
while ($categories = mysqli_fetch_array($categories0, MYSQLI_ASSOC)) {
$catecory_name = $categories['category'];
echo '
<div class="content">
<div class="content_container no_padding">
<div class="content_container header">
<p>'.$categories['category'].'</p>
</div>
';
$subcategories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'subcategory'");
while ($subcategories = mysqli_fetch_array($subcategories0, MYSQLI_ASSOC)) {
echo $subcategories['category'];
//mysqli_free_result($subcategories0);
}
echo '
</div>
</div>
';
}
?>
</div>
</div>
</body>
</html>
Here is the connection script:
<?php
DEFINE ('DB_USER', '*');
DEFINE ('DB_PASSWD', '*');
DEFINE ('DB_HOST', '*');
DEFINE ('DB_NAME', '*');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWD, DB_NAME);
if(!$conn){
die('Database connection error');
}
echo '<!-- Connected to database -->'
?>
It returns the following error:
Warning: mysqli_query(): Couldn't fetch mysqli
When both queries are above the doctype everything is fine, but when the second query is below the doctype the error occurs.
The first query always runs without problems, it is the second one that returns the error.
I can't seem to figure out what is going on, if anyone can help me that would be appreciated.
You forget to close your while loop. check comment in line where you need to close it.
<?php
$categories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'category'");
?>
<!DOCTYPE html>
<?php
while ($categories = mysqli_fetch_array($categories0, MYSQLI_ASSOC)) {// need to close your loop
$catecory_name = $categories['category'];
echo '
<div class="content">
<div class="content_container header">
<p>'.$categories['category'].'</p>
</div>
';
}// close here
$subcategories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'subcategory'");
// The above line is where the error occurs
while ($subcategories = mysqli_fetch_array($subcategories0, MYSQLI_ASSOC)) {
echo $subcategories['category'];
}
?>
UPDATED
Remove close connection from top because after it your query will not execute. Your connection variable is vanished after your connection is closed.
<?php
session_start();
include_once "/mysqli_connect.php";
$categories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'category'");
?>
Today I have phased the same problem. But There is little mistake that you did in code.
You are trigger select statement this:
See. You are now closing the connection with mysqli_close($conn);
and then in while loop you are fetching data. If connection has been closed then how can php take data from mysql table?
Just remove mysqli_close($conn); statement and run.
In the last line you can put this code. After all the operation.

Warning: Illegal string offset 'todo' | PHP

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...

Query failing to get MySQL data, not mysql_error() displaying

I am using phpmyadmin and had mySQL database working with my php until I started adding foreign key constraints. Then all of the sudden it stopped working. Now I'm backtracking to the very beginning when I ran my first query, but it still will not work (even though it used to). When I call for the mysql_error() nothing appears.
It seems so simple but I do not know what is going wrong. I even deleted out all of the tables from my database except the subjects table.
manage_content page (which should read my table):
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/db_connection.php");?>
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/functions.php");?>
<?php include($_SERVER['DOCUMENT_ROOT']."/includes/header-home.php");?>
<?php
// 2. Perform database query
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
confirm_query($result);
?>
<div id="main">
<div id="navigation">
<ul class="subjects">
<?php
// 3. Use returned data (if any)
while($subject = mysqli_fetch_assoc($result)) {
// output data from each row
?>
<li><?php echo $subject["first_name"] . " (" . $subject["id"] . ")"; ?></li>
<?php
}
?>
</ul>
</div>
<div id="page">
<h2>Manage Content</h2>
</div>
</div>
<?php
// 4. Release returned data
mysqli_free_result($result);
?>
<?php include($_SERVER['DOCUMENT_ROOT']."/includes/footer.php");?>
Functions page:
<?php
function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed: " . mysql_error());
}
}
?>
Please help! I'm new and I know this is incredibly simple. I just don't know what I'm missing!
Because when you do query you call mysqlI_query() function, but when you wanna get error, you do it with mysql_query(), try to change that!!
mysqli_error()

Categories