PHP loop error message - php

I am new to php as well as posting php code. SO if there is any information missing please let me know.
I am trying to have a list of products echo through a foreach loop. I am not sure whether the mistake is just syntax or something bigger than that.
Here is the error message:
Home
Product List
Code Name Version Release Date
( ! ) Warning: Invalid argument supplied for foreach() in /Applications/XAMPP/xamppfiles/htdocs/tech_support/product_manager/product_list.php on line 15
Call Stack
# Time Memory Function Location
1 0.0004 247496 {main}( ) ../index.php:0
2 0.0024 273008 include( '/Applications/XAMPP/xamppfiles/htdocs/tech_support/product_manager/product_list.php' ) ../index.php:20
Here's is product_list php.
<?php include '../view/header.php'; ?>
<h1>Product List</h1>
<!-- display a table of products -->
<h2><?php echo $products; ?></h2>
<tr>
<th>Code</th>
<th>Name</th>
<th>Version</th>
<th>Release Date</th>
<th> </th>
</tr>
<?php foreach ($products as $product) : ?> //<-----line 15
<tr>
<td><?php echo $product['product_id']; ?></td>
<td><?php echo $product['name']; ?></td>
<td class="right"><?php echo $product['version']; ?></td>
<td><form action="." method="post">
<input type="hidden" name="product_id"
value="<?php echo $product['releaseDate']; ?>">
<input type="submit" value="Delete">
</form></td>
</tr>
<?php endforeach; ?>
<p>Add Product</p>
<?php include '../view/footer.php'; ?>
Heres the code I have in my index folder.
<?php
require('../model/database.php');
require('../model/product_db.php');
$action = filter_input(INPUT_POST, 'action');
if ($action === NULL) {
$action = filter_input(INPUT_GET, 'action');
if ($action === NULL) {
$action = 'list_products';
}
}
if ($action == 'list_products') {
$product_id = filter_input(INPUT_GET, 'product_id',
FILTER_VALIDATE_INT);
if ($product_id == NULL || $product_id == FALSE) {
$product_id = 1;
}
$products = get_product($product_id);
include('product_list.php');
}
else if ($action == 'show_add_form') {
$product = get_product($product_id);
include('product_add.php');
.......
Just in case here is my database functions
<?php
function get_product($product_id) {
global $db;
$query = 'SELECT * FROM products
WHERE productCode = :product_id';
$statement = $db->prepare($query);
$statement->bindValue(":product_id", $product_id);
$statement->execute();
$products = $statement->fetch();
$statement->closeCursor();
return $products;
}
?>

If $products is an object you can try to typecast it before use it in loop like this: $array = (array) $yourObject;

as looking into:
PDO Fetch
it returns an array of the data, not an object as expected.
so, try to
var_dump( $products );
to take a look what it really is...an object or an array.
hope that helps.

Related

Viewing the properties of the selected product with the woocommerce rest api

I created a form in the list of products linked to the id number, but I don't know how to bring it up. Can you help me?
My product form list;
<?php $i = 1; ?>
<?php foreach ( $data as $row ) : ?>
<td><?= $i; ?></td>
<td><?= $row['name']; ?></td>
<form action="single_product.php" name="update" method="GET">
<td><input type="submit" name="edit" value="<?= $row['id']; ?>"/></td></form>
<?php $i++; ?>
<?php endforeach; ?>
single_product.php
<?php
$data = file_get_contents('http://localhost/api-woocommerce/single_product_connect.php');
$data = json_decode($data, true);////I get an undefined error when I print this array as foreach
?>
//I don't know what to write here in array because foreach ( $data as $row ) komutunu kullandığımda"I'm getting an undefined foreach error"
single_product_connect.php
<?php
$id = $_get['edit'];?>
<?php echo json_encode($woocommerce->GET('products'.$id)); ?>
screen;

How to fetch and display data at the same time from MYSQL using PHP

I am unable to display data from a table from a MYSQL database using PHP OOP. However, I'm not sure if I'm unable to display the data because I'm not actually fetching the data in the first place.
I've tried fetching and displaying the data using only a PHP array and no HTML in my method and I figured this wouldn't be working because I wasn't using HTML list tags to format the data from the database. I've considered using a HTML table but I have seen displays from databases using lists work a few times before and I want to know why this doesn't work how it should.
I've tested for MYSQL connection and it does exist.
* M_PRODUCTS.PHP *
<?php
class Products
{
private $Conn;
private $db_table = "toys";
function __construct() {
// here we're making sure that the connection from $conn in "init.php" is transferred
// into our own private $conn property for usage in this object
global $Conn;
$this->Conn = $Conn;
}
// fetches and displays all products from db
public function fetch_all_products($id = NULL)
{
if ($id == NULL)
{
$data = [];
if ($result = $this->Conn->query("SELECT * FROM " . $this->db_table . " ORDER BY name"))
{
if ($result->num_rows > 0)
{
while ($row = $result->fetch_array())
{
$data = array(
"id" => $row["product_id"],
"name" => $row["name"],
"price" => $row["price"],
"image" => $row["image"]
);
}
return $data;
}
else
{
return "<h1>Oops... Something went wrong!</h1>";
}
}
}
}
}
* INDEX.PHP *
<?php include("init.php");
include("models/m_products.php");
?>
<body>
<div id="whitespace">
<?php
$products = fetch_all_products();
?>
<?php foreach($products as $row) { ?>
<tr>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->price; ?></td>
<td><img src="<?php echo $row->image_path(); ?>" alt="<?php echo $row->name; ?>" width="100" /></td>
</tr>
<?php } ?>
</div>
</body>
I expect the images of my products to be displaying in my index.html file. However, nothing appears.
I also get this error message in the JavaScript console: Failed to load resource: the server responded with a status of 404 (Not Found). This would explain a lot but as I said I tested my database connection and it works. I'm not sure how or why this message is coming from the JavaScript console if I'm not using JavaScript. I thought it would be worth mentioning anyway.
According to your code the function returns some data, but the thing is that you have not printed it, so instead of return in the function you can use echo or just put
echo $Products->fetch_all_products();
Strange code, I would do something like that.
1. First the function find all()
2. index.php echo - output
<?php
$products = find_all_products();
?>
<?php foreach($products as $row) { ?>
<tr>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->price; ?></td>
<td><img src="<?php echo $row->image_path(); ?>" width="200" /></td>
</tr>
<?php } ?>
There are 2 major issues I can see in your code
1) you need to update your comparison operator from
if ($id = NULL)
to
if ($id == NULL)
2) you need to update your code in index.php from
<body>
<div id="whitespace">
<h1><?php echo shop_name ?></h1>
<?php
echo $Products->fetch_all_products();
?>
</div>
</body>
to
<body>
<div id="whitespace">
<?php
$products = find_all_products();
?>
<?php foreach($products as $row) { ?>
<tr>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->price; ?></td>
<td><img src="<?php echo $row->image_path(); ?>" alt="<?php echo $row->name; ?>" width="100" /></td>
</tr>
<?php } ?>
</div>
</body>
I hope it will sort out your issue
Correct your comparison operator it should be.
if ($id == NULL)
instead of
if ($id = NULL)
in your function fetch_all_products().
correct the code in index.php to print an array use print_r() or loop through the result array.

