Select option doesn't connect to database - php

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]

Related

Insert data in table (diary) and update the data in the (category) table mysql

I am trying to insert the image name in the table (diary) and at the same time I am trying to update the image name in the table (category). but the value is not updating the in the category. I tried all the available solutions on the internet but nothing worked can someone help me?
I want to update the (category) table "cat_img" whenever the user adds a new image to the table (diary) diary_thumbnail_image.
Please help me it will be appreciated.
here is my code add_diary.php
<?php include 'header.php';
if ($admin != 1 && $admin != 2) {
header("location:index.php");
}
if (isset($_SESSION['user_data'])) {
// This will fetch the author id that is stored in index['0'].
$author_id = $_SESSION['user_data']['0'];
}
$sql = "SELECT * FROM categories";
$query = mysqli_query($config, $sql);
$sql_school = "SELECT * FROM school";
$query_school = mysqli_query($config, $sql_school);
?>
<form method="POST" action="" enctype="multipart/form-
data"
this diary:</strong></label>
<select class="form-control"
name="show_in_school">
<option value=""
name="show_in_school">Select School
Name</option>
<!-- $cats will fetch all the data that
is stored in the categories. -->
<?php while ($school_result =
mysqli_fetch_assoc($query_school)) { ?>
<option value="<?=
$school_result['school_title'] ?>">
<?= $school_result['school_title'] ?>
</option>
<?php } ?>
}
</select>
</div>
<div class="mb-3">
<input type="submit" name="add_diary"
value="Add" class="btn btn-primary">
<a class="btn btn-secondary"
href="diary_information.php">Back</a>
</div>
</form>
<?php
if(isset(add_diary)){
$select_cat = "SELECT * FROM categories";
$query_cat = mysqli_query($config, $select_cat);
$cat_result = mysqli_fetch_array($query_cat);
$get_cat_id = $cat_result['cat_id'];
// FACING THE ISSUE HERE
$cat_up = "UPDATE categories SET cat_name='$category'
cat_img='$filename' WHERE
cat_id='$get_cat_id'";
$query_up = mysqli_query($config, $cat_up);
if ($query_up) {
$msg = ["Post Publish Successfully", "alert-success"];
$_SESSION['msg'] = $msg;
// If the post publish successfully then redirect to
same page with a success message.
header("location:add_diary.php");
} else {
$msg = ["Failed, Please try again", "alert-danger"];
$_SESSION['msg'] = $msg;
// If the post is not able to post then redirect to the
same
page with an error message.
header("location:add_diary.php");
}
}
?>
I tried to insert using the id but didn't work and checked all the ways to insert and update that were available on the internet but didn't work
// This worked but it stays with the old image and doesn't update the new image.
$sql_up_cat = "UPDATE categories SET cat_img = (SELECT diary_thumbnail_image FROM diary WHERE cat_id = blog_id) ";
$query_up = mysqli_query($config, $sql_up_cat);
Actually, I was sending the value of the cat_name in integer to the database that's why it was not able to check the category name and was not updating the image.
I than changed it's value to the String.
<div class="mb-3">
<label><strong>Category:</strong></label>
<select class="form-control" name="category">
<option value="" name="category">Select
Category</option>
<!-- $cats will fetch all all the data that is store
in the categories. -->
<?php while ($cats = mysqli_fetch_assoc($query)) { ?
>
<option value="<?= $cats['cat_name'] ?>">
<?= $cats['cat_name'] ?>
</option>
<?php } ?>
}
</select>
</div>
Updated the query to this and then it worked
$cat_up = "UPDATE categories SET cat_img='$filename' WHERE cat_name='$category'";
$query_up = mysqli_query($config, $cat_up);

Populating Second Dropdown Based on first dropdown from the database table without using javascript

