PHP SQL Sorting information into HTML div elements - php

I am trying to sort SQL results into different divs based on the category they are assigned in the database. There are four categories and it works fine as long as there are videos available for all 4 categories. It will create 1 div for each and assign the videos to the correct div. The issue I'm having is that I'd like to also create the div even if there are no videos available within that category. (Pretty new so the code is probably pretty chunky for what it should be)
PHP code
$stmt = $conn->prepare("SELECT * FROM VIDEOS WHERE categorie=:category ORDER BY categorie ASC, subcategorie ASC");
$stmt->bindParam(':category', $_POST['category']);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<div class='spacer'>";
$testcase = "";
for($x = 0; $x < sizeof($result); $x++) {
if($result[$x]["subcategorie"] != $testcase) {
echo
"</div><div class='subcategory_container active' id='" . $result[$x]["subcategorie"] . "'>
<h3 class='subcategory_title'>". $result[$x]["subcategorie"] . "</h3>";
echo
"<div class='video_div'> <iframe width='196' height='350'
src='" . $result[$x]['linkembed'] . "'>
</iframe></div>";
$testcase = $result[$x]["subcategorie"];
} else {
echo
"<div class='video_div'> <iframe width='196' height='350'
src='" . $result[$x]['linkembed'] . "'>
</iframe></div>";
}
}
I have tried adding multiple if($result[$x]["subcategorie"] == "categoryname") statements but specifying the name within a for loop resulted in there being multiple of the same divs and a repeat of data. So far I've tried to look up SQL group by PHP tutorials but they all show the same result being inside of a table. The goal is to get the information into their own div with the ID of said div being the category name. I'm working with AJAX calls using JS to fix the issue won't work.