Unable to delete product from table using PHP

I am in a pickle here. Whenever I try to press the delete button on my project, it goes straight to the PHP file and does nothing to the database that I have set up for it.
Here are some visuals to help you:
Visual number 2
Here is the code for index.php:
<?php
require_once('database.php');
//Get Category Id
$category_id= filter_input(INPUT_GET, 'category_id', FILTER_VALIDATE_INT);
if ($category_id == NULL || $category_id == false){
$category_id = 1;
}
// Get name for selected category
$queryCategory = 'SELECT * FROM categories
WHERE categoryID = :category_id';
$statement1 = $db->prepare($queryCategory);
$statement1->bindValue(':category_id', $category_id);
$statement1->execute();
$category = $statement1->fetch();
$category_name = $category['categoryName'];
$statement1->closeCursor();
//Get all categories
$queryAllCategories = 'SELECT * FROM categories
ORDER BY categoryID';
$statement2 = $db -> prepare($queryAllCategories);
$statement2->execute();
$categories = $statement2->fetchAll();
//Get products fpr selected category
$queryProducts = 'SELECT * FROM products
WHERE categoryID = :category_id
ORDER BY productID';
$statement3 = $db -> prepare($queryProducts);
$statement3 -> bindValue(':category_id', $category_id);
$statement3 -> execute();
$products = $statement3 -> fetchAll();
$statement3 ->closeCursor();
?>
<!DOCTYPE html>
<HTML>
<head>
<title>My Guitar Shop</title>
<link rel="stylesheet" type="text/css" href="../main1.css"/>
</head>
<body>
<header><h1>Product Manager</h1></header>
<main>
<hr>
<h1>Product List</h1>
<aside>
<h2>Categories</h2>
<nav>
<ul>
<?php foreach ($categories as $category) : ?>
<li>
<a href=".?category_id=<?php echo $category['categoryID']; ?>">
<?php echo $category['categoryName'];?>
</a>
</li>
<?php endforeach; ?>
</ul>
</nav>
</aside>
<section>
<!-- display a table of products -->
<h2><?php echo $category_name; ?></h2>
<table>
<tr>
<th>Code</th>
<th>Name</th>
<th class="right">Price</th>
<th> </th>
</tr>
<?php foreach ($products as $product) : ?>
<tr>
<td><?php echo $product['productCode']; ?></td>
<td><?php echo $product['productName']; ?></td>
<td><?php echo $product['listPrice']; ?></td>
<td><form action="delete_product.php" method="post">
<input type="hidden" name="product_id" value="<?php echo $product['productID']; ?>">
<input type="hidden" name="category_id" value="<?php echo $product['categoryID']; ?>">
<input type="submit" value="Delete">
</form></td>
</tr>
<?php endforeach; ?>
</table>
<p>Add Product</p>
</section>
</main>
<hr>
<footer><p>$copy; <?php echo date("Y"); ?> My Guitar Shop Inc</p></footer>
</body>
</html>
code for delete_product.php:
<?php
require_once('database.php');
$product_id= filter_input(INPUT_GET, 'product_id', FILTER_VALIDATE_INT);
$category_id= filter_input(INPUT_GET, 'category_id', FILTER_VALIDATE_INT);
//Delete the product from the datavase
if ($product_id != false && $category_id != false){
$query = 'DELETE FROM products
WHERE productID = :product_id';
$statement = $db -> prepare($query);
$statement -> bindValue(':product_id', $product_id);
$success = $statement->execute();
$statement -> closeCursor();
}
//Display the Product List Page
include('index.php');
?>
Thank you for helping me out! I really appreciate it!
Your are submitting delete button in post method. So you have to receive these value in post method in delete page.
Just change INPUT_GET to INPUT_POST in two lines in delete_product.php
$product_id= filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
$category_id= filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);
instead of
$product_id= filter_input(INPUT_GET, 'product_id', FILTER_VALIDATE_INT);
$category_id= filter_input(INPUT_GET, 'category_id', FILTER_VALIDATE_INT);
You should try with this :
...
$product_id= filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
$category_id= filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);
...

