I am new to php and want to create a simple gallery using an extensive file and implementing it in the index.php: I create an array and use a foreach loop to add pictures with some additional info. Something is obviously wrong with the logic or/and the syntax : ( All I get so far is a blank red rectangle.
<?php>
$landscape = array(
'pic1'=> array('name'=>'picture1.jpg','label'=>'p1', 'text'=>''),
'pic2'=> array('name'=>'picture2.jpg','label'=>'p2', 'text'=>''),
'pic3'=> array('name'=>'picture3.jpg','label'=>'p3', 'text'=>''),
'pic4'=> array('name'=>'picture4.jpg','label'=>'p4', 'text'=>''),
);
$galleriya='';
foreach ($landscape as $key => $value) {
$galleriya .= "<div>
<div style='float:left;height:140px;width:200px;border:1px solid red;'>
<img src=$value['name'] alt=''>
</div>"
."<div style='font-size:50px;'>$value['label']</div>"
."<div style='font-size:50px;'>$value['text']</div>
</div>"
};
echo($galleriya);
?>
I've tidied up the syntax stuff within the foreach loop. You need to have a read of this article, which has a brilliant explanation of when to use single and double quotes.
What is the difference between single-quoted and double-quoted strings in PHP?
$landscape = array(
'pic1' => array('name' => 'picture1.jpg', 'label' => 'p1', 'text' => ''),
'pic2' => array('name' => 'picture2.jpg', 'label' => 'p2', 'text' => ''),
'pic3' => array('name' => 'picture3.jpg', 'label' => 'p3', 'text' => ''),
'pic4' => array('name' => 'picture4.jpg', 'label' => 'p4', 'text' => ''),
);
$galleriya = '';
foreach ($landscape as $key => $value) {
'<div style="float:left">'.
'<div style="height:140px;width:200px;border:1px solid red;">
<img src="' . $value["name"] . '">
</div>'
. '<div style="font-size:50px;">' . $value["label"] . '</div>'
. '<div style="font-size:50px;">' . $value["text"] . '</div>
</div>';
}
echo($galleriya);
For the images to display, they will need to be in the same folder as this script. If you wanted to move them to another folder such as images, then the images folder must be in the same place as this script and the source would be modified to (for example):
<img src="images/' . $value["name"] . '"
Related
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>
i have a big array with a lot of subarrays. Each subarray has a few values. Every subarray is an item and values are parameters of that item. I have a searchbar with a POST method. One of the values of the item is name of the item. So if the client is looking for item_one, I need to echo some piece of code with parameters of item_one.
My array looks like this:
$database = [
[
'name'=> 'item_one',
'img_src'=> 'pictures/item_one.jpg',
'preview_href'=> 'item_site.php?id='.item_preview($database).'',
'description'=> 'This product is.....' ,
],
[
'name'=> 'item_two',
'img_src'=> 'pictures/item_two.jpg',
'preview_href'=> 'item_site.php?id='.item_preview($database).'',
'description'=> 'This product is.....' ,
],
// ...
];
and this piece of code i need to use for specific subarray:
echo '<div class="item">
<a href="' . $item['preview_href'] . '" title="' . $item['name'] . '">
<img src="' . $item['img_src'] . '">
<div class="item_description"> '
. $item['name'] . ' ('
. $item['release']
. ') </div>
</a>
</div>'
I have tried loads of different things, for example:
$post = $_POST['search'];
foreach ($database as $item) {
if ($item['name'] == $post) {
echo '<div class="item">
<a href="' . $item['preview_href'] . '" title="' . $item['name'] . '">
<img src="' . $item['img_src'] . '">
<div class="item_description"> ' . $item['name'] . ' (' . $item['release'] . ') </div>
</a>
</div>'
}
}
I have been trying for a few days so I will be happy for any advice. Thanks
Your code is not very forgiving. If the user does not type the name exactly as you have it in your database, you will not get a match.
I would try a couple of things.
if you need exact match:
if( strtoupper($post) === strtoupper($item['name']))
{ // item found}
or, if you want to search for substring, try
if( stripos($item['name'], $post) !== false)
{ //item was found }
I've added two approaches to filter your array using array_filter and array_reduce, both using stripos to test for an occurance of your search keyword with the item's name.
<?php
$items = [
[
'name'=> 'foo',
'img_src'=> 'pictures/item_one.jpg',
'preview_href'=> 'item_site.php?id=1',
'description'=> 'Generic description...' ,
],
[
'name'=> 'cat food',
'img_src'=> 'pictures/item_two.jpg',
'preview_href'=> 'item_site.php?id=2',
'description'=> 'This may smell bad but your cat...' ,
],
[
'name'=> 'dog food',
'img_src'=> 'pictures/item_three.jpg',
'preview_href'=> 'item_site.php?id=2',
'description'=> 'These biscuits...' ,
]
];
$search = 'food';
$matches = array_filter($items, function($item) use ($search) {
if(stripos($item['name'], $search) !== false)
return true;
});
var_export($matches);
$matches = array_reduce($items, function($matches, $item) use ($search) {
if(stripos($item['name'], $search) !== false)
$matches[] = $item;
return $matches;
}, []);
var_export($matches);
Array filter result:
array (
1 =>
array (
'name' => 'cat food',
'img_src' => 'pictures/item_two.jpg',
'preview_href' => 'item_site.php?id=2',
'description' => 'This may smell bad but your cat...',
),
2 =>
array (
'name' => 'dog food',
'img_src' => 'pictures/item_three.jpg',
'preview_href' => 'item_site.php?id=2',
'description' => 'These biscuits...',
),
)
Array reduce result:
array (
0 =>
array (
'name' => 'cat food',
'img_src' => 'pictures/item_two.jpg',
'preview_href' => 'item_site.php?id=2',
'description' => 'This may smell bad but your cat...',
),
1 =>
array (
'name' => 'dog food',
'img_src' => 'pictures/item_three.jpg',
'preview_href' => 'item_site.php?id=2',
'description' => 'These biscuits...',
),
)
You could change your test filter to something like:
if(preg_match("/(\b)$search/i", $item['name']))
This might be useful as word boundaries are respected. A search for oo above would not match. But a search for foo would match all.
You might also want to look at word stemming for your search terms (there are freely available libraries for this).
And/or possibly add and search a non-public field associated with each item containing alternative names/keywords for each item.
For large datasets, you'll probably end up using a database, and can leverage queries to filter resultsets instead of filtering arrays.
You might want to filter user input before:
$search = preg_replace('/[^\sa-zA-Z0-9]/', '', $search); // Remove non word chars but not spaces.
$search = preg_replace('/[\s]+/', ' ', $search); // Replace multiple spaces with one.
Or at least escape with preg_quote before the preg_match.
(You may need to tweak those regexes patterns. I welcome feedback/edits here.)
please help me get through with this.
Everytime I update data from database there is '\' added before the single quote.
For example I have an input that has a value=I'm ok after updating there is '\' will be added.
Sample code from my Model
function update_questionnaire() {
$Cid1 = $this->input->post('Cid1');
$Cid2 = $this->input->post('Cid2');
$Cdata = array(
array(
'choices_id' => $Cid1,
'questionnaire_id_fk' => $Qid,
'choices' => $choice1
),
array(
'choices_id' => $Cid2,
'questionnaire_id_fk' => $Qid,
'choices' => $choice2
)
);
$question = $this->db->escape_like_str($this->input->post('question', TRUE));
$this->db->update_batch('choices', $Cdata, 'choices_id');
}
And sample code from my Controller
$this->form_validation->set_rules('choice1', 'Choice 1', 'required|trim');
$this->form_validation->set_rules('choice2', 'Choice 2', 'required|trim');
And sample code from my View
<?php
$i=0;
foreach ($query as $row):
$i++;
echo '<input type="text" name="choice' . $i . '" id="choice_' . $row->choices_id . '" value="' . trim_slashes($row->choices) . '" class="form-control"/>';
endforeach;
?>
I need help to get the data from my checkbox-group with multidimensional array options to reflect in my post page(single.php code). Radio type is working well but the checkbox-group type is not. I added on the bottom the sample code found in my single.php for the radio type which query the data to my post page for your reference.
Here's the array from my metabox.php code:
<?php
// array
$prefix = 'wtf_';
$meta_box = array( 'id' => 'site',
'title' => 'Program Details',
'page' => 'post',
'context' => 'normal',
'priority' => 'high',
'fields' => array(
array('name' => 'Principal Return',
'desc' => 'Principal Return After Expiry or Not',
'id' => $prefix . 'principal',
'type' => 'radio',
'options' => array(
array('name' => ' Yes ', 'value' => 'Yes-after expiry'),
array('name' => ' No ', 'value' => 'No-included on the interest')
)
),
array(
'name' => 'Compounding',
'desc' => 'Choose if compounding is allowed or not',
'id' => $prefix . 'compounding',
'type' => 'radio',
'options' => array(
array('name' => ' Yes ', 'value' => 'Allowed'),
array('name' => ' No ', 'value' => 'Not Allowed'),
array('name' => ' Re-purchase', 'value' => 'Yes thru re-purchase')
)
),
array ('name' => 'Payment Processors',
'desc' => 'Payment Processsor Accepted',
'id' => $prefix.'processors',
'type' => 'checkbox_group',
'options' => array(
array('label' => ' Liberty Reserve ', 'value' =>'LR'),
array('label' => ' SolidTrustPay ', 'value' =>'STP'),
array('label' => ' EgoPay ', 'value' =>'EgoPay'),
array('label' => ' Perfect Money ', 'value' =>'PM'),
array('label' => ' Payza ', 'value' =>'Payza'),
array('label' => ' PayPal ', 'value' =>'PayPal'),
array('label' => ' Bankwire ', 'value' =>'Bankwire')
))))
// Callback function to show fields in meta box
function mytheme_show_box() {
global $meta_box, $post;
// Use nonce for verification
echo '<input type="hidden" name="mytheme_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
echo '<table class="form-table">';
foreach ($meta_box['fields'] as $field) {
// get current post meta data
$meta = get_post_meta($post->ID, $field['id'], true);
echo '<tr>',
'<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></th>',
'<td>';
switch ($field['type']) {
case 'text':
echo $statetemt;
break;
case 'textarea':
echo $statetemt;
break;
case 'select':
echo $statetemt;
break;
case 'radio':
foreach ($field['options'] as $option) {
echo $statetemt; }
break;
case 'checkbox':
foreach ($field['options'] as $option) {
echo $statetemt;}
break;
case 'checkbox_group':
foreach ($field['options'] as $option) {
echo '<input type="checkbox" value="'.$option['value'].'" name="'.$field['id'].'[]" id="'.$option['value'].'"',$meta && in_array($option['value'], $meta) ? ' checked="checked"' : '',' />',$option['label']; }
echo '<br /><span class="description">'.$field['desc'].'</span>';
break;
}
//From my single.php code <<<<=================
<div class="sdinfo"><strong>Principal Return</strong>:<span><?php $principal = get_post_meta(get_the_ID(), 'wtf_principal', true);
if (isset($principal[0])) {
echo $principal ;
} else if (isset($principal[1])) {
$principal = get_post_meta(get_the_ID(), 'wtf_principal', true);
echo $principal;
} else {_e('Not Available');} ?></span></div>
<div class="sdinfo"><strong>Program Started</strong>:<span> <?php $started = get_post_meta(get_the_ID(), 'wtf_started', true); if (isset($started[0])) { echo $started;
} else {_e('Not Available');} ?></span></div>
<div class="sdinfo"><strong>Compounding</strong>:<span>
<?php $compounding = get_post_meta(get_the_ID(), 'wtf_compounding', true);
if (isset($compounding[0])) {
echo $compounding ;
} else if (isset($compounding[1])) {
$compounding = get_post_meta(get_the_ID(), 'wtf_compounding', true);
echo $compounding;
} else if (isset($compounding[2])) {
$compounding = get_post_meta(get_the_ID(), 'wtf_compounding', true);
echo $compounding;
} else {_e('Not Available');} ?></span></div>
?>
This give me an output from post meta like this:
admin screenshot
This is the output from my post page. :
post page screenshot
Please help!.. I am not a programmer hope you can share me an answer in much details.Thank you in advance!
All what you need is point an array using var_dump($array) to check where and what data you need from arrays fields.
Second you need to get foreach() function. For example you want grab an array of data:
'priority' => 'high', should be as example:
echo $meta_box["priority"] which will result as value of array: high
If you are not sure and not familiar with array use as simple:
foreach ($meta_box as $arr)
{
var_dump($arr);
#then play and manipulate how to grab a fields a data:
foreach ($arr["fields"][""] as $fa)
{
var_dump($fa["name"]);
var_dump($fa["desc"]);
var_dump($fa["desc"]);
}
#...
}
Learn how to grab via var_dump() if you unsure with array of data.
Payment Processors LR STP EgoP
echo $meta_box["fields"][""]["name"];
Than you need grab a data of an array:
foreach ($meta_box["fields"][""]["options"] as $options)
{
foreach ($options as $options_key)
{
foreach ($options_key as $opt_val)
{
$result .= ' '.$opt_val;
}
}
}
I have difficult times to figure out how to manage my loop to not override variables during the process, my example script looks as it follows
$targets = array(
array(
'site_id' => 1,
'url' => array('http://example.com','http://test.com'),
'title' => "Title_1",
'int_link' => "/internal_link/",
'icon' => '/icon_2.gif',
'teaser_index' => 5),
array(
'site_id' => 2,
'url' => array('http://example2.com','http://test2.com'),
'title' => "Title_2",
'int_link' => "/internal_link/",
'icon' => '/icon_2.gif',
'teaser_index' => 5)
)
foreach($targets as $target){
$images = array();
$links = array();
$name = array();
$loop=-1;
foreach($target['url'] as $url){
$loop++;
//parsing $url;
//the insider loop has 2 iterations
if ($loop=1){
$content .="<div>".$target['title'].$url"</div>";
}
else{
$content .="<div>".$target['title'].$url"</div>";
}
}
//write $content html to database, without to override the first $content
}
Your question is not clear but i think i understand what the likely problem might be
There are so many errors in the script which you need to fix maybe your script would run the way you want it to be .
A. $content was not define .. you need to define it
B. if ($loop=1){ should be if ($loop == 1){
C. $content .="<div>".$target['title'].$url"</div>"; is missing . and it should be something like this $content .= "<div>" . $target['title'] . $url . "</div>";
D. You if condition does not make sense since you are outputting the same information
Form what i can see you want to output Title & URL you can as well just use this simple script (Just Guessing)
$targets = array(
array(
'site_id' => 1,
'url' => array('http://example.com','http://test.com'),
'title' => "Title_1",
'int_link' => "/internal_link/",
'icon' => '/icon_2.gif',
'teaser_index' => 5),
array(
'site_id' => 2,
'url' => array('http://example2.com','http://test2.com'),
'title' => "Title_2",
'int_link' => "/internal_link/",
'icon' => '/icon_2.gif',
'teaser_index' => 5)
);
foreach ( $targets as $target ) {
$content = "";
$output = "<div> %s : %s </div>";
$content .= sprintf($output, $target['title'], implode(" , ",$target['url']));
echo $content;
// write $content html to database, without to override the first $content
}
Output
Title_1 : http://example.com , http://test.com
Title_2 : http://example2.com , http://test2.com