How to send all possible WHERE options to mysqli? - php

Hello everyone I am sending 3 var via form / select / input to mysqli_fetch which creates div with another var and put there image which have same id as name.jpg.
Question : How to make option all for instance in colors to send all possible colors to $color_val?
<form action="produkt.php" method="post">
<!-- COLOR-->
<li>
<img class="img_search_bar" src="../img/search/color.jpg" />
<select id="color" name="color">
<option value="all" selected="selected">ALL</option>
<option value="blue">blue</option>
<option value="red">red</option>
<option value="black">black</option>
<option value="white">white</option>
</select>
</li>
<!-- 2 more like this for size and type-->
<INPUT TYPE="submit" name="submit" /></a> <!-- refresh page-->
</form>
<?php
if(isset($_POST['submit'])){
// Storing Selected Value In Variable
$color_val = $_POST['color'];
$size_val = $_POST['size'];
$type_val = $_POST['type'];
// Displaying Selected Value
echo "COLOR :" .$color_val;
echo "<br>SIZE :" .$size_val;
echo "<br>TYPE :" .$type_val;
//making connection to database
$link = mysqli_connect("localhost", "root","" ,"test");
//selecting query from database where var = select var
$query = "SELECT * FROM testtable WHERE color = '$color_val' AND size ='$size_val' AND type = '$type_val'";
if ($result = mysqli_query($link, $query)){
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
printf ("
<div id='produkt_table'>
<img class='produkt_ikon' src='../img/produkt/ikon/%s.jpg'>
<h3> name : name </h3>
<h4> Prize : %s </h4>
<h5> Stock : %s </h5>
</div>
", $row["id"], $row["prize"], $row["stock"]);
}
/* free result set */
mysqli_free_result($result);
}
}
/* close connection mysqli_close($link);*/
?>

BIG FAT WARNING: YOUR CODE IS INSECURE, SO IS MY EXAMPLE! READ BOTTOM FOR MORE!
Your description is very vague, but I give it a try.
$query = "SELECT * FROM testtable WHERE color = '$color_val' AND size ='$size_val' AND type = '$type_val'";
If you want to match all colors when $color_val === 'ALL', you have to make the query conditional.
Note: this code and your code is INSECURE
if ($color_val === 'ALL' && empty($color_val)) {
$query = "SELECT * FROM testtable WHERE size ='$size_val' AND type = '$type_val'";
} else {
$query = "SELECT * FROM testtable WHERE color = '$color_val' AND size ='$size_val' AND type = '$type_val'";
}
About that Security-Thing
Your code is open to SQL injection, I suggest you start reading the PHP Manual on it or simply google for it.
You don't validate, you don't escape, you could just give away the password to your database as well.

The following code should do. I have made slight changes in your code to get this. You could now optimize this too.
the changes
in html part i have changed the value of option 'all' to 1. this is to easily check the condition in the back end.
The variable $Query_appender is used to store part of the query. if there is a specific color coming through, it will carry the condition else it will carry simply 1.
now i have modified your query to change the color condition to last and appended the value in the variable.
This said, if its just the color, you can check the value of the post variable and write two different queries in a conditional statement.
<form action="produkt.php" method="post">
<!-- COLOR-->
<li>
<img class="img_search_bar" src="../img/search/color.jpg" />
<select id="color" name="color">
<option value="1" selected="selected">ALL</option>
<option value="blue">blue</option>
<option value="red">red</option>
<option value="black">black</option>
<option value="white">white</option>
</select>
</li>
<!-- 2 more like this for size and type-->
<INPUT TYPE="submit" name="submit" /></a> <!-- refresh page-->
</form>
<?php
if(isset($_POST['submit'])){
// Storing Selected Value In Variable
$color_val = $_POST['color'];
$size_val = $_POST['size'];
$type_val = $_POST['type'];
$Query_appender = '1';
if($color_val!=1)
{
$query_appender = "color = '$color_val'";}
// Displaying Selected Value
echo "COLOR :" .$color_val;
echo "<br>SIZE :" .$size_val;
echo "<br>TYPE :" .$type_val;
//making connection to database
$link = mysqli_connect("localhost", "root","" ,"test");
//selecting query from database where var = select var
$query = "SELECT * FROM testtable WHERE size ='$size_val' AND type = '$type_val' AND ".$Query_appender;
if ($result = mysqli_query($link, $query)){
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
printf ("
<div id='produkt_table'>
<img class='produkt_ikon' src='../img/produkt/ikon/%s.jpg'>
<h3> name : name </h3>
<h4> Prize : %s </h4>
<h5> Stock : %s </h5>
</div>
", $row["id"], $row["prize"], $row["stock"]);
}
/* free result set */
mysqli_free_result($result);
}
}
/* close connection mysqli_close($link);*/
?>