I am trying to create a form for the admin of an e-commerce site and the admin should be able to create a category and add new products.
I have two tables in my database from where I want to populate the dropdown list. I want the second dropdown to populate as I select the first drop-down value but I have to do it without the submit button.
This is the code for the form with two drop-downs:-
<form method="post" action="add_category.php">
<h4>Choose the root level:</h4>
<select name="rootLevel">
<?php
$conn = mysqli_connect("localhost","root","","store")
or die("Error in Connection on add_category");
$query = "SELECT * FROM root_category";
$result = mysqli_query($conn,$query) or die("Query failed add_category");
$id=1;
//echo $id;
//echo "Hello";
while($row = mysqli_fetch_assoc($result)){
global $id;
//echo "<h1>$id</h1>";
$id = $row['id'];
echo "<option name='rootLevel' value=$id>".$row['Name']."</option>";
//echo "<option>$id</option>";
}
?>
</select>
<br><br>
<h4>Choose the Level 1 Category:</h4>
<select name="level1">
<?php
global $id;
//echo "<option>".$_POST['rootLevel']."</option>";
$query_level1 = "Select * from level1_category Where P_id = $id";
$result1 = mysqli_query($conn,$query_level1) or die("Query failed level 1");
while($row = mysqli_fetch_assoc($result1)){
$id1 = $row['P_id'];
echo "<option name='level1' value=$id1>".$row['Name']."</option>";
}
?>
</select>
I have successfully populated the first drop-down and now I want to fetch the $id in 'resultValue' without the submit button.
You cant do this only with PHP. You have to use jquery OR Ajax to do this.
Please check this example page . This may help you
https://www.tutorialrepublic.com/faq/populate-state-dropdown-based-on-selection-in-country-dropdown-using-jquery.php
OR
https://www.codexworld.com/dynamic-dependent-select-box-using-jquery-ajax-php/
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "states.php",
data: { country : selectedCountry }
}).done(function(data){
$("#states").html(data);
});
});
});
</script>
</head>
<body>
<div class="form-group">
<label for="country" class="input__label">Country</label>
<select id="country" onchange="states(this.value);" name="country" class="country form-control login_text_field_bg input-style">
<option selected>Choose...</option>
<?php
$sql= $cnn->prepare("SELECT key_iso_code FROM country");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
?>
<option><?php echo $key_iso_code ?></option>
<?php
}
?>
</select>
</div>
<div class="form-group col-md-4">
<label for="inputState" class="input__label">State/Province</label>
<select id="states" name="state" class="form-control input-style">
<option selected>Choose...</option>
</select>
</div>
</body>
<?php
include("PDOConnection.php");
if(isset($_POST["country"])){
// Capture selected country
$country = $_POST["country"];
// Display city dropdown based on country name
if($country !== 'Shoose...'){
$sql= $cnn->prepare("SELECT state.key_name FROM country INNER JOIN state ON country.key_id = state.key_country_id WHERE country.key_iso_code like '$country'");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
echo "<option>". $key_name . "</option>";
}
}
}
?>

Save ID from dropdown list into other table

I have a form with fields and one dropdown list. The data from the dropdown list comes out the table: categorie. (fields are: catID, catName)
When I select a categorie from the drop down list and fill all the other input fields, it saves all the input fields and only the catName from the categorie table into the tabel: event.
How can I also save the selected catID from the categorie table into the event table?
Can someone helm me out here?
Regards, Benny
<?php require '../Connections/localhost.php'; ?>
<?php
if(isset($_POST['newEvent'])) {
session_start();
$eventName = $_POST['SelCatName'];
$eventSDate = $_POST['Event-StartDate'];
$eventSTime = $_POST['Event-StartTime'];
$eventEDate = $_POST['Event-EndDate'];
$eventETime = $_POST['Event-EndTime'];
$eventDescription = $_POST['Event-Description'];
$catID = $_POST["catID"];
$sql = $con->query("INSERT INTO event (eventName, eventSDate, eventSTime, eventEDate, eventETime, eventDescription, catID)Values('{$eventName}', '{$eventSDate}', '{$eventSTime}', '{$eventEDate}', '{$eventETime}', '{$eventDescription}', '{$catID}')");
header('Location: eventOK.php');
}
?>
<form action="" method="post" name="RegisterForm" id="RegisterForm">
<div class="FormElement">
<select name="SelCatName" class="TField" id="SelCatName">
<option selected="selected" id="0">--Selecteer een categorie--</option>
<?php
$GetAllCategories = $con->query("SELECT * FROM categorie");
while ($ViewAllCategories = mysqli_fetch_array($GetAllCategories)){
?>
<option id="<?php echo $ViewAllCategories['catID']; ?>"><?php echo $ViewAllCategories ['catName']; ?> </option>
<?php } ?>
</select>
You made a mistake in <option id="id"></option>
if you wanna take value from select child.
you must change id to value="" or you must add value="id" proper.
change your select box block completely like below..
<select name="SelCatName" class="TField" id="SelCatName">
<option selected="selected" id="0">--Selecteer een categorie--</option>
<?php
$GetAllCategories = $con->query("SELECT * FROM categorie");
while ($ViewAllCategories = mysqli_fetch_array($GetAllCategories)){
?>
<option value="<?PHP echo $ViewAllCategories['catID'].'-'.$ViewAllCategories['catName']; ?>"> <?PHP echo $ViewAllCategories['catName']; ?></option>
<?php } ?>
</select>
and a tip for mysql query... to the best of one's ability don't use "select * from" use it if you dont need to all colums better than "*"
$con->query("SELECT catID, catName FROM categorie");
PHP file
<?php require '../Connections/localhost.php'; ?>
<?php
if(isset($_POST['newEvent'])) {
session_start();
//$eventName = $_POST['SelCatName'];
$eventSDate = $_POST['Event-StartDate'];
$eventSTime = $_POST['Event-StartTime'];
$eventEDate = $_POST['Event-EndDate'];
$eventETime = $_POST['Event-EndTime'];
$eventDescription = $_POST['Event-Description'];
$catIDs = $_POST["SelCatName"];
$catID = explode("-", $catIDs);
$sql = $con->query("INSERT INTO event (eventName, eventSDate, eventSTime, eventEDate, eventETime, eventDescription, catID)Values('{$catID[1]}', '{$eventSDate}', '{$eventSTime}', '{$eventEDate}', '{$eventETime}', '{$eventDescription}', '{$catID[0]}')");
header('Location: eventOK.php');
}
?>
to me you are missusing the attribute of ID, Replace the ID for value: your option tag already have the id and name
<select name="SelCatName" class="TField" id="SelCatName">
your code will be:
<?php
$GetAllCategories = $con->query("SELECT * FROM categorie");
while ($ViewAllCategories = mysqli_fetch_array($GetAllCategories)){
?>
<option value="<?php echo $ViewAllCategories['catID']; ?>"> <?php echo $ViewAllCategories ['catName']; ?> </option>
<?php } ?>
Therefore you will find your post as only SelCatName = (numerical ID)
Now, if you need that the list of the catID and catName stores to the next page you can re-run your query in the next page and store them in an array.

