Show count instead of duplicate values on select - PHP - php

I'm trying to build a demo website showcasing the food and/or products in your home ie. fridge or freezer.
I've got most of it down, dynamically creating a list with the items, but I would like to have the duplicates count up like 1x [product] instead of just appearing multiple times in the list like this:
.
My query and stuff looks like this - all inside a for loop.
$sql = "SELECT * FROM goods WHERE person_id = " . $_SESSION['ID'] . " AND room LIKE '" . $rooms[$count] . "'";
if ($result = mysqli_query($conn, $sql)){
if (mysqli_num_rows($result) > 0){
$output = "<ul>";
while ($row = mysqli_fetch_array($result)){
$output .= "<li class='varer'> " . $row['name'] . "</li>";
}
$output .= "</ul>";
}
}
Hope you can help - I'm not that experienced with PHP :)

Check the following code where I show you how to have a group by to have the quantity per item and also, how to use query with prepared statements to avoid sql injection:
// prepare and bind
$stmt = $conn->prepare("SELECT COUNT(*) AS QUANTITY, * FROM goods WHERE person_id = ? AND room LIKE ? BROUP BY name");
$stmt->bind_param("ii", $_SESSION['ID'], $rooms[$count]);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
if ($result) {
$output = "<ul>";
while ($row = $stmt->fetch_assoc()) {
$output .= "<li class='varer'> " . $row['QUANTITY'] . "x " . $row['name'] . "</li>";
}
$output .= "</ul>";
}

(using prepared statements)
$sql = "SELECT room,count(*) FROM goods WHERE person_id = ? AND room LIKE ? ";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $_SESSION['ID'], $rooms[$count]);
$stmt->execute();
result = $stmt->get_result();
if( $result->num_rows > 0 ){
$output = "<ul>";
while ($row = $result->fetch_assoc()){
$output .= "<li class='varer'> " . $row['name'] . "</li>";
}
$output .= "</ul>";
}
$stmt->close();

Related

how can i get a php variable outside a while loop which is in a function

function getTowns($conn)
{
$sql = "SELECT towns.name, towns.id, regions.name AS region_name FROM towns INNER JOIN regions ON towns.region_id = regions.id ORDER BY name ASC";
$result = $conn->query($sql);
$town_opt = ''; //stands for town option
town_opt .= "<datalist id='townlist'>";
while ($row = $result->fetch_assoc()) {
$town_id = $row['id'];
$town_opt .= "<option>" . $row['name'] . ", " . $row['region_name'] . "</option>";
}
$town_opt .= "</datalist>";
return $town_opt;
};
echo $town_id;
echo getTowns($conn);
//how can I echo every town id?
This is the best I could think of, and yet it doesn't work. I tried setting a cookie but it still wasn't working the way I wanted.
function getTowns($conn)
{
$sql = "SELECT towns.name, towns.id, regions.name AS region_name FROM towns INNER JOIN regions ON towns.region_id = regions.id ORDER BY name ASC";
$result = $conn->query($sql);
$town_opt = ''; //stands for town option
// We first set the town_id placeholder
$town_id = array();
town_opt .= "<datalist id='townlist'>";
while ($row = $result->fetch_assoc())
{
// We add the ID into our array
$town_id[] = $row['id'];
$town_opt .= "<option>" . $row['name'] . ", " . $row['region_name'] . "</option>";
}
$town_opt .= "</datalist>";
// We return an array
return array($town_opt, $town_id);
/* Or you could use this
return array('town_opt' => $town_opt, 'town_id' => $town_id);
And then use them like so:
$towns = getTowns($conn);
// $town_opt
echo $towns['town_opt'];
// $town_id
print_r($towns['town_id]);
*/
};
$towns = getTowns($conn);
// $town_opt
echo $towns[0];
// $town_id
print_r($towns[1]);
return an array with the first value being one value you want and the second as the other

PHP array implode keys and values to function