Try putting this in place of $query = "SELECT * FROM testtable WHERE size ='$size_val' AND type = '$type_val' AND ".$Query_appender;
$query = "SELECT * FROM testtable";
if($color_val !='all' || $size_val !='all' || $type_val !='all')
{
$query_arr = array();
if($color_val !='all')
{
$query_arr[] = "color = '$color_val'";
}
if($size_val !='all')
{
$query_arr[] = "size ='$size_val'";
}
if($type_val !='all')
{
$query_arr[] = "type = '$type_val'";
}
$query .=" where ".implode(" AND ", $query_arr);
}

Related

How would i be able to sort the category that i filtered with MYSQL?

How would i be able to sort the category that i filtered with MYSQL?
For example i would like to get the cheapest hat.What would i have to do?
if(isset($_GET['category'])){
$category = $_GET['category'];
$sql = "SELECT * FROM store WHERE category='$category'";}else{
$sql = "SELECT id,title,image FROM store";
}
if(isset($_GET['category'],$_GET['value'])){
$currentPage = $_GET['category'];
$value = $_GET['value'];
$sql = "SELECT * FROM store WHERE category='$category'ORDER BY $value";
}
if(isset($_GET['value'])) {
if($_GET['value'] == 'price') {
// query to get all by price
$sql = "SELECT * FROM store ORDER BY price";
}
elseif($_GET['value'] == 'title') {
// query to get all by title
$sql = "SELECT * FROM store ORDER BY title";
} elseif($_GET['value']== 'date') {
// query to get all by date added
$sql = "SELECT * FROM store ORDER BY date_added";
}
`
<div id="filters">
All
T-Shirt
Mug
Hat
</div>
<label for="sort">Sort By</label>
<select name="sort">
<option value="price">Price: Low to High</option>
<option value="title">Title: A-Z</option>
<option value="date">Newest</option>
</select>
/*****
To my eyes I do not see how you can get what you want by using your given HTML. So what I've done is placing category and sort as form inputs. In this way we can easily manipulate with category and sort.
The form method here is GET. POST would have meant if(isset($_POST)).
Hope this helps.
******/
// Define category
if(isset($_GET['category'])){
$category = $_GET['category'];
}
// Define order of result
if(isset($_GET['sort'])){
$sort = $_GET['sort'];
}
// When the form is submitted
if(isset($_GET['submit'])){
// Select based on category input and order result based on sort input
$sql = "SELECT * FROM store WHERE category='$category' ORDER BY $sort";
}
<forrm action="store.php" method="GET">
<label for="category">Category</label>
<select name="category">
<option value="t-shirt">T-Shirt</option>
<option value="mug">Mug</option>
<option value="hat">Hat</option>
</select>
<label for="sort">Sort By</label>
<select name="sort">
<option value="price">Price: Low to High</option>
<option value="title">Title: A-Z</option>
<option value="date">Newest</option>
</select>
<input type='submit' name='submit' />
</form>

How to convert the blob image from binary to real image in database when it uploaded from PHP page?

The problem is when I uploaded the blob image to the product table from PHP page it seems as binary, but if do that manually that's working.
Please see the link image under the code to what I mean.
Cheers!
<?php
//connect to the server and create database.
$host = "localhost";
$userMS = "";
$passwordMS = "";
$connection = mysql_connect($host,$userMS,$passwordMS) or die("Couldn't connect:".mysql_error());
$database = "projectDataBase";
$db = mysql_select_db($database,$connection) or die("Couldn't select database");
if (isset($_POST['sAddProduct']))
{
addNewProduct();
}
else if(isset($_POST['delete']))
{
$Product_ID=$_POST['Product_ID'];
$mysqlquery = "delete from Product where Product_ID= ".$Product_ID."";
mysql_query($mysqlquery);
echo "Deleted successfully";
echo("<FORM><INPUT Type='button' VALUE='Back' onClick='history.go(-1);return true;'></FORM>");
}
else
{
showForm();
}
// add new product
function addNewProduct()
{
$ProductName = $_POST['Product_Name'];
$ProductPrice = $_POST['Price'];
$Gender = $_POST['Gender_ID'];
$Category = $_POST['Category_ID'];
$Status = $_POST['Status_ID'];
$Age = $_POST['Age_ID'];
$image = $_FILES['Image'];
$image = mysql_real_escape_string(file_get_contents($image['tmp_name']));
//database query to add product
$insertStringProduct = "INSERT into Product(Product_Name, Price,Gender_ID, Category_ID,Status_ID,Age_ID,Image)
VALUE('$ProductName', '$ProductPrice', '$Gender', '$Category', '$Status', '$Age',''".$image."'')";
$result = mysql_query($insertStringProduct);
echo ("<p1>Product added Successfully</p1>");
echo("<FORM><INPUT Type='button' VALUE='Back' onClick='history.go(-1);return true;'></FORM>");
}
//function for the form page
function showForm()
{
//First form for adding new product
$self = htmlentities($_SERVER['PHP_SELF']);
echo("<form action = '$self' method='POST'>
<fieldset>
<legend>Adding New Product</legend>
Product Name: <input name='Product_Name' type='text' size = '40'>
<br /><br />
Price: <input name='Price' type='text' size = '20'><br><br />
Gender:
<select name='Gender_ID'>
<option value = '%'> <-- select--></option>");
//database query to show the country in the options from the database "product" field.
$dbQuary = " SELECT DISTINCT Gender_ID, Gender_Description from Gender";
$result = mysql_query($dbQuary);
while($row = mysql_fetch_row($result)){
echo("<option value ='$row[0]'> $row[1]</option>");
}
echo("
</select> <br/><br/>
Category:
<select name='Category_ID'>
<option value = '%'> <-- select--></option>");
//database query to show the country in the options from the database "product" field.
$dbQuary = " SELECT DISTINCT Category_ID, Description from Category";
$result = mysql_query($dbQuary);
while($row = mysql_fetch_row($result)){
echo("<option value ='$row[0]'> $row[1]</option>");
}
echo("
</select><br/><br/>
Status:
<select name='Status_ID'>
<option value = '%'> <-- select--></option>");
//database query to show the country in the options from the database "product" field.
$dbQuary = " SELECT DISTINCT Status_ID, Availability from Status";
$result = mysql_query($dbQuary);
while($row = mysql_fetch_row($result)){
echo("<option value ='$row[0]'> $row[1]</option>");
}
echo("
</select><br/><br/>
Age:
<select name='Age_ID'>
<option value = '%'> <-- select--></option>");
//database query to show the country in the options from the database "product" field.
$dbQuary = " SELECT DISTINCT Age_ID, Age_Description from Age";
$result = mysql_query($dbQuary);
while($row = mysql_fetch_row($result)){
echo("<option value ='$row[0]'> $row[1]</option>");
}
echo("
</select><br/><br/>
<form action='form.php' method='POST' enctype='multipart/form-data'> <input type='file' name='Image'> <input type='submit' name='sAddProduct' value='Upload'>
</fieldset>
</form>");
}
?>
Here is what has shown in my database table:
http://www.ya-techno.com/up/uploads/1429703619491.jpg
You could try to use addslashes instead of mysql_real_escape_string before you add the image to db in addproduct and then when you query the db to do something like this:
$sql = "SELECT Image FROM Product WHERE ProductId='.$product_id.'";
$result = mysqli_query($db,$sql);
while($imgarr= mysqli_fetch_array($result))
{
echo "<img src='php/showimage.php?ProductId=".$imgarr."' />";
}
I would start with actually uploading the file. Add this to your form: enctype='multipart/form-data'. Without it you will never upload anything.
Do some validation. Make sure you actually have something uploaded.
Read about MVC pattern and OOP. This will make your (and your co-workers) life easier.

Select option doesn't connect to database

Following my previous question: PHP code won't pull database information
I wanted to take the transaction page to be navigated by a selection option.
In each selection option, it will use the client_id from database and filter the listing (dynamically should change page to have filtered information of transactions based on client id).
My sql (without the :client variable inside) shows the following information:
Part of my php code to use the selection option is as so:
<?php
//url /index.php?action=clients
include('header.php'); // create top box
include('sidemenu.php'); // create side menu
//database connection
echo "<div id='content'>";
include('pdo_connect.php');
//Read data type
$type = "";
if (isset($_REQUEST['action']))
$type = $_REQUEST['action'];
//echo 'Action: {$type}';
switch($type) {
case 'transactions' :
$sql = "SELECT products.product_title, products.product_description, products.unit_price,
p_clients.first_name, p_clients.last_name, sales.quantity FROM p_clients INNER JOIN
sales ON p_clients.client_id = sales.client_id INNER JOIN products ON products.product_id = sales.product_id
WHERE client_id = :client_id";
$values = array(':client_id'=>$_REQUEST['client_id']);
$transactions = getAll($sql, $values);
displayTransactionList($transactions);
break;
default:
defaultView();
break;
}
include('footer.php');
function defaultView() {
?>
<!-- add page content -->
<!-- <div id='content'>-->
<h2>Welcome to our movie store</h2>
</div>
<div id = 'image'></div>
<div id = 'box'>
<p id = 'text-box'>
Welcome to International Electronics, the store where technology is endless. Please
feel free to browse our online store items and current customer interactions.
</p>
</div>
<?php
}
function displayTransactionList($transactions) {
//echo "<div id='content'>
echo"<h2>List of Client Transactions</h2>";
echo " <p>
<h3> Select Specific Client </h3>
<form id='myform' method='post' action='index.php'>
<select id = 'category' name='client_id' >
<option selected= 'selected'> --select id--</option>
<option value = '1'>Client ID 1</option>
<option value = '2'>Client ID 2</option>
<option value = '3'>Client ID 3</option>
<option value = '4'>Client ID 4</option>
<option value = '5'>Client ID 5</option>
<option value = '6'>Client ID 6</option>
<option value = '7'>Client ID 7</option>
<option value = '8'>Client ID 8</option>
<option value = '9'>Client ID 9</option>
<option value = '10'>Client ID 10</option>
</select>
</li>
<input type='hidden' name= 'action' value = 'transactions'/>
</form></p>";
echo "<table id = 'long'>";
echo "<tr><td id = 'title'>First Name</td><td id= 'title'>Last Name</td><td id = 'title'>Product Title</td>
<td id = 'title'>Product Description</td><td id = 'title'>Cost</td><td id = 'title'>Quantity</td></tr>";
//display each record
for ($i = 0; $i < count($transactions); $i++){
echo "<tr><td>{$transactions[$i]['first_name']}</td><td> {$transactions[$i]['last_name']}
</td><td> {$transactions[$i]['product_title']} </td><td> {$transactions[$i]['product_description']} </td><td>
{$transactions[$i]['unit_price']} </td><td> {$transactions[$i]['quantity']} </td></tr>";
}
echo "</table>";
echo "</div>";
}
function getAll($sql, $values =null){
global $db;
$statm = $db->prepare($sql);
//Method 4
//assign a value to named parameters using an array
//$values= array(':genre'=>'drama');
$statm->execute($values);
//Fetch all records
$result = $statm->fetchAll();
return $result;
}
Script.js to change page when select option is clicked:
document.ready(function() {
$('#category').on('change', function() {
//send form data
$('#myform').submit();
$('#content').html(); //also tried $('#content').html(response);
});
});
sidemenu.php
<div id = 'top'>
<div class = "nav">
<ul id = "nav1" class= "text-left">
<div id = 'text-left'>
<ul id = "nav" class= "text-left">
<li><a href='index.php'>Home</a></li>
<li><a href='index.php?action=products&product_type=tv'>TV Products</a></li>
<li><a href='index.php?action=products&product_type=cell'>Cell Phone Products</a></li>
<li><a href='index.php?action=products&product_type=computer'>Computer Products</a></li>
<li><a href='index.php?action=clients'>List of Customers</a></li>
<li><a href='index.php?action=transactions'>List of Transactions</a></li>
</ul>
</div>
</div>
UPDATE:
if i try:
$values = array(':client_id'=>$_POST['client_id']);
nothing changes.
![enter image description here][3]

php - Drop Down Executes Query On Post?

I've looked online and most drop down tutorials are for ratings e.g. matching the drop down value with a rating. I need to execute a query which corresponds to a number in the dropdown and the results to display once a user clicks submit, I don't want to use javascript. In my HTML :
<form action="" method="post" enctype="multipart/form-data" name="form1" id="genericForm">
<fieldset>
<p>Filter Rating</p>
<select name="value">
<option value="1">One Star</option>
<option value="2">Two Stars</option>
<option value="3">Three Stars</option>
<option value="4">Four Stars</option>
<option value="5">Five Stars</option>
</select>
</div>
<input type="submit" name="Submit" value="Submit"><br />
</form>
The php :
<?php
$Link = mysql_connect($Host, $User, $Password);
if($_POST['value'] == '1') {
// query to get all 1 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='1'";
}
elseif($_POST['value'] == '2') {
// query to get all 2 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='2'";
}
elseif($_POST['value'] == '3') {
// query to get all 3 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='3'";
}
elseif($_POST['value'] == '4') {
// query to get all 4 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='4'";
}
elseif($_POST['value'] == '5') {
// query to get all 5 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='5'";
}
WHILE($board = mysql_fetch_array($result)):
$title = $board['title'];
$studio = $board['studio'];
$language = $board['language'];
$certification = $board['certification'];
echo '
Title : '.$title.'<br />
Studio : '.$studio.'<br />
Language : '.$language.'<br />
Certification : '.$certification.'<br />
;
endwhile;
?>
Try it this way, assuming you're already connected and have selected DB and that you're using your entire code inside the same file, since you are using action=""; this denotes executing as "self".
You also are not executing mysql_query() which I have added below.
Be sure to change xxx below with your DB credentials and your_db to your database's name.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$Host = "xxx";
$User = "xxx";
$Password = "xxx";
$Link = mysql_connect($Host, $User, $Password);
$db_selected = mysql_select_db('your_db', $Link);
if (!$db_selected) {
die ('Can\'t use that DB : ' . mysql_error());
}
if(isset($_POST['Submit'])){
if($_POST['value'] == '1') {
// query to get all 1 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='1'");
}
elseif($_POST['value'] == '2') {
// query to get all 2 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='2'");
}
elseif($_POST['value'] == '3') {
// query to get all 3 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='3'");
}
elseif($_POST['value'] == '4') {
// query to get all 4 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='4'");
}
elseif($_POST['value'] == '5') {
// query to get all 5 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='5'");
}
WHILE($board = mysql_fetch_array($query)){
$title = $board['title'];
$studio = $board['studio'];
$language = $board['language'];
$certification = $board['certification'];
echo '
Title : '.$title.'<br />
Studio : '.$studio.'<br />
Language : '.$language.'<br />
Certification : '.$certification.'<br />';
}
} // brace for if(isset($_POST['Submit']))
?>
</div>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="genericForm">
<fieldset>
<p>Filter Rating</p>
<select name="value">
<option value="1">One Star</option>
<option value="2">Two Stars</option>
<option value="3">Three Stars</option>
<option value="4">Four Stars</option>
<option value="5">Five Stars</option>
</select>
</div>
<input type="submit" name="Submit" value="Submit"><br />
</form>
Note:
This enctype="multipart/form-data" isn't required if it's not going to be used to upload files.
If im not mistaken this is what you want? you just need to loop through the row in the tables and fetch it.
<div class="form">
<?php
$Link = mysql_connect($Host, $User, $Password);
$Query = "select * from books where product = 'hannibal' AND book = '1'";
$result = mysql_query($Query);
while ($row = mysql_fetch_array($result)) {
$subject = $row['subject'];
$username = $row['username'];
$date = $row['date'];
$comments = $row['comments'];
?>
<h1>Subject : <?php echo $subject;?>
Posted by <?php echo $username;?> on <?php echo $date;?></h1><br />
<?php echo $comments;?>'; <br />
<?php
}
?>
</div>

Using Select Option's value to query database [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have the following code to generate my option:
<?php
$sql = "SELECT DISTINCT MyID FROM database";
$query = $db->prepare($sql);
$query->execute();
$option = "";
foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $rows) {
$id = $rows[MyID];
$option.="<option>".$id."</option>";
}
?>
<select name="options" id="options" class="options">
<option value="$id">Select an Option</option>
<?php echo $option?>
</select>
I would like to use the value of the selected option in my next query.. like this:
<?php
$myDB= $db->prepare("SELECT * FROM names WHERE RowID = :option");
$myDB->bindParam(':option', $option); //the value of the option selected in my dropdown
$myDB->execute();
$result = $myDB->fetchAll();
This is not working for some reason. Can you please help on this. Thanks
<?php
$sql = "SELECT DISTINCT MyID FROM database";
$query = $db->prepare($sql);
$query->execute();
$option = "";
$result = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$id = $row['MyID'];
$option.='<option value="'.$id.'">'.$id.'</option>';
}
?>
<form method="post" action"(`The url of the next page`)">
<select name="options" id="options" class="options">
<option disabled>Select an Option</option>
<?php echo $option?>
</select>
<input type="submit" value="submit" />
</form>
Next page:
<?php
if(isset($_POST['submit']) && isset($_POST['options'])) {
$option = $_POST['option'];
$myDB= $db->prepare("SELECT * FROM names WHERE RowID = :option");
$myDB->bindParam(':option', $option); //the value of the option selected in my dropdown
$myDB->execute();
$result = $myDB->fetchAll();
}
With fetchAll() you should assign this to a variable and then loop through that.
$row[MyID] MyID should be wrapped in '' or "" as the index is a string so $row['MyId']
You'll need to submit the data back to the server for PHP to be able to do anything with it as PHP creates he HTML and then sends it from the server to the browser.
I've used if(isset()) for the REQUEST variables ($_GET, $_POST), this will prevent PHP from throwing errors if you try and load the page without them being available.
If you have any other questions, I'd be happy to help.
Hope this helps! :)
EDIT
<?php
if(isset($_GET['submit']) && isset($_GET['options'])) {
$option = $_GET['option'];
$myDB= $db->prepare("SELECT * FROM names WHERE RowID = :option");
$myDB->bindParam(':option', $option); //the value of the option selected in my dropdown
$myDB->execute();
$result = $myDB->fetchAll();
/**
* You'll need to put the logic for the query above here
**/
} else {
$sql = "SELECT DISTINCT MyID FROM database";
$query = $db->prepare($sql);
$query->execute();
$option = "";
$result = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$id = $row['MyID'];
$option.='<option value="'.$id.'">'.$id.'</option>';
}
?>
<form method="get" action"">
<select name="options" id="options" class="options">
<option disabled>Select an Option</option>
<?php echo $option?>
</select>
<input type="submit" value="submit" />
</form>
<?php
} // End of else
?>
I've also changed the form method to get and removed the action, so it will submit to the current page.

Categories