PDO fetch then targeted object? - javascript

I currently have a page where I'm connecting to db via PDO, db, prepare.
Selecting SQL_CALC_FOUND_ROWS in order to have pagination with the results.
All of that is good. However, each return is to have a text popup when clicked. Thats where I want to target a particular field of defined row.
Code I have is as follows :
$db = new PDO('mysql:dbname=###;host=###','###','###');
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = isset($_GET['per-page']) && $_GET['per-page'] <= 50 ?(int)$_GET['per-page'] : 8;
//Positioning
$start = ($page > 1) ? ($page * $perPage) - $perPage : 0;
//Query
$articles = $db->prepare("
SELECT SQL_CALC_FOUND_ROWS id, comment_caption, comment_sub_caption,comment_title, comment_main, comment_name,
comment_date, comment_url
FROM TABLE_NAME
LIMIT {$start}, {$perPage}
");
$articles->execute();
$articles = $articles->fetchAll(PDO::FETCH_ASSOC);
// Pages
$total = $db->query("SELECT FOUND_ROWS() as total")->fetch()['total'];
$pages = ceil($total / $perPage);
//Pagination div
<div class="pagination">
<?php for($x = 1; $x <= $pages; $x++): ?>
<a href="?page=<?php echo $x; ?>&per-page=<?php echo $perPage; ?> "<?php if($page === $x){ echo 'class="selected"'; }?>><?php echo $x ?></a>
<?php endfor; ?>
</div>
// Here is the container for the foreach
<div id="container">
<?php
foreach($articles as $article): ?>
<div class="item small">
<div class="module">
<div class="article">
<div class="item-inner">
<a href="<?php echo $article['comment_url']; ?>">
<div class="project-title">
<div class="mid">
<h2><?php echo $article['comment_caption']; ?></h2>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
// This is the popup that I want to associate with each return
<div id="test-popup" class="white-popup mfp-hide">
<blockquote><?php echo $article['comment_main'];
?></blockquote>
<p><i><?php echo $article['comment_name']; ?> - <?php echo $article['comment_date']; ?></i></p>
</div>
In the popup, I want to echo the 'comments_main, comments_name & comments_date' field of the particular instance that is clicked. Here currently, it just echos the first row.
I'm not sure what the best way to go about it is... ?
Any help would be greatly appreciated.

This is not really a php-mysql related question, but rather a javascript-html-css related one.
You have 2 options:
You output the comments_main, comments_name & comments_date fields to all listed items in a way they are not visible to the users first in the browser. Typically, you could use the anchor element's title property, or html5's data- properties, or even a list of invisible divs. Whenever the user clicks a link, you use javascript to fetch these data for the given comment from your list on the client side (if they are not stored in a list of divs already) and make it appear.
You do not output these data to the client, but upon clicking you use an ajax call to retrieve these data from the server via another php page.
For both approach there are lots of tutorials out there with designed boxes (tooltips) and copy-paste javascript, html, and css code.

Related

Variable assigned to HTML input's value through PHP is not understood by JS script

I'm working on a project of a website which shows a chart. User should be able to change a displayed chart (without changing the website) by clicking one of 'Available sensors' from dropdown options. Dropdown connects to MySQL database with used sensors. The sensor's id is assigned to HTML-input ID and its name is assigned to input value.
My intension is to use sensor ID in another data.php file which is responsible for connecting to tables (MySQL) with data collected by sensors. This ID would tell to which of the tables this programm should connect.
At the moment JS script's task is to alert an ID of the chosen sensor when it's clicked on the dropdown menu. Instead of a number I get a message saying 'undefined'. Eventually it would transfer the stored id to the mentioned data.php file.
Could you please tell me whether it's necessary to use AJAX in this case or what's a possible reason of this error in my code?
I also tried to use button insted of input. When clicking on sensors names on dropdown I've received only messages with '1'. However assigning sensorName worked out in both cases. Sensors ID is stored as INT, name as VARCHAR in MySQL table.
Thank you in advance for your help :)
<div id="header_btn" class="dropdown">
<input type="submit" id="btn" value="Available sensors" class="btn btn-success" />
<div class="dropdown-content">
<?php
include("config.php");
$sql = "SELECT * FROM sensors";
$result = $db->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$sensorID = $row["id"];
$sensorName = $row["WebName"];
?>
<input onclick="changeSensorID(this.value)" onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'" class="btn_drop" id="<?php echo $sensorID ?>" value="<?php echo $sensorName ?>" /></a>
<?php
}
}
?>
</div>
<script>
function changeSensorID() {
var sensorID = document.getElementsByClassName("btn_drop").id;
alert(sensorID);
};
</script>
</div>
please check this code, working fine
<input type="submit" id="btn" value="Available sensors" class="btn btn-success" />
<div class="dropdown-content">
<?php
include("config.php");
$sql = "SELECT * FROM sensors";
$result = $db->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$sensorID = $row["id"];
$sensorName = $row["WebName"];
?><input onclick="changeSensorID(event)" onmouseover="this.style.textDecoration='underline'"
onmouseout="this.style.textDecoration='none'" class="btn_drop" id="<?php echo $sensorID ?>"
value="<?php echo $sensorName ?>" /></a>
<?php
}
}
?>
</div>
<script >
function changeSensorID(event){
var sensorID = event.target.id;
alert(sensorID);
}
</script>
</div>
getElementsByClassName returns array of at least one item if found any. You have to provide index of element that you want to use.
Example
var sensorID = document.getElementsByClassName("btn_drop")[0].id;