I'm not too familiar with PHP arrays, I have the following code that generates query to output the results needed.
$allstore = $_POST['store'];
function createSelect($allstore)
{
if (empty($allstore))
return "";
$querySelect = "";
$queryJoin = "";
$baseTable = "";
foreach ($allstore as $store => $value) {
if (!$querySelect) {
$baseTable = $store;
$querySelect = "SELECT " . $store . ".item_no, " . $store . ".actual_price, " . $store . ".selling_price, " . $store . ".qty as " . $store;
} else {
$querySelect .= ", " . $store . ".qty as " . $store;
$queryJoin .= "
INNER JOIN " . $store . " ON " . $baseTable . ".item_no = " . $store . ".item_no";
}
}
$querySelect .= " FROM " . $baseTable;
$query = $querySelect . $queryJoin;
return $query;
}
//Stores to be shown
$allstore = ['s_M9' =>0 , 's_M10' =>1];
$query = (createSelect($allstore));
$result = mysql_query($query);
//rest of code...
As you can see above, at the very top there is $allstore = $_POST['store']; Which collects values based from previous form POST method that has checkbox with the name=store[] .
Now According to the function shown, if I create my own keys and values like this
$allstore = ['s_M9' =>0 , 's_M10' =>1];
the output shows exactly what i'm looking for. But the problem goes on how to let $allstore implode those stores s_M9, s_M10 based on what the user has selected on the previous page ( checkbox )? I mean, the user can select either one of the stores or Both stores . How can I implode the checked results between those brackets without inserting them manually?
Thank You
Edit :
<?php
echo "<form action='somewhere.php' method='POST'>";
$query = "SELECT * from stores_list ORDER BY short Asc";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row = mysql_fetch_assoc($result);
echo "<input type=checkbox name=store[] value={$row['short']} style='width:20px; height:20px;'>{$row['short']}";
}
}
else{
//No Stores Available
echo "No Stores Found !";
}
echo "</td><input type='submit' value='Search'/></form>";
$allstore = [];
if (!empty($_POST['store'])) {
foreach ($_POST['store'] as $value) {
$allstore[$value] = 1; // or 0, it doesn't matter because your function adds all the keys
}
}
$query = (createSelect($allstore));
$result = mysql_query($query);
And of course you have to take care of your createSelect function to avoid SQL Injections, please read here

Select * from table not working SQL

I am trying to select all records from a table and then output them below, however I am only able to get the most recent output out.
The table structure is Id, Start, End, DistanceDirections and Date
I am using the code below to get them and then output each Start as a H1 on the page. As mentioned I am only getting the last value out not all as I would expect, I have also tried to be more specific which can be seen in the code below that and it didn't have an effect on the result.
$sql = "SELECT * FROM `searchdata`";
$stmt = $conn->prepare($sql);
$stmt->execute();
foreach($stmt as $row) {
$htmlResult = "<h1>" . $row['Start'] . "</h1>";
}
Here is the other try:
$sql = "SELECT * FROM `searchdata` WHERE DistanceDirections = 'distance'";
$stmt = $conn->prepare($sql);
$stmt->execute();
foreach($stmt as $row) {
$htmlResult = "<h1>" . $row['Start'] . "</h1>";
}
Is there something simple I am missing?
You're only executing the query, you'll also need to fetch the rows.
$sql = "SELECT * FROM `searchdata`";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
$htmlResult = "";
foreach($result as $row) {
$htmlResult .= "<h1>" . $row['Start'] . "</h1>";
}
echo $htmlResult;
More info:http://php.net/manual/en/pdostatement.fetchall.php

PHP select field from nested query