This solution builds a $videos array using the static subcategories as keys, it then populates these after looking through the database, then it's a matter of echoing the iframes if records exist.
<?php
/*
Question Author: Terhert
Question Answerer: Jacob Mulquin
Question: PHP SQL Sorting information into HTML div elements
URL: https://stackoverflow.com/questions/74715867/php-sql-sorting-information-into-html-div-elements
Tags: php, mysql
*/
include '../../inc/helpers.php';
try {
$pdo = new PDO(DB_DSN, DB_USER, DB_PASS, DB_OPTIONS);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
$pdo->query('DROP TABLE table74715867;');
$pdo->query('CREATE TABLE IF NOT EXISTS table74715867 (id TEXT, name TEXT, linkembed TEXT, categorie TEXT, subcategorie TEXT);');
$data = [
['id' => '1', 'name' => 'test1','linkembed' => 'http://example.org', 'categorie' => 'abc', 'subcategorie' => 'kracht'],
['id' => '2', 'name' => 'test2','linkembed' => 'http://example.org', 'categorie' => 'abc', 'subcategorie' => 'uithouding'],
['id' => '9', 'name' => 'test9','linkembed' => 'http://example.org', 'categorie' => 'abc', 'subcategorie' => 'mobiliteit'],
['id' => '10', 'name' => 'test10','linkembed' => 'http://example.org', 'categorie' => 'abc', 'subcategorie' => 'mobiliteit'],
['id' => '3', 'name' => 'test3','linkembed' => 'http://example.org', 'categorie' => 'xyz', 'subcategorie' => 'majig1'],
['id' => '4', 'name' => 'test4','linkembed' => 'http://example.org', 'categorie' => 'xyz', 'subcategorie' => 'majig2'],
['id' => '5', 'name' => 'test5', 'linkembed' => 'http://example.org', 'categorie' => '123', 'subcategorie' => 'whatchmacallit1'],
['id' => '6', 'name' => 'test6', 'linkembed' => 'http://example.org', 'categorie' => '123', 'subcategorie' => 'whatchmacallit2'],
['id' => '7', 'name' => 'test7', 'linkembed' => 'http://example.org', 'categorie' => 'qwerty', 'subcategorie' => 'fizz1'],
['id' => '8', 'name' => 'test8', 'linkembed' => 'http://example.org', 'categorie' => 'qwerty', 'subcategorie' => 'buzz1'],
];
$stmt = $pdo->prepare('INSERT INTO table74715867 SET id=:id, name=:name, linkembed=:linkembed, categorie=:categorie, subcategorie=:subcategorie;');
foreach ($data as $record) {
$stmt->execute([
':id' => $record['id'],
':name' => $record['name'],
':linkembed' => $record['linkembed'],
':categorie' => $record['categorie'],
':subcategorie' => $record['subcategorie']
]);
}
$category = 'abc';
$stmt = $pdo->prepare("SELECT * FROM table74715867 WHERE categorie=:category ORDER BY categorie ASC, subcategorie ASC");
$stmt->bindParam(':category', $category);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$videos = ["kracht" => [], "uithouding" => [], "mobiliteit" => [], "stretching" => []];
foreach ($result as $record) {
$videos[$record['subcategorie']][] = $record;
}
foreach ($videos as $subcategory => $records) {
echo '<div class="subcategory_container active" id="' . $subcategory . '">' .
'<h3 class="subcategory_title">' . $subcategory . '</h3>';
if (!empty($records)) {
foreach ($records as $record) {
echo '<div class="video_div"><iframe width="196" height="350" src="'.$record['linkembed'].'"></iframe></div>';
}
}
echo '</div>';
}
Here's the resulting HTML:
<head></head>
<body>
<div class="subcategory_container active" id="kracht">
<h3 class="subcategory_title">kracht</h3>
<div class="video_div">
<iframe src="http://example.org" width="196" height="350"></iframe>
</div>
</div>
<div class="subcategory_container active" id="uithouding">
<h3 class="subcategory_title">uithouding</h3>
<div class="video_div">
<iframe src="http://example.org" width="196" height="350"></iframe>
</div>
</div>
<div class="subcategory_container active" id="mobiliteit">
<h3 class="subcategory_title">mobiliteit</h3>
<div class="video_div">
<iframe src="http://example.org" width="196" height="350"></iframe>
</div>
<div class="video_div">
<iframe src="http://example.org" width="196" height="350"></iframe>
</div>
</div>
<div class="subcategory_container active" id="stretching">
<h3 class="subcategory_title">stretching</h3>
</div>
</body>

Related

Distinct in foreach loop. To many result because of two loops

I've a custom system that provides adding new information in custom columns.
I've two tables in my database. One for my value data and the second for the columns (data fieds).
Above you see a image from my form that is build by custom data fields with data per field.
Only in my for each i get for every data a extra loop so that is why i got from every data field two. How can I fix this?
<?php foreach ($list as $key => $value) { ?>
<?php foreach ($dataList as $data) { ?>
<div class="row clearfix">
<div class="col-xl-12">
<div class="form-group form-group-default">
<label><?php echo ucfirst($key); ?></label>
<?php if($key == $data['name']) { ?>
<input type="text" class="form-control" name="value_<?php echo trim($data['name']); ?>" value="<?php echo trim($data['value']); ?>" required>
<?php }else{ ?>
<input type="text" class="form-control" name="value_<?php echo trim($data['name']); ?>" placeholder="<?php echo ucfirst($key); ?>">
<?php } ?>
</div>
</div>
</div>
<?php } ?>
<?php } ?>
$list you'll find a list of data fields and in $dataList you'll find records of data.
Database structure:
data:
['id','hash','field_id','value']
Example of data:
['id' => 1, 'hash' => 123, 'field_id' => 1, 'value' => 'food']
Fields:
['id','name']
Example of fields:
['id' => 1, 'name' => 'firstname']
Below you'll find the foreach variables:
$data = processing('read', 'data JOIN fields ON data.field_id = fields.id', ['data.value,data.uid,fields.name,data.id,fields.category_id'], 'uid = "' . trim($_GET['datalist']) . '"', true);
$dataItem = processing('read', 'data JOIN fields ON data.field_id = fields.id', ['fields.category_id'], 'uid = "' . trim($_GET['datalist']) . '"');
$fieldList = processing('read', 'fields', ['name'], 'category_id = "'. trim($dataItem['category_id']) . '"',true);
$list = [];
foreach($fieldList as $key => $value) {
$list[$value['name']] = $value['name'];
}
Update:
I've update my own question because the other answers didn't resolved my problem. The only problem on my answer is, that when I update it doesnt look at the id of the item but at the name, so i can't save two items with the same name.
<?php foreach ($dataItems as $key => $value) { ?>
<div class="row clearfix">
<div class="col-xl-12">
<div class="form-group form-group-default">
<label><?php echo ucfirst($key); ?></label>
<input type="text" placeholder="<?php echo ucfirst($key); ?>" class="form-control" name="<?php echo trim($key); ?>" value="<?php echo trim($value); ?>">
</div>
</div>
</div>
<?php } ?>
method:
public function getDataListItems(int $category, array $list) {
global $dbh;
$query = 'SELECT data.value, data.uid, fields.name FROM data JOIN fields ON data.field_id = fields.id WHERE fields.category_id = "' . trim($category) . '" ORDER BY uid';
$sql = $dbh->prepare($query);
$sql->execute();
$values = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach ($values as $row) {
if (!isset($items[$row['uid']])) {
$items[$row['uid']] = array_fill_keys($list, ''); // if it needs to dynamically generated
$items[$row['uid']]['uid'] = $row['uid'];
}
$items[$row['uid']][$row['name']] = $row['value'];
}
return $items;
}
Return:
array (
'7d1f4f8e906245f' =>
array (
'Voornaam' => 'Bettina',
'Achternaam' => 'Les',
'Initialen' => 'pop',
'uid' => '7d1f4f8e906245f',
),
'7d1f4f8e906245g' =>
array (
'Voornaam' => 'Simone',
'Achternaam' => '',
'Initialen' => '',
'uid' => '7d1f4f8e906245g',
),
'7d1f4f8e906245l' =>
array (
'Voornaam' => 'test',
'Achternaam' => 'Kül',
'Initialen' => 'lol',
'uid' => '7d1f4f8e906245l',
),
'7d1f4f8e906245s' =>
array (
'Voornaam' => 'Joshua',
'Achternaam' => 'Mas',
'Initialen' => '',
'uid' => '7d1f4f8e906245s',
),
'gGcYEJdRYJ1vqcn' =>
array (
'Voornaam' => '',
'Achternaam' => 'Hello',
'Initialen' => '',
'uid' => 'gGcYEJdRYJ1vqcn',
),
)

Display the member of one array depending on the other array

i have an array i and i want to show the array values if the name of same array repeat in the another array and have true value
my arrays like this
$array1 = [
array(
'name' => internal_evidence
'price' => 30
'course_id' => 3
),
array(
'name' => international_evidence
'price' => 450
'course_id' => 3
),
array(
'name' => internal_evidence
'price' => 10
'course_id' => 1
),
array(
'name' => technical_evidence
'price' => 134
'course_id' => 3
),
];
$array2 = [
array(
'id' => 3
'name' => graphic
'price' => 150
'attr' => array(
'internal_evidence' => 'true',
'international_evidence' => 'false',
'technical_evidence' => 'true'
)
),
array(
'id' => 5
'name' => 3dmax
'price' => 300
'attr' => array(
)
),
array(
'id' => 1
'name' => ICDL
'price' => 480
'attr' => array(
'internal_evidence' => 'true',
)
),
];
i want to showing this all attr selected with true value in like this
also I want to sum price of array2 member and array1
<h2>graphic</h2>
<p>internal_evidence</p>
<p>technical_evidence</p>
<small>course price: 150</small>
<small>314</small> <!-- Price with selected evidence -->
<h2>3dmax</h2>
<small>course price: 300</small>
<!-- its not have attr evidence -->
<h2>ICDL</h2>
<p>internal_evidence</p>
<small>course price: 480</small>
<small>490</small> <!-- Price with selected evidence -->
i try this but its don`t work properly
$priceOfAttr = 0;
foreach($array2 as $key => $cat):
echo "<h2>{$cat['name']}</h2>";
foreach($array1 as $pr):
if($pr['course_id'] == $cat['id']):
foreach($cat['attr'] as $m => $optionV):
if($m == $pr['name'] && $optionV == "true"){
echo $m .'<br>';
$priceOfAttr += $pr['price'];
// echo "<small>{$cat['price']}</small><br>";
// echo $cat['price'] + $pr['price']. "<br>";
}
endforeach;
echo $priceOfAttr + $cat['price'] . '<br>';
endif;
endforeach;
echo '<br>';
endforeach;
I'd use a combination array_reduce and array_map to transform your data into what you need, then simply loop over that to display your view:
<?php
// Index your $array1 by [id][name]
$array1ByIdAndName = array_reduce($array1, static function ($byIdAndName, $entry) {
$byIdAndName[$entry['course_id']][$entry['name']] = $entry;
return $byIdAndName;
});
// Transform $array2's `attr` entries into attribute list + compute total price
$array2 = array_map(static function ($entry) use ($array1ByIdAndName) {
$entry['total_price'] = $entry['price'];
$entry['attr'] = array_reduce(array_keys($entry['attr']), static function ($attrs, $attrName) use ($array1ByIdAndName, &$entry) {
if ($entry['attr'][$attrName] === 'true') {
$attrs[] = $attrName;
$entry['total_price'] += $array1ByIdAndName[$entry['id']][$attrName]['price'];
}
return $attrs;
}, []);
return $entry;
}, $array2);
// Display your view
?>
<?php foreach ($array2 as $entry): ?>
<h2><?= $entry['name'] ?></h2>
<?php foreach ($entry['attr'] as $attrName): ?>
<p><?= $attrName ?></p>
<?php endforeach ?>
<small>course price : <?= $entry['price'] ?></small>
<?php if ($entry['total_price'] > 0): ?>
<small><?= $entry['total_price'] ?></small>
<?php endif ?>
<?php endforeach ?>
Demo: https://3v4l.org/nS3Gl

Multi-Dimensional PHP array – select data from key

Not sure if I titled this question correctly. I'm having some trouble looping over a multi-demensional php array to build some HTML nodes. Here is the array I'm looping over:
$locations = array(
'CityName' => array(
array(
'title' => 'Title',
'phone' => '(555) 555-5555',
'address' => '1234 Fake st.',
'city' => 'Ventura',
'state' => 'CA',
'zip' => '93003',
'url' => 'http://www.google.com/'
),
array(
'title' => 'Title',
'phone' => '(555) 555-5555',
'address' => '1234 Fake st.',
'city' => 'Ventura',
'state' => 'CA',
'zip' => '93003',
'url' => 'http://www.google.com/'
),
),
'CityName2' => array(
array(
'title' => 'Title',
'phone' => '(555) 555-5555',
'address' => '1234 Fake st.',
'city' => 'Ventura',
'state' => 'CA',
'zip' => '93003',
'url' => 'http://www.google.com/'
),
array(
'title' => 'Title',
'phone' => '(555) 555-5555',
'address' => '1234 Fake st.',
'city' => 'Ventura',
'state' => 'CA',
'zip' => '93003',
'url' => 'http://www.google.com/'
)
)
);
Keep in mind I may have built this array incorrectly for what I'm trying to do. The HTML output for this loop should be:
<h4>CityName</h4>
<ul>
<li>
<p>Title</p>
<p>1234 Fake St.</p>
<p>Ventura, CA 93003</p>
<p>(555) 555-5555</p>
<p class="link">Visit Website</p>
</li>
<li>
<p>Title</p>
<p>1234 Fake St.</p>
<p>Ventura, CA 93003</p>
<p>(555) 555-5555</p>
<p class="link">Visit Website</p>
</li>
</ul>
<h4>CityName2</h4>
<ul>
...
</ul>
I think what I want to do is to be able to grab the individual pieces of data to plug into my HTML template.. like $location['title'], $location['phone'], etc. The PHP that I currently have will only go as far to loop over and echo out the keys or values from each individual location array.
<?php
// Printing all the keys and values one by one
$locationNames = array_keys($locations);
for($i = 0; $i < count($locations); $i++) {
echo "<h4>" . $locationNames[$i] . "</h4>";
echo "<ul>";
foreach($locations[$locationNames[$i]] as $key => $value) {
foreach($value as $key => $value) {
echo $value;
}
}
echo "</ul>";
}
?>
Use nested foreach loops amd drop the values in to the appropriate places:
<?php foreach ($locations as $location => $ldata) { ?>
<h4><?php echo $location; ?></h4>
<ul>
<?php foreach ($ldata as $attribute) { ?>
<li>
<p><?php echo $attribute['title']; ?></p>
<p><?php echo $attribute['address']; ?></p>
<p><?php echo $attribute['city'] . " ," . $attribute['state'] . " " . $attribute['zip']; ?></p>
<p><?php echo $attribute['phone']; ?></p>
<p class="link">Visit Website</p>
</li>
<? php } ?>
<?php } ?>
You just need nested (foreach) loops:
<?php foreach($locations as $cityname => $location):?>
<h4><?=$cityname?></h4>
<ul>
<?php foreach($location as $place:?>
<li>
<p><?=$place['title']?></p>
<p><?=$place['phone']?></p>
<!-- etc etc-->
</li>
<?php endforeach;?>
</ul>
<?php endforeach;?>
Something like this should work. I won't implement the HTML for you, but you it should be easy to do. This has the advantage that if you have dynamic keys in the inner array, you won't have to know them before hand.
foreach($locations as $key => $value) {
echo $key, PHP_EOL;
$data = $locations[$key];
$length = count($data);
for($i = 0; $i < $length; $i++) {
$values = $data[$i];
foreach($values as $key2 => $value2)
echo "\t", $key2, ": ", $value2, PHP_EOL;
}
}
Just a few tweaks to your code:
<?php
// Printing all the keys and values one by one
$locationNames = array_keys($locations);
for($i = 0; $i < count($locations); $i++) {
echo "<h4>" . $locationNames[$i] . "</h4>";
echo "<ul>";
foreach($locations[$locationNames[$i]] as $key => $value) {
echo "<li>"; // add list open tag <-- tweak #1
foreach($value as $key => $value) {
echo "<p>$value</p>"; // add paragraph tags <-- tweak #2
}
echo "</li>"; // add list close tag <-- tweak #3
}
echo "</ul>";
}
?>
PHP Sandbox example.

foreach within array doesnt work, how to add values to to an array?

I have this complicated array.
<?php
require_once('core/connect.php');
require_once('core/database.class.php');
require_once('core/controller.class.php');
require_once('core/settings.class.php');
$database = new Database($db);
$controller = new Controller($db);
$settings = new Settings($db);
$database->selectAll('SELECT * FROM bookings_calendar');
$result = $database->fetchAll();
$count = 0;
$arr = array();
foreach($result as $row)
{
$arr['booking_date'][$count] = $row['booking_date'];
$arr['new'][$count] = $row['new'];
$arr['completed'][$count] = $row['completed'];
$arr['accepted'][$count] = $row['accepted'];
$arr['cancelled'][$count] = $row['cancelled'];
$count++;
}
header("content-type: application/json");
$year = date('Y');
$month = date('m');
echo json_encode(array(
array(
'id' => 111,
'title' => $arr['new'][0] . ' new',
'start' => $arr['booking_date'][0],
'url' => "bookings/ordered-by-date/" . str_replace('-','', $arr['booking_date'][0]),
'color' => '#F7F8E0',
'textColor' => 'black'
),
array(
'id' => 111,
'title' => $arr['new'][1] . ' new',
'start' => $arr['booking_date'][1],
'url' => "bookings/ordered-by-date/" . str_replace('-','', $arr['booking_date'][1]),
'color' => '#F7F8E0',
'textColor' => 'black'
),
array(
'id' => 111,
'title' => $arr['new'][2] . ' new',
'start' => $arr['booking_date'][2],
'url' => "bookings/ordered-by-date/" . str_replace('-','', $arr['booking_date'][2]),
'color' => '#F7F8E0',
'textColor' => 'black'
),
));
?>
As you can see i can only put values manually by changing index, however i'd like to put all elements into that array automatically, but unfortunately i cannot use a foreach loop within an array. And my php skills are not that good, so im searching for some help.
Any help really appreciated. Thanks!
Get rid of the foreach and use a for loop.
$arr = array();
for($i=0; $i < count($result); $i++) {
$arr[$i]['title'] = $result[$i]['new'] . ' new';
$arr[$i]['whatever'] = $result[$i]['whatever'];
}
return json_encode($arr);

Can you compare an array of strings in PHP and if there are two that are the same it will only return it once?

Here is the script I am running and I would like if there are 2 strings that the same to only display one string and not both. I dont know where to add the array_unique() I have added it to my script but it doesnt seem to work properlly, instead it is taking out all the strings with the same value Here is the script I am running and I would like if there are 2 strings that the same to only display one string and not both
//Get slider data from theme options
$company1 = $data['md_media_company_img1'];
$company2 = $data['md_media_company_img2'];
$company3 = $data['md_media_company_img3'];
$company4 = $data['md_media_company_img4'];
$company5 = $data['md_media_company_img5'];
$company6 = $data['md_media_company_img6'];
$company7 = $data['md_media_company_img7'];
$company8 = $data['md_media_company_img8'];
$company9 = $data['md_media_company_img9'];
$company10 = $data['md_media_company_img10'];
$company11 = $data['md_media_company_img11'];
$company12 = $data['md_media_company_img12'];
/*Slides Array*/
$company_name = array(
'company1' => array(
'name' => $company1,
),
'company2' => array(
'name' => $company2,
),
'company3' => array(
'name' => $company3,
),
'company4' => array(
'name' => $company4,
),
'company5' => array(
'name' => $company5,
),
'company6' => array(
'name' => $company6,
),
'company7' => array(
'name' => $company7,
),
'company8' => array(
'name' => $company8,
),
'company9' => array(
'name' => $company9,
),
'company10' => array(
'name' => $company10,
),
'company11' => array(
'name' => $company11,
),
'company12' => array(
'name' => $company12,
)
);
/*check if exist slide*/
$check_exist_company = 0;
$result = array_unique($company_name);
foreach($result as $company => $value) {
if (!empty ($value['name'])){
$check_exist_company = 1;
}
}
?>
<?php if($check_exist_company == 1) {// check if any slide image added in theme option, return custom slide?>
<?php $i = 1; ?>
<?php foreach($company_name as $company => $value) {
if (!empty ($value['name'])) {?>
<li><a class="nivoLink4" rel="<?php echo $i;?>" href="#"><?php echo $value['name'];?></a></li>
<?php ++$i ?>
<?php } ?>
<?php }?>
<?php } ?>
<!--/slider-->
You could just run array_unique() on the source array and just iterate over the result.

Categories