Calling PHP Variable from another file without the use of Session or Include

so I'm making a pagination which uses 3 different files. The page itself (index.php), the header which contains a JS Ajax scripts for changing page which is included in the index.php (header.php) and a pagination script contained in a separate PHP file which is called via the AJAX script (pagination.php).
In the index.php I have a variable which defines the category the user is currently in named $category, I would like this variable to be used in the pagination.php to select what results are shown (Only results where subcategory2 = $category).
Because pagination.php is called through an ajax script on document ready it can't see that variable. Is there any way for the two to communicate without the use of Session (which would mess up when changing to other categories) or include (which would end up calling the script twice).
Header.php:
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("/includes/pagination.php");
$(".pagination").bootpag({
total: <?php echo $pages; ?>,
page: 1,
maxVisible: 5
}).on("page", function(e, num){
e.preventDefault();
$("#results").prepend('<div class="loading-indication"><img src="/images/ajax-loader.gif" style="width: 2em; margin: 0 auto;" /><br />Loading...</div>');
$("#results").load("/includes/pagination.php", {'page':num});
});
});
</script>
Pagination.php
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');
//sanitize post value
if(isset($_POST["page"])){
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
if(!is_numeric($page_number)){die('Invalid page number!');} //incase of invalid page number
}else{
$page_number = 1;
}
echo $category;
//get current starting point of records
$position = (($page_number-1) * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($mysqli, "SELECT ProductID, SupplierID, ProductName, ProductDesc, ProductURL, Image1URL, Image2URL, Image3URL, Image4URL, Image5URL, ProductCondition, Stock, AvailabilityDate, ProductGTIN, ProductMPN, ProductBrand, ProductGroupID, ProductColour, ProductGender, ProductAgeGroup, ProductMaterials, ProductSize, ProductPSize, Feature1, Feature2, Feature3, Feature4, Feature5, Feature6, Feature7, Feature8, Feature9, Feature10, CostPrice, Markup, Offer, Shipping, ShippingWeight, ShippingLabel FROM products ORDER BY productid ASC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
echo '
<table id="productbox">
<tr>
<th class="producthead" colspan="3">'.$row["ProductName"].'</th>
</tr>
<tr>
<td class="productimgcell"><img src="'.$row["Image1URL"].'" class="productimg" /></td>
<td class="productinfo">'.$row["Feature1"].'<br />'.$row["Feature2"].'<br />'.$row["Feature3"].'</td>
<td class="productprice"><div class="pricebg">'; echo price_calc($mysqli, $row["ProductID"], $row["CostPrice"], $row["Markup"], $row["Offer"]); echo '<span class="priceinfo">inc. VAT</a></div><div style="clear:both;"></div><div class="addtocartbg">Add To Cart</div></td>
</tr>
<tr>
<td class="productfoot" colspan="3">5/5 Stars - Write A Review</td>
</tr>
</table><br />
';
}
echo '</ul>';
?>
Index.php
<?php
$category = 'AMD';
global $category;
$page_title = 'AMD Motherboards - Motherboards - PC Components';
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
$results = mysqli_query($mysqli,"SELECT COUNT(*) FROM products WHERE SubCategory2 = '$category'");
$get_total_rows = mysqli_fetch_array($results);
$pages = ceil($get_total_rows[0]/$item_per_page);
include_once($_SERVER['DOCUMENT_ROOT'].'/template/header.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/template/sidemenu.php');
?>
<div class="contentboxcontainer">
<div class="centercontentbox">
<div class="halfcontentboxcontainer">
<div class="halfcontentbox">
<div class="contenthead">Deals</div>
<div class="content">
<div class="contentcontainer">
Test
</div>
</div>
</div>
</div>
<div class="halfimgcontentboxl">
<img src="https://assets.vg247.com/current//2015/07/battlefront_leaked_alpha_tatooine_4.jpg" style="border-radius: 5px; width: 100%;" />
</div>
</div>
</div>
<div class="contentboxcontainer">
<div id="contentbox">
<div class="contenthead">Products</div>
<div class="content">
<div id="results"></div>
<div class="pageswrap"><div class="pagination"></div> <div style="clear:both;"></div></div>
</div>
</div>
</div>
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/template/footer.php');
?>
Send the category id as a post variable in the load command.
var cat = <?php echo $category; ?>
$("#results").load("/includes/pagination.php", {'page':num , 'category':cat});
For anyone else interested in an answer for this, I'm going to post my work around just in case anyone might find it useful.
In my pagination.php I added a check for the current page the user is on and compared that to a url I define. If the user is on said page then I define the category there.
pagination.php
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');
if ($_SERVER['HTTP_REFERER'] == $domainurl.'/store/pc-components/motherboards/amd/') {
$category = 'AMD';
}
I had to use $_SERVER['HTTP_REFERER'] due to it being called from JS and $domainurl is defined in my config file (which is included in db_connect.php).
I can now call my variable in a mysql query on pagination.php
FROM products WHERE SubCategory2 = '".$category."'
Not the cleanest of work arounds but it saved me worrying about having to rethink the way I was doing it all.

Adding a second custom field

I have a custom field 'ExtraCSS' which brings in custom post css using the following code. (It is brought in from a 'have_posts()' loop)
html
<?php $extraCSS = get_post_meta(get_the_ID(),'ExtraCSS',true);?><!-- get specific css for post -->
<article>
<div id="post-<?php the_ID(); ?>" class="img-cell" style="background-image:url('<?php echo $thumbnail_url ?>');" <?php post_class('col-md-12'); ?> >
<a class="linkage" href="<?php the_permalink(); ?>"</a>
</div><!-- /#post -->
<div class="text-cell">
<div class="<?php echo $extraCSS?>" >
<h1><?php the_title(); ?></h1>
<h3><?php the_category(', '); ?></h3>
</div>
</div>
</article>
*EDIT
I want to add 1 more custom field ('BG-align') with either values 'BG-align-L' or 'BG-align-R'. I figured I just add another similar line of code under the current one.
ex.
<?php $extraCSS = get_post_meta(get_the_ID(),'ExtraCSS',true);?>
<?php $BGalign = get_post_meta(get_the_ID(),'BGalign',true);?>
but it doesn't work
According to *edit:
'BGalign' have to be defined in post (by "Add New Custom Field"), otherwise it is just empty.
You could set default value (edit "default-value") if not set in post:
<?php
$BGalign = get_post_meta(get_the_ID(),'BGalign',true);
$BGalign = ( !empty($BGalign) ? $BGalign : "default-value" );
?>
Then remember to echo that new php variable. For example:
<div class="<?php echo $extraCSS . " " . $BGalign; ?>" >
. is dot joining variables into one string
" " is empty space for sure that your both classes names will not be connected

JScript within php

The below code included in php file and gets data from data base
$sqlUrl = "SELECT *
FROM $category
WHERE sub_category = '$subCategory'";
$result = mysqli_query($con,$sqlUrl);
now I need to display those data on the screen and thus I would like to load them on am html file in a specific division
<div id="div6">
</div>
I think that I can do it using JScript but I don't know how to do it
What the ... If you just want to print it, you dont need JavaScript:
<div id="div6">
<?php foreach($result as $r) {
echo $r;
} ?>
</div>
why you want to display results with JScript? You can do it like this also:
<div id="div6">
<?php
while ($row = mysqli_fetch_assoc($result)) {
echo $row["Name"]."<br />";
}
?>
</div>
for more details Plese refer: http://in1.php.net/mysqli_fetch_assoc

Trying to display data shown depending on what users click

Have a look here:
http://test.neworgan.org/100/
Scroll down to the community section.
What I'm trying to achieve is to get the data for new organizers, (e.g.: number of friends / amount donated) to show once users click on their thumbnails. right now each user has his or her own unique data stored externally.
Once the users click the thumbnail, 'inline1' appears with the content.
As of now, I'm only able to get the data from the last user to show regardless of whichever user's thumbnails I'm clicking on. I just need a bit of help as to how to change the content depending on which thumbnail users click. So I was wondering if I could have some help here?
Here's that part of the code that matters:
<div class="top-fundraisers-wrapper">
<div class="subsection top-fundraisers">
<?php if ($top_fundraisers && is_array($top_fundraisers)): ?>
<?php foreach ($top_fundraisers as $index => $fundraiser): ?>
<a title="" class="fancybox" href="#inline1">
<div class="top-fundraiser">
<div id="newo<?php print htmlentities($index + 1); ?>" class="top-fundraiser-image">
<img src="<?php
if($fundraiser['member_pic_medium']) {
print htmlentities($fundraiser['member_pic_medium']);
} else {
print $template_dir . '/images/portrait_placeholder.png';
}
?>"/>
</div>
</div>
</a>
<?php endforeach;?>
<?php endif; ?>
</div>
</div>
</div>
<div id="inline1">
<div class="top-fundraiser-image2">
<img src="<?php
if($fundraiser['member_pic_large']) { print htmlentities($fundraiser['member_pic_large']);
} else {
print $template_dir . '/images/portrait_placeholder.png';
}
?>"/>
</div>
<span class="member-name"><?php print htmlentities($fundraiser['member_name']); ?></span>
<span class="friend-count"><?php print number_format($fundraiser['num_donors']) . (($fundraiser['num_donors'] == 1) ? ' Friend' : ' Friends'); ?></span>
<span class="fundraisers-text"> Donated: </span><span class="fundraisers-gold"> $<?php print number_format($fundraiser['total_raised']); ?></span>
</div>
Best way is to use Ajax. Something like this
$("#button").click( function() {
$.ajax({
url: 'file.php',
method: 'post',
data: { id: $(this).val() },
error: function() {
alert('error while requesting...');
}, success: function(data) {
alert( data ); /** received data - best to use son **/
}
});
});
Next parse json var json = $.parseJSON(data);
or ... use dataJson option.
Next Your data should be inserted using class or id to specific location.
Create another loop for content
<?php if ($top_fundraisers && is_array($top_fundraisers)):
$i = 1;
foreach ($top_fundraisers as $index => $fundraiser): ?>
<a title="" class="fancybox" href="#inline<?php echo $i; ?>">
// ... content
<?php $i++;
endforeach;
endif; ?>
And another loop
<?php if ($top_fundraisers && is_array($top_fundraisers)):
$i = 1;
foreach ($top_fundraisers as $index => $fundraiser): ?>
<div id="inline<?php echo $i; ?>">
// inline content here
</div>
<?php $i++;
endforeach;
endif; ?>
Hope your JavaScript function to open fancybox works fine via calling class. So by following code you do not need to play with Javascript code.
Building anchors tags:
<?php
if (!empty($top_fundraisers) && is_array($top_fundraisers)) {
foreach ($top_fundraisers as $index => $fundraiser) {
<a title="" class="fancybox" href="#inline<?php echo $fundraiser['id']; ?>">HTML Content Goes Here</a>
<?php
} //end of foreach
} // end of if condition
?>
Building Popup HTML DOMs:
<?php
if (!empty($top_fundraisers) && is_array($top_fundraisers)) {
foreach ($top_fundraisers as $index => $fundraiser) {
<div id="inline<?php echo $fundraiser['id']; ?>">HTML Content Goes Here</div>
<?php
} //end of foreach
} // end of if condition
?>
You cannot perform this because PHP runs server-side and JavaScript runs in the browser.
To perform this you can use AJAX to get the div as required by user.
...or store the data client-side and change the content of #inline1 based on which item was clicked

Categories