How to send all possible WHERE options to mysqli?

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);
}

listbox value goes 0 in database if not selected on edit mode in php

I have three tables
City: city_id, city_name
State: State_id, State_name
News: City_id, State_id, Headline, Story, Author etc.
I am Displaying data in textbox and listbox on edit button click Of Selected ID.
Data is displaying in listbox properly of selected id but when i click save button without change of listbox value it goes 0 in database.
If I don't change the listbox value and click save then it inserting 0 from listbox.
<?php
$data = 0;
if(isset($_GET['edit']))
{
$id = clean($_GET['edit']);
mysql_set_charset('utf8');
$sql="SELECT city_name,state_name,category_name,headline,author,story,source,photo,date from news left join
city on news.city_id=city.city_id left join state on news.state_id=state.state_id left join category on news.cat_id=category.category_id where id = '$id'";
$result=mysql_query($sql);
$data=mysql_fetch_array($result);
}
?>
<?php
$cat = $Admin->select($Admin->cat_table,'','','');
?>
<select name="cat_id" class="select" required="">
<option value="<?php if(isset($_GET['edit'])){ echo $data['category_name']; }?>"><?php if(isset($_GET['edit'])){echo $data['category_name'];}?></option>
<?php
foreach($cat as $load_category)
{
?>
<option value="<?php echo $load_category["category_id"]; ?>"><?php echo $load_category["category_name"]; ?></option>
<?php }?>
</select>
<?php
$errors = array();
$Admin = new admins;
if(isset($_POST['save']))
{
$table = $Admin->news_table;
if(isset ($_GET['edit']))
{
$id = clean($_GET['edit']);
$cond = "id = '$id'";
if($Admin->save_advance($table,$_POST,'',$cond))
{
$_SESSION['message'] = "News Updated Successfully";
header("Location:add_news.php");
exit;
}
}
}
?>
What am I doing wrong?
Tell me if I'm wrong but this line
<option value="<?php if(isset($_GET['edit'])){ echo $data['category_name']; }?>">
<?php if(isset($_GET['edit'])){echo $data['category_name'];}?>
</option>
seems strange to me, it sets the category name as value for first option in the select. Basically, if you don't change the listbox, you are trying to update a row where the category_id is a category_name.
This should be:
<option value="0">
<?php if(isset($_GET['edit'])){echo $data['category_name'];}?>
</option>
But if you have to update something you can't do that without a value. So add some kind of validation that forbids to click the save button without setting a value in the select, or just do something like this (adds a default category to the listbox)
<select name="cat_id" class="select" required>
<?php
$counter = 0;
foreach($cat as $load_category){ ?>
<option <?php echo ($counter == 0) ? 'selected' : ''; ?> value="<?php echo $load_category["category_id"]; ?>"><?php echo $load_category["category_name"]; ?></option>
<?php
//increments counter
$counter++; }?>
</select>

Categories