How to remove duplicate post in wordpress where post has different id's?

I have a template file there are showing my post from a certain year, it is working but there are now duplicates of some post on my site and I am not allowed to delete them. So my problem is that the generated list is showing two different post but with the same content. I have an idear that it should be possible to test if the post_title is already printet to page, but I have not succeeded in that. So now i am asking for help. Below is my template file.
<?php
/* Template Name: 2012 */
get_header();
?>
<?php
$post_titles = array();
$year = isset($_GET['y']) ? $_GET['y'] : date('Y');
if($year == date('Y')){
$posts = get_newest_posts();
}
else{
$posts = get_yearly_posts($year);
} ?>
<div class="site-content-wrapper site-content-blog-wrapper container columns clearfix archive">
<article id="primary-wrapper" class="eight column">
<div class="post-blog inner">
<h2 class="entry-title">News <?= $year ?></h2>
<?php foreach($posts as $post): ?>
/* here i would like a test to see if a post with a similar title already has
printet to page. if it has not the code below should run and print post to page. */
<div class="archive-post">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody><tr>
<td width="100%"><span class="STRONG"><?= $post->post_title ?></span></td>
</tr>
<tr>
<td><span class="norm">
<?php if($year != date('Y')): ?>
<?= $post->search_plus_description ?>
<?php else: ?>
<?= $post->post_excerpt ?>
<?php endif ?>
</span></td>
</tr>
<tr>
<td>
<span class="norm">
<?= $year == date('Y') ? date('d F Y', strtotime($post->post_date)) : date('d F Y', strtotime($post->publication_date)) ?>
</span>
</td>
</tr>
<tr>
<td><img src="x.gif" width="1" height="10" alt=""></td>
</tr>
</tbody></table>
</div>
<?php endforeach ?>
Thanks for answers. I made function that that run through $post array and returns an array without duplicates. Seems to do it and I do not erase from db. Here is the code
function remove_duplicates(array $array){
$tmp_array = array();
$title_array = array();
$date_array = array();
foreach($array as $post)
{
$title = $post->post_title;
$date = $post->post_date;
if (!(in_array($title, $title_array) && in_array($date, $date_array)))
{
$tmp_array[] = $post;
$title_array[] = $title;
$date_array[] = $date;
}
}
return $tmp_array;
}
Just try this
global $wpdb;
$duplicate_titles = $wpdb->get_col("SELECT post_title FROM {$wpdb->posts} GROUP BY post_title HAVING COUNT(*) > 1");
foreach( $duplicate_titles as $title ) {
$post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_title=%s", $title ) );
// Iterate over the second ID with this post title till the last
foreach( array_slice( $post_ids, 1 ) as $post_id ) {
wp_delete_post( $post_id, true ); // Force delete this post
}
}
you can use your custom sql query on wp_posts table to find the ID of posts having distinct title and content. After that you can use WP_Query to use these ID's to display posts in the template loop.
i am posting an example which gives me distinct posts based on title:
$sql = 'select ID,post_title,post_type,post_status from wp_posts group by post_title having (post_status)="publish" AND (post_status)="publish"';
$results = $wpdb->get_results($sql,ARRAY_A);
$distinctIds = array();
foreach($results as $result){
$distinctIds[] = $result['ID'];
}
$args = array('post_type' => 'post','post__in'=> $distinctIds);
$distinct_posts = new WP_Query($args);
if($distinct_posts->have_posts()) :
while($distinct_posts->have_posts()) :
$distinct_posts->the_post();
// your stuff related to post
// echo content etc..
endwhile;
endif;
Of course we can use custom parameters in WP_Query for more refinement.
Hope this will help.