I am running a query on 2 tables, to return information from a blog. The nested query selects the tags that are associated with that blog, which is a separate table.
I want to be able to get the 'tag' row from the 'tags' table and display these on the page. My code is below and I have commented where I would like the rows to be selected.
<?php
include("inc/dbconnection.php");
$id = $_GET['tag'];
$id = trim($id);
$result = mysqli_query($conn, "
SELECT *
FROM blog
WHERE blog_id IN (SELECT blog_id FROM tags WHERE tag = '$id')
");
if (!$result) {
die("Database query failed: " . mysqli_error($conn));
} //!$result
else {
$rows = mysqli_num_rows($result);
if ($rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$content = $row['content'];
$content2 = substr($content, 0, 100);
/* Below is where I would like to pull the row 'tag' from the nested query */
$rawTag = $row['tag'];
$tag = str_replace(" ", "", $rawTag);
$tagArray = explode(",", $tag);
$tag = "";
for ($i = 0; $i < count($tagArray); $i++) {
$tag .= "<a href='tag-" . $tagArray[$i] . ".php'>" . $tagArray[$i] . "</a> ";
} //$i = 0; $i < count($tagArray); $i++
echo "
<table>
<tr>
<th>
<a href='blog-" . $row['blog_id'] . ".php'>
<h2>" . $row['title'] . "</h2>
</a>
</th>
</tr>
<tr>
<td>
<p>" . date("d/m/Y", strtotime($row['createdDate'])) . "</p><br />
<span>" . $content2 . "...</span><br />
<span><small>Tags: " . $tag . "</small></span>
</td>
</tr>
</table>";
} //$row = mysqli_fetch_array($result, MYSQLi_ASSOC)
} //$rows > 0
else { //$rows > 0
echo "<br /><h1>There are currently no blogs with the selected tag (" . $_GET['tag'] . ")</h1><br /><h2>Please check back later.</h2>";
}
}
?>
Sorry if this is a stupid question and thanks in advance for your help :)
There are two part one is Query and second is data display.So Data display is total based
on your business call (how to display tag data in HTML.. )
but here you can optimize first part
(query for fetching data) as below:
$result = mysqli_query($conn, "SELECT b.*, t.* FROM blog b inner join tags t on
b.blog_id= t.blog_id WHERE t.blog_id '" . $id . "')");
Please use this.

$_Get not getting url id

*fixed****
echo "<li>" . $row['iname'] . "</li>";
what is missing ?
.php
/facepalm
I can't seem to get the id value to pass to the $_GET. I've tried adding sessions and all kinds of stuff.
Even when I just do a print_r($GET) by itself it gives me :
The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for
this address in a way that will never complete
This is not for production, but a project so I'm not to worried about injections ect..
I've use GET with old php mysql syntax and it works, just not sure what the problem is. Alos no the code is barbaric so any help would be greatly appreciated.
Page 1 :
<?php
require('lib/inc/db_inc.php');
$sql = "SELECT items.itemID, items.iname, items.idesc, items.iprice,iimg.imgURL FROM items JOIN iimg ON items.itemID = iimg.pid WHERE items.itype = 'usb_controllers'";
$stmt = $db->query($sql);
while ($row = $stmt->fetch()){
$id = $row['itemID'];
echo "<div class=\"prodMain\">";
echo "<div class=\"img\">";
echo "<img src=\"" . $row['imgURL'] ."\"/>";
echo "</div>";
echo "<ul>";
echo "<li>" . $row['iname'] . "</li>";
echo "<li>" . $row['idesc'] . "</li>";
echo "<li>" . $row['iprice'] . "</li>";
echo "</ul>";
echo "</div>";
}
?>
page 2 :
<?php
require('../lib/inc/db_inc.php');
if (!isset($_GET['id'])) {
die("missing query parameter");
}
$id = intval($_GET['id']);
if ($id === '') {
die("Invalid query parameter");
}
$sql = "SELECT items.itemID, items.iname, items.idesc, items.iprice,iimg.imgURL FROM items JOIN iimg ON items.itemID = iimg.pid WHERE itemID = '$id'";
$stmt = $db->query($sql);
$row = $stmt->fetch();
echo print_r($row);
?>
db_inc.php
<?php
try {
$db = new PDO('mysql:host=******;dbname=*****', '*********', '********');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
This statement
$sql = "SELECT items.itemID, items.iname, items.idesc, items.iprice, iimg.imgURL FROM items JOIN iimg ON items.itemID = iimg.pid WHERE itemID = '$id'";
$stmt = $db->query($sql);
has a vulnerability for SQL Injection. See here.
So you should rewrite it like
$sql = "SELECT items.itemID, items.iname, items.idesc, items.iprice, iimg.imgURL FROM items JOIN iimg ON items.itemID = iimg.pid WHERE itemID = ?";
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));

Categories