So I've made a database where people can upload pictures to. The pictures are linked to a place which is linked to a category.
I'm trying to create a gallery page that displays all the images, and then the categories available. When you click on a category it's meant to show all the pictures for that category.
I've got my categories in my database as well, which I'm using php to echo out:
<?php
include('includes/connectdb.php');
/* Selects id and name from the table 'category' */
$query = "SELECT id, name FROM category";
$result_category = mysqli_query($dbc,$query);
?>
<h1>Category</h1>
<!-- iterate through the WHILE LOOP -->
<?php while($row = mysqli_fetch_array($result_category)): ?>
<!-- Echo out values {id} and {name} -->
<button name="category[]" value=" <?php echo $row['id']; ?> "><?php echo $row['name'] . '<br />'; ?></button>
<?php endwhile; ?>
When a button is clicked I need it to run this php:
<?php
if(isset($_POST['category[]'])){
displayimage();
function displayimage()
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="SELECT pictures.name, pictures.image, pictures.place_id
FROM pictures
INNER JOIN sted
ON pictures.place_id = sted.id
INNER JOIN placecategory
ON sted.id = placecategory.place_id
INNER JOIN category
ON placecategory.category_id = category.id
WHERE placecategory.category_id = $row['id']";
$result=mysql_query($qry,$con);
while($row = mysql_fetch_array($result))
{
//var_dump($row);
echo '<img height="300" width="300" src="data:image;base64,'.$row["image"].' "> ';
echo '<p style="display:inline-block">'.$row["name"].' </p> ';
}
mysql_close($con);
}
}
?>
I found out that it should be possible with ajax, so I added the following to my ajax.php file:
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'category':
category();
break;
}
}
function category() {
displayimage();
function displayimage()
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="SELECT pictures.name, pictures.image, pictures.place_id
FROM pictures
INNER JOIN sted
ON pictures.place_id = sted.id
INNER JOIN placecategory
ON sted.id = placecategory.place_id
INNER JOIN category
ON placecategory.category_id = category.id
WHERE placecategory.category_id = $row['id']";
$result=mysql_query($qry,$con);
while($row = mysql_fetch_array($result))
{
//var_dump($row);
echo '<img height="300" width="300" src="data:image;base64,'.$row["image"].' "> ';
echo '<p style="display:inline-block">'.$row["name"].' </p> ';
}
mysql_close($con);
}
exit;
}
?>
And this to my gallery.php file where I'm displaying the pictures and categories.
<script>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
});
</script>
And lastly I changed my button to be
<?php while($row = mysqli_fetch_array($result_category)): ?>
<!-- Echo out values {id} and {name} -->
<input type="submit" class="button" name="category[]" value=" <?php echo $row['id']; ?> "><?php echo $row['name'] . '<br />'; ?>
<?php endwhile; ?>
I'm linking to the jquery library and I've tested the SQL statement that I need to run, and it works when I specify what the placecategory.category_id is.
Related
I have a page listing articles from a database. When user clicks a tag label they are taken to a blogsbycategory.php page. This page gets the tag parameter from the url and returns all blogs that have this tag. On the right hand side of this page I have a list of tags. How do I change the GET so when a user click a tag in the list, the url parameter will update and they can view all blogs for that chosen tag.
http://example.com/articles/blogsbycategory.php?tag=People%20management
<?php
$tag = $_GET["tag"];
$sql = "select * from blogs where tag = '$tag' " ;
$rs = mysqli_query($connect, $sql);
//get row
$fetchRow = mysqli_fetch_assoc($rs);
?>
<h3>Tags</h3>
<?php
while($row = mysqli_fetch_array($result))
{
echo '<ul style="list-style: none;">';
echo '<li>' .$row["tagName"]. '</li><hr />';
echo '</ul>';
}
?>
Something like this:
<h3>Tags</h3>
<?php
while($row = mysqli_fetch_array($result))
{
echo '<ul style="list-style: none;">';
echo '<li>' . $row["tagName"] . '</li><hr />';
echo '</ul>';
}
?>
With jQuery something like this:
<h3>Tags</h3>
<?php
while($row = mysqli_fetch_array($result))
{
echo '<ul style="list-style: none;">';
echo '<li onclick="$('#articleContainer').load(' . $row["tagName"] . ')">' . $row["tagName"] . '</li><hr />';
echo '</ul>';
}
?>
<div id="art" style="width: 600px; height: 800px; border: 1px solid grey;"></div>
List them as links
<h3>Tags</h3>
<ul>
<?php while($row = mysqli_fetch_array($result)) { ?>
<li><?php echo htmlspecialchars($row["tagName"]); ?></li>
<?php } ?>
</ul>
And please quote the data before you use them in a SQL statement.
I am trying to make a filter for a website for cars. I would like to be able to filter by exterior color. I use exterior to represent my color in the database. My UL puts all color from the database into the box and makes each one a induvial check box. Then I have my page that list of all cars through a SELECT * Statement and then I fetch my results through individual echo statements that are wrap and a div. I Do not want to display my exterior colors name next to each car on this page since I am designing a mobile version and trying to keep it clean. However I have tried to list them as induvial tags and I still get send to a blank page.
<ul class="list-group">
<?php
$sql = "SELECT DISTINCT exterior FROM newcars ORDER BY exterior";
$result = $conn->query($sql);
while($row=$result->fetch_assoc()) {
?>
<li class="list-group-item">
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input product_check" name="" value="<?= $row['exterior']; ?>" id="exterior"><?= $row['exterior']; ?>
</label>
</div>
</li>
<?php
}
?>
</ul>
<div id="test">
<?php
$sql = "SELECT * FROM newcars";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo ("<a href='newcarindex.php?id={$row['id']}'><div class='car'>");
echo '
<tr>
<td>
<img src="data:image\jpeg;base64,'.base64_encode($row['photo']).'"/>
</td>
</tr>
';
echo "<h2 class=car-name>";
echo $row['name'];
echo "</h2>";
echo "<span class=stock>STOCK#";
echo $row['stock'];
echo "</span>";
echo "<h3 class=car-msrp>";
echo $row['msrp'];
echo "</h3>";
echo "</div></a>";
}
} else {
echo "There are no matching results!";
}
?>
</div>
this then leads into my ajax script
<script type="text/javascript">
$(document).ready(function(){
$(".product_check").click(function(){
$("#loader").show();
var action = 'data';
var class = get_filter_text('class');
var body = get_filter_text('body');
var exterior = get_filter_text('exterior');
$.ajax({
url:'action.php',
method:'POST',
data:{action:action,class:class,body:body,exterior:exterior},
success:function(response){
$("#test").html(response);
$("loader").hide();
}
});
});
function get_filter_text(text_id){
var filterData = [];
$('#'+text_id+':checked').each(function(){
filterData.push($(this).val());
});
return filterData;
}
});
</script>
and Finally use a action.php page to connect to my database and filter the results
include 'dbh.php';
if(isset($_POST['action'])) {
$sql = "SELECT * FROM newcars WHERE class !=''";
if(isset($_POST['exterior'])) {
$exterior = implode("','", $_POST['exterior']);
$sql .="AND exterior IN('".$exterior."')";
}
$result = $conn->query($sql);
$output='';
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$photo = base64_encode($row['photo']);
$output .= "<a href='newcarindex.php?id={$row['id']}'>
<div class='car'>
<tr>
<td>
<img src='data:image\jpeg;base64,{$photo}'/>
</td>
</tr>
<h2 class='car-name'>{$row['name']}</h2>
<span class='stock'>STOCK#{$row['stock']}</span>
<h3 class='car-msrp'>{$row['msrp']}</h3>
</div></a>";
}
echo $output;
}
} else {
echo "There are no comments!";
}
}
?>
The Problem I have is every time i click on a color to filter by my page comes up blank showing no results or errors. What am I doing wrong?
just looking at the action.php, upon a successful query, I don't see $output being echoed. Is this the complete code for the action.php?
include 'dbh.php';
if(isset($_POST['action'])) {
$sql = "SELECT * FROM newcars WHERE class !=''";
if(isset($_POST['exterior'])) {
$exterior = implode("','", $_POST['exterior']);
$sql .="AND exterior IN('".$exterior."')";
}
$result = $conn->query($sql);
$output='';
if($result->num_rows>0){
while($row=$result->fetch_assoc()) {
$photo = base64_encode($row['photo']);
$output .= "<a href='newcarindex.php?id={$row['id']}'>
<div class='car'>
<tr>
<td>
<img src='data:image\jpeg;base64,{$photo}'/>
</td>
</tr>
<h2 class='car-name'>{$row['name']}</h2>
<span class='stock'>STOCK#{$row['stock']}</span>
<h3 class='car-msrp'>{$row['msrp']}</h3>
</div></a>";
}
echo $output;
} else {
echo "There are no comments!";
}
}
?>
```
I'm having a hard time displaying the title and note on each row of my database. I want to display one row (with the title and note) after each
from a form in a page heading to the displaying of row datas page.
This is my code below:
//
Let's say that we have 4 rows of datas. In my code, I can only display the first row, because it keeps having the first row's data. This is because the form is in the first php file. Then after I submit the form, it's directed to this file, and it keeps getting the first row.
<?php $con=mysqli_connect("localhost","root","","task");?>
<?php $results = mysqli_query($con, "SELECT * FROM note"); ?>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<?php
$id=$row['id'];
echo ' ';
echo '<button class="call_modal" data-id="$id" style="cursor:pointer;">'. $row['title'] . '</button>';
?>
<?php
}?>
<?php $results = mysqli_query($con, "SELECT * FROM note"); ?>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<div class="note" data-id="<?= $row['id'] ?>">
<div class="modal">
<div class="modal_close close"></div>
<div class="modal_main">
<?php
echo '<br><br>';
echo '<div class="padding">'.$row['title'].'';
echo '<br><br><br><br>';
echo ''.$row['note'].'</div>';
?>
</div>
</div>
<?php
}?>
<?php
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
} ?>
The code below is not tested but it should be correct and give you a better idea of what you are doing right/wrong. I hope it helps..
<?php
$con=mysqli_connect("localhost","root","","task");
$results = mysqli_query($con, "SELECT * FROM note");
while ($row = mysqli_fetch_array($results)) { //starting your data row loop
$id=$row['id'];// you are creating a variable here but not using it two lines down.
echo ' ';
//YOUR OLD CODE echo '<button class="call_modal" data-id="$id" style="cursor:pointer;">'. $row['title'] . '</button>';
echo '<button class="call_modal" data-id="$id" style="cursor:pointer;">'. $id . '</button>';// use the variable "$id" that you created here
// You dont need the next two lines, you already did a query and have the data loaded in the "$results" array
/* $results = mysqli_query($con, "SELECT * FROM note");
while ($row = mysqli_fetch_array($results)) */
?> // close the php tag if you are going to switch to html instead of "echoing html"
/* OLD CODE <div class="note" data-id="<?= $row['id'] ?>"> you were missing the "php" in the php tags */
<div class="note" data-id="<?php echo $id; ?>"> // corrected code
<div class="modal">
<div class="modal_close close"></div>
<div class="modal_main">
<?php //switching back to php so create your open tag again...
echo '<br><br>';
echo '<div class="padding">'.$row['title'].'';
echo '<br><br><br><br>';
echo ''.$row['note'].'</div>';// you dont NEED the '' before .$row.... unless you want it but its just essentially a blank string
?>
</div>
</div>
<?php
} // ending your "for each data row" here
?>
<?php
// PS you're not using this function anywhere unless its in ommited code?
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
} ?>
In your loop you're using mysqli_fetch_array, which returns an array with each element in that array containing the field value.
What you want is mysqli_fetch_assoc instead, this will return a hash which you can then use the way you're using it now.
Another thing is that you don't need to have 2 loops in there querying the database. And please indent your code, it makes it really hard for you and everyone else to read it.
Here is the updated/cleaned up version of your code. This has been tested, you can find a sample code with instructions to run on my Github here.
<?php
$con = mysqli_connect("localhost", "root", "", "task");
$results = mysqli_query($con, "SELECT * FROM note");
while ($row = mysqli_fetch_assoc($results)) {
$id = $row['id'];
echo ' ';
echo '<button class="call_modal" data-id="' . $id . '" style="cursor:pointer;">'. $row['title'] . '</button>';
?>
<div class="note" data-id="<?= $row['id'] ?>">
<div class="modal">
<div class="modal_close close"></div>
<div class="modal_main">
<?php
echo '<br /><br />';
echo '<div class="padding">' . $row['title'];
echo '<br /><br /><br /><br />';
echo $row['note'];
echo '</div>'
?>
</div>
</div>
</div>
</div>
<?php
}
?>
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I have created two select boxes each have different country names with flag images using select2 plugin and values are fetching from Database below is the code.
JS CODE
$(".currencyconverterselect").select2({
templateResult: addflag,
templateSelection: addflag
});
function addflag(opt) {
if (!opt.id) {
return opt.text;
}
var $opt = $(
'<span><img src="./img/flags/' + $(opt.element).attr('data-country-code') + '.png" class="userPic" /> ' + $(opt.element).text() + '</span>'
);
return $opt;
};
HTML CODE
<label style="color:white">Currency from</label>
<select name="fromcurrency_cc" id="fromcurrency_cc" class="form-control charts_currency" style="width:100%" required="required">
<?php
$sql = "SELECT fc.country_id,fc.code,fc.name,cc.country_code AS countrycode FROM fx_currency fc LEFT JOIN fx_country cc ON fc.country_id = cc.id ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ($row['code'] == 'AED')
{ ?>
<option data-country-code='<?php echo $row['countrycode']; ?>' value="<?php echo $row['code']; ?><?php echo $row['countrycode']; ?>" selected>
<?php echo $row['name']; ?>(
<?php echo $row['code']; ?> )</option>
<?php } else { ?>
<option data-country-code='<?php echo $row['countrycode']; ?>' value="<?php echo $row['code']; ?><?php echo $row['countrycode']; ?>">
<?php echo $row['name']; ?>(
<?php echo $row['code']; ?> )</option>
<?php }}
} else {
echo "0 results";
}
?>
</select>
I have also created a button below is the code
</i>
I want to swap the value of FROM currency to TO Currency and vice versa by clicking the button.
I have tried below code
$("#swapvalues_btn1").on('click', function() {
var pickup = $('#fromcurrency_cc').val();
$('#from').val($('#tocurrency').val());
$('#to').val(pickup);
});
Select2 will listen for the change event on the that it is attached to. If you make any external changes that need to be reflected in Select2 (such as changing the value).
Just use below code
$("#swapvalues_btn1").on('click', function() {
var fromcurrency = $('#fromcurrency').val();
var tocurrency = $('#tocurrency').val();
$('#fromcurrency').val(tocurrency).trigger('change');
$('#tocurrency').val(fromcurrency).trigger('change');
});
For More follow the link
https://select2.github.io/options.html#events
i am doing a php script wherein I need to remember the checked checkbox and save it all the database. Unfortunately, my code save only the current page where I checked the checkbox but the other checked box became unchecked.
Example In Page 1 I checked 3 items, on the second page I checked I tem. When I click the submit button I only got the checked item of the current page. And when I go back to the previous page the item that I checked became unchecked.How can I preserved and save the value of my checked checkbox through pagination?
here is my code for CreateTest.php
<html>
<body>
<?php
ob_start();
session_start();
include("connect.php");
error_reporting(0);
$item_per_page=10;
$results = mysqli_query($con,"SELECT COUNT(*) FROM tblitem");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<=$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?><!DOCTYPE html>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
});
</script>
<form name="myform" action="CreateTest.php" method="POST" onsubmit="return checkTheBox();" autocomplete="off">
<body>
<?php
if(isset($_POST['save'])){
$testPrice = $_POST['testPrice'];
$testName = $_POST['testName'];
$items = $_POST['items'];
$quantity = $_POST['quantity'];
$testDept = $_POST['testDept'];
$measurement = $_POST['measurement'];
global $con;
Tool::SP_Tests_Insert(strip_tags(ucwords($testName)), $testPrice, $testDept);
$result = mysqli_query($con, "SELECT MAX(TestID) FROM lis.tbltests");
$data= mysqli_fetch_array($result);
$testID=$data[0];
foreach ($items as $key => $value){
$checkedItem[] = $value;
echo $value, " | ",$quantity[$key], " | ",$measurement[$key], "<br>";
mysqli_query($con,"INSERT INTO tbltestitem (TestID, ItemID, ItemQuantity, ItemMeasurement) VALUES ($testID, $value, '$quantity[$key]', '$measurement[$key]')");
}
echo "<script type='text/javascript'>alert('Succesfully added test!')</script>";
$site_url = "tests.php";
echo "<script language=\"JavaScript\">{location.href=\"$site_url\"; self.focus(); }</script>";
}else if(!isset($_POST['save'])){
$selectDept='';
$result= mysqli_query($con,"select * from tbldepartment");
$selectDept.="<option value=''>Select Department:</option>";
while($data = mysqli_fetch_array($result)){
$selectDept.="<option value='{$data['DeptID']}'>{$data['DeptName']}</option>";
}
?>
<td style="vertical-align: top;">
<body>
<div id="container" align="center">
<div id="title">Create Test</div>
<div id="a">Input Test Name:</div><div id="b"><input type="text" name="testName" id="myTextBox" onkeyup="saveValue();" ></div>
<div id="a">Input Test Price:</div><div id="b"><input type="number" name="testPrice"></div>
<div id="a">Select Department:</div><div id="b"><select name="testDept" ><?php echo $selectDept; ?></select></div>
<div id="results"></div><div id="a"><?php echo $pagination; ?></div>
<div align="right" style="padding: 10px;"><input type="submit" name="save" value="Submit"></div> </div>
<?php
}
?>
</body>
</html>
This is my fetch_pages.php code.
this php page help me to keep the textbox values through pagination through jquery it will be loaded without going the another page of pagination
<?php
include("connect.php");
require_once('classes/tool.php');
$item_per_page=10;
//sanitize post value
$page_number = $_POST["page"];
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($con,"SELECT * FROM tblitem ORDER BY ItemID ASC LIMIT $position, $item_per_page");
$connection=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$selectMeasure='';
$measurements = Tool::SP_Measurement_Select();
foreach($measurements as $measure) {
$selectMeasure.='<option value=' . $measure['MeaName'] . '>' . $measure['MeaName'] . '</option>';
$i=0;
while($item = mysqli_fetch_array($results))
{
echo "<div id='a'><input type='checkbox' name='items[$i]' id='item[]' value='". $item['ItemID'] ."' >".$item['ItemName']."</div>";
echo "<div id='b'><input type='number' name='quantity[$i]' class='quantity' /></div>";
echo "<div id='b'><select name='measurement[$i]' class='quantity'>'".$selectMeasure."'</select></div>";
$i++;
}
?>
Hope you can help me. Thanks in advance
Ugg... way too much code to look through.
The short answer, however, is that you pass values from one form to another using <input type-"hidden"...> markup.
Warning, code type free-hand
Page1.php
<form action="page2.php">
<div>
<input type="checkbox" name="test1">
</div>
</form>
Page2.php
<?php
if (is_set($_REQUEST["test1"])) {
$test1 = $_REQUEST["test1"];
} else {
$test1 = false;
}
<form action="page3.php">
<div>
<input type="hidden" name="test1" value="<?php echo $test1 ?>">
</div>
</form>
Page3.php
<?php
$test1 = $_REQUEST["test1"];
?>