displaying data from mysql

Having a little trouble displaying data from a table. Been looking at my code for the past few hours and can't seem to see the problem. What I am trying to do is when a team is clicked on it will go into the players table and display any player that has that team name on the team page. I keep getting a blank page:
index.php
This is the case that launches the team_view.php
case 'view_team':
$team = $_GET['name'];
$teams = get_players_by_team($team);
include('team_view.php');
break;
team_view.php
<?php include '../../view/header.php'; ?>
<?php include '../../view/sidebar_admin.php'; ?>
<div id="content">
<h1>Team Roster</h1>
<!-- display product -->
<?php include '../../view/team.php'; ?>
<!-- display buttons -->
</div>
<?php include '../../view/footer.php'; ?>
team.php
<?php
$team = $team['name'];
$first = $player['first'];
$last = $player['last'];
$age = $player['age'];
$position = $player['position'];
$team = $player['team'];
?>
<table>
<?php foreach ($players as $player) :
?>
<tr>
<td id="product_image_column" >
<img src="images/<?php echo $player['player_id']; ?>_s.png"
alt=" ">
</td>
<td>
<p>
<a href="?action=view_player&player_id=<?php echo
$player['player_id']; ?>">
<?php echo $player['first']; ?>
<?php echo $player['last']; ?>
</a>
</p>
</td>
</tr>
<?php endforeach; ?>
</table>
product_db.php
<?php
function get_players_by_team($team) {
global $db;
$query = 'SELECT * FROM players
WHERE team = :team';
try {
$statement = $db->prepare($query);
$statement->bindValue(':team', $team);
$statement->execute();
$result = $statement->fetch();
$statement->closeCursor();
return $result;
} catch (PDOException $e) {
display_db_error($e->getMessage());
}
}
You never define $players it looks like what you are expecting to be $players is actually $teams.
$teams = get_players_by_team($team);
Additionally youre using $player at the top of the script instead of inside the loop which makes no sense.

Categories