Using form method="post" to assign a php variable dynamically - php

I'm trying to run a specific database query based on what value is selected in a select drop down. The current code I have isn't running the queries.
My current code looks like this:
main-search.php
<form action="" method="post">
<div class="search-container">
<input type="text" id="search_input" placeholder="">
<select name="search-by">
<option value="symptom">Symptom</option>
<option value="language">Language</option>
</select>
</div>
</form>
<?php
session_start();
$searchBy = $_POST['search-by'];
$_SESSION['search_type'] = $searchBy;
?>
search.php
<?php
session_start();
$queryType = $_SESSION['search_type'];
if ($queryType == "symptom") {
$searchQuery = $db->query("SELECT * FROM Symptoms WHERE symptom_name ORDER BY symptom_name ASC");
}
else if ($queryType == "language") {
$searchQuery = $db->query("SELECT * FROM `Language` WHERE language_name ORDER BY language_name ASC");
}
?>
I have tried changing the code in main-search.php to...
<?php
session_start();
$searchBy = $_POST['search-by'];
$_SESSION['search_type'] = "symptom";
?>
and it works as intended, running the first query, so that's why I'm assuming I'm doing something wrong with the post form and assigning the $searchBy value.
I'm new to php, so any help would be appreciated, thanks.

It's probably best to avoid Session variables for this purpose, as session variables are used to store/pass information from page to page in PHP (such as login status).
From my deduction you are trying to change this PHP variable dynamically when the user changes the <select> option. As PHP is a server-side script this will not work, if you need something to change without reloading the page you will need to use a client-side script (e.g. Javascript/jQuery). For example (in jQuery):
$('select[id="search-type"]').on("change", function(){
//Do work
});
However, if I understand you correctly, your best bet is to just use HTTP POST variables (accessed by $_POST in PHP), for example:
main-search.php:
<form action="search.php" method="post">
<div class="search-container">
<input type="text" id="search_input" placeholder="">
<select name="search_type" id="search-type">
<option value="symptom">Symptom</option>
<option value="language">Language</option>
</select>
<button type="submit">Submit</button>
</div>
</form>
search.php:
<?php
$queryType = $_POST['search_type'];
if ($queryType == "symptom") {
$searchQuery = $db->query("SELECT * FROM Symptoms WHERE symptom_name ORDER BY symptom_name ASC");
}
else if ($queryType == "language") {
$searchQuery = $db->query("SELECT * FROM `Language` WHERE language_name ORDER BY language_name ASC");
}
?>

Related

Passing selected Value from options to a php variable

I want to create a form in which I access several tables and offer the user choices regarding the entries through these tables.
I have a "Systems" table from which the user can choose a system.
For this purpose I have a "Users" table, from which the user can choose a user.
This data should be selected and stored in the third table "Reports".
My code looks like this:
if (isset($_POST['submit'])) {
$systemId = $_POST['systemId'];
$userId = $_POST['userId'];
}
if ($db->addReport('reports', ["systemId" => $systemId, "userId" => $userId,)) {
echo("Entry added");
}
?>
<p>Create report</p>
<form action="" method="post">
<?php $entries = $db->getSystem(); ?>
<div class="form">
<label>System</label>
<select name="systemId" class="form-control">
<?php foreach ($entries as $option) : ?>
<option value="<?php ($option[0]) ?>" selected="<?php ($option[0]) ?>"> <?php echo($option[0]) ?> </option>
<?php endforeach; ?>
</select>
</div>
<input type="submit" name="submit" value="Submit">
</form>
I left out the part with the user for simplicity's sake, because I proceed exactly as I do with the system.
My problem is that an entry is made in the database, but the values are always "0". However, there are also entries in the database that do not have the value 0. The correct names are shown to me in the selection context, but what is actually written to the database is wrong.
So I cannot pass the correct value to the variable "systemId".
I tried several things on the internet, unfortunately nothing worked.
Notice: the connection to the database works fine. I don't have any problems with running the querys.
You're running the insert command even when the form hasn't been submitted. Just move that command inside the if statement which checks for the submitted data, so that it only runs in response to a suitable POST request.
if(isset($_POST['submit']))
{
$systemId = $_POST['systemId'];
$userId = $_POST['userId'];
if($db->addReport('reports',["systemId"=> $systemId, "userId"=>$userId,)){
echo("Entry added");
}
}

The form is not collecting the user input and the query is not working properly even though I have typed in a valid table and column

I'm trying to validate the user input and query to delete the record which have the same name. I'm using phpStorm for coding
I have tried to go over the typo, format of the code and check the query in phpAdmin and it's working fine
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 3/24/2019
* Time: 4:38 PM
*/
// Include config file
require_once "config.php";
$product_name= '';
$product_name_err = '';
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty(trim($_POST["product_name"]))){
$product_name_err = "Please enter the product name.";
} else{
$product_name = trim($_POST["product_name"]);
}
//Delete the data in the product table
$sql = "DELETE FROM `products` WHERE `name` = '$product_name'";
if ($product_name_err =''){
mysqli_query($link,$sql);
}
}
?>
<?php include "header_admin.php"?>
<div class="wrapper">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group" <?php echo (!empty($product_name_err)) ? 'has-error' : ''; ?>>
<label>Product name</label>
<input type="text" name="product_name" class="form-control" >
<span class="help-block"><?php echo $product_name_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Delete Item">
</div>
</form>
</div>
<?php include "footer.php"?>
I expect the preceding code to check if the field is blank and the query delete that matched record on the database but either of them seem to work properly. The $product_name seem not received any value at all.
The below code should work correctly. There was a typo in your confition: if ($product_name_err =''){ should be if ($product_name_err ==''){
Also, your code was vunerable to injection attacks, which is fixed below by using the mysqli_escape_string function.
if($_SERVER["REQUEST_METHOD"] == "POST") {
$product_name = mysqli_escape_string($link, trim($_POST["product_name"]));
if(empty($input)){
$product_name_err = "Please enter the product name.";
}
//Delete the data in the product table
$sql = "DELETE FROM `products` WHERE `name` = '$product_name'";
if($product_name_err == ''){
mysqli_query($link,$sql);
}
}
Your if condition is incorrect, use '==' instead of '='.
if ($product_name_err ==''){
mysqli_query($link,$sql);
}
also you should really consider using prepared statements to prevent sql injection attacks and it does other nice things for you like you not having to escape ' or " characters from your strings.
More info on prepared statements
Php code check will help to check your PHP code. May be it will help you.
#PHP Code Checker
An advanced, custom PHP code checker that searches your code for common, hard to find typos and mistakes; includes a syntax check.

Show price from DB

The user goes change the nm_peca, will select tipo_preco and then find the price in MySQL database to complete the textbox vlr_peca.
What do I need to do to get the value of products?
<?php>
$query = mysql_query("SELECT id, nm_peca, vlr_original,
vlr_paralelo, fabricante
FROM peca
ORDER BY nm_peca");
<select id="nm_peca" name="nm_peca"
title="Selecione um status."
class="form-control" size="1">
<option value="">Status</option>
<option value="N/A">N/A</option>
<option value="S">S - Substituir</option>
</select>
</div>
</div>
<select id="tipo_preco" name="tipo_preco"
class="form-control" size="1">
<option value="">Tipo</option>
<option value="Peça Original">Original</option>
<option value="Peça Paralela">Paralela</option>
</select>
</div>
</div>
<div class="col-md-1">
<div class="input-group btn-group">
<input type="text" value="????????" name="vlr_peca"
class="form-control" readonly>
</div>
</div>
Well your code is a little confusing because what you really want is not clear to me, maybe it doesn't help that it's in a different language. What is the $query for? You are not using this in the code, so you'll need to do this to access it:
$rows = array();
while ($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
print '<pre>'. print_r($rows, true) . '</pre>';
Then you'll need to use an ajax request OR setup javascript vars on the front end to make changes. I'm just going to go ahead and use the latter since it's more illustrative.
So I would add the cdn of jQuery which is https://code.jquery.com/jquery-2.1.4.min.js to the top of your file in a tag like:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
Then you'll need to add an input id to that input tag like <input id="dynamic-variable" type="text" value="????????" name="vlr_peca"> and then use something like:
<script type="text/javascript">
$(document).ready(function() {
$('#tipo_preco').change(function() {
if ($(this).val() == 'Peça Original') {
$('#dynamic-variable').val('$5,000,000,000.00');
} else if ($(this).val() == 'Peça Paralela') {
$('#dynamic-variable').val('$300 billion trillion dollars');
} else {
$('#dynamic-variable').val('Bro. Choose one.');
}
});
});
</script>
I'm not going to program this whole thing for you since I don't know what kind of data you are getting from your DB, but this should be good enough to get you started. You need to be able to access the data in the mysql query, and you may just want to use the <?= $db_variable ?> or <?php echo $db_variable?> in your javascript where I have the amount variables. This should be good enough to get you started. Read up on php mysql_query and jQuery
AJAX
If you were to do this via AJAX, you would need a second page that accesses the database, you'd have to $_GET or $_POST variables and then print back the amount.
So your JavaScript would be something like this:
$.get('/the/page.php?tipo_preco=' + $('#tipo_preco').val(), function(response) {
if (response != '') {
$('#dynamic-variable').val(response);
}
});
And your second page would be something like this:
<?php
// code that sets up the database
// .... //
// now your code
$selected_value = $_GET['tipo_preco'];
$result = mysql_query("SELECT price FROM table WHERE column_val = '" . mysql_real_escape_string($selected_value) . "'");
$row = mysql_fetch_assoc($result); // assuming you're only fetching one row
print $row['price'];
?>
I would suggest you just go with the first suggestion, it's faster, less moving parts.

Results on the same page as the search form php

How can i echo the results in the same page as the search form is (wordpress)?(i`m newbie)
<form action="" id="searchform" method="POST">
<input name="searchquery" type="text" placeholder="Nume, spital" size="30" maxlength="40">
<select name="filter">
<option value="ALL">Toate judetele</option>
<option value="AB">Alba</option>
</select>
<input type="submit" value="Cauta">
</form>
the php code
global $wpdb;
$con=mysqli_connect("localhost","root","");
$search = mysql_real_escape_string(trim($_POST['searchquery']));
if($_POST['filter'] == "ALL"){
$sqlCommand = $wpdb->get_results("SELECT * FROM `wp_doctors` WHERE `name` LIKE '%searchquery%'");
} else if($_POST['filter'] == "AB"){ $sqlCommand = $wpdb->get_results("SELECT * FROM `wp_doctors` WHERE `name` LIKE '%searchquery%' AND `city`= 'Alba' ");
} //more if`s, i just cuted for example
foreach ( $sqlCommand as $result)
{
echo $result->id;
echo $result->name;
echo $result->spec;
}
and if i`m using at the form action atribute it will take me to the index page.
Thanks!
Try putting in the form action :
action="<?=$_SERVER['PHP_SELF']?>"
In order to test if you are not being redirected by wordpress, try this
in your php code:
if(isset($_POST)){
var_dump($_POST);
}
In this way you can clear out if the page is posting right and if you are being
redirected somewhere by wordpress.

Multiple, dynamic dropdown list based on user selection

I have read through all the "dynamic multiple dropdown lists" questions here on stackoverflow but could not find what I am looking for.
It's a form for states and cities. User select a state, through ajax I request the cities for that specific state ID.
But, I need to have the two selects already created and displayed (maybe the city select grayed out). An example here PenskeAutomotive.
What I managed to do so far is to have only the state select and upon the execution of ajax, from the XMLHttp.ResponseText to create the city select. An example here Dorpdown list example - at bottom of page.
I need to have both selects displayed and then only update the city select with the new values of the XMLHttp.ResponseText.
Can anybody point me to some direction?
UPDATE:
Right after posting I found a question that I have not read before. Went into it and I may have found my direction. I am just trying that right now. It's jQuery/Ajax. Question
Not sure where you're having trouble, but to (hopefully) point you in the right direction:
You could have both of your <select> elements created on the page, with the City dropdown having the HTML disabled attribute, which will gray it out.
The disabled dropdown will have no options, aside from maybe one that says something like "select state."
You'll add an onchange event listener to your State dropdown which will perform the AJAX call, and I would recommend you get your response back in JSON format.
Then you can clear out the options of the next dropdown and create and append the new options from your server, then enable the dropdown.
If you want to provide what you've done so far, I'm sure we can help debug it.
I use this code in my site, maybe is usefull for you:
in head:
<script language="JavaScript" type="text/JavaScript">
$(document).ready(function(){
$("#select1").change(function(event){
var id = $("#select1").find(':selected').val();
$("#select2").load('../scripts/depto.php?id='+id);
});
});
</script>
<script language="JavaScript" type="text/JavaScript">
$(document).ready(function(){
$("#select2").change(function(event){
var id = $("#select2").find(':selected').val();
$("#select3").load('../scripts/municipios.php?id='+id);
});
});
</script>
and in select:
<div class='control-group'>
<label class='control-label' for='typeahead'>País </label>
<div class="controls">
<select name="IDPAIS" id="select1" required>
<?
$sql = $conn->prepare("SELECT * FROM lista_paises");
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo
'<option value="'.$row[id].'">'.$row[opcion].'</option>';
}
?>
</select>
</div>
</div>
<div class='control-group'>
<label class='control-label' for='typeahead'>Departamento </label>
<div class="controls">
<select name="departamento" id="select2" required></select>
</div>
</div>
<div class='control-group'>
<label class='control-label' for='typeahead'>Municipio / Ciudad</label>
<div class='controls'>
<select name="ciudad" id="select3" required></select>
</div>
</div>
in the lista_paises.php
<?
include('../include/config.php');
$query = $conn->prepare("SELECT * FROM PAISES);
$respuesta="[";
foreach ($aMunicipios as $muni) {
$respuesta .="{id:".$muni["id_municipio"].",nombre_municipio:'".$muni["municipio_nombre"]."'},";
}
$respuesta = substr($respuesta,0,strlen($respuesta)-1);
$respuesta.="]";
echo $respuesta;
}
?>
in depto.php
<?
include('../include/config.php');
$sql = $conn->prepare("SELECT * FROM lista_estados WHERE relacion = ".$_GET['id']);
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo
'<option value="'.$row[id].'">'.$row[opcion1].'</option>';
}
?>
in municipios.php(ciudad/city)
<?
include('../include/config.php');
$sql = $conn->prepare("SELECT * FROM MUNICIPIOS WHERE relacion1 = ".$_GET['id']);
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo
'<option value="'.$row[id].'">'.$row[opcion2].'</option>';
}
?>
maybe works for you

Categories