I have a problem with my database and doing the update of it. I have a database table stock with 5 columns (stock_id, p_id, brand_id, cat_id, availability). I want to do an update from the frontend. So when the popup show up and I fill in the form, UPDATE doesn't work. I have 3 files. First one stock.php that read database and works fine. the seconf one that open if you click edit looks like this:
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST['rowid']) {
$id = $_POST['rowid']; //escape string
$query = "SELECT * FROM stock WHERE stock_id = $id";
$results = $database->get_results( $query );
foreach( $results as $row ){
$cat_id = $row['cat_id'];
$brand_id = $row['brand_id'];
$p_id = $row['p_id'];
?>
<form method="post" name="form">
<input id="stock_id" name="stock_id" type="hidden" value="<?php echo $row['stock_id'];?>"/>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">CATEGORY</label>
<select id="category" name="category" class="form-control">
<?php
$qex = "SELECT * FROM category";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['cat_id']; ?>"<?php
if ($cat_id == $rowex['cat_id'])
echo 'selected'; ?>><?php echo $rowex['cat_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">BRAND</label>
<select id="brand" name="brand" class="switchable form-control">
<?php
$qex = "SELECT * FROM brand";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['brand_id']; ?>"<?php
if ($brand_id == $rowex['brand_id'])
echo 'selected'; ?> class="brand_<?php echo $rowex['cat_id'];?>"><?php echo $rowex['brand_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">PRODUCT NAME</label>
<select id="product" name="product" class="switchable form-control">
<?php
$qex = "SELECT * FROM product";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['product_id']; ?>"<?php
if ($product_id == $rowex['product_id'])
echo 'selected'; ?> class="product_<?php echo $rowex['brand_id'];?>"><?php echo $rowex['product_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">IN STOCK</label>
<input type="number" id="availability" name="availability" value="<?php echo $row['availability'];?>" class="form-control"/>
</div>
</div>
<div class="clearfix"></div>
<div>
<input type="submit" value="Update Data" class="pull-right btn btn-primary submit" style="margin-right:15px;"/>
<span class="pull-left error" style="display:none;margin-left:15px;"> Please Enter Valid Data</span>
<span class="pull-left success" style="display:none;margin-left:15px;"> Data updated!</span>
<div class="clearfix"></div>
</div>
</form>
<?php
}
?>
<script type="text/javascript" >
$(document).ready(function(){
$(function() {
$(".submit").click(function() {
var stock_id = $("#stock_id").val();
var category = $('select[name="category"]').val()
var brand = $('select[name="brand"]').val()
var product = $('select[name="product"]').val()
var availability = $("#availability").val();
var dataString =
'stock_id='+ stock_id +
'&brand=' + brand +
'&category=' + category +
'&product=' + product +
'&availability=' + availability
;
if(
stock_id=='' ||
brand=='' ||
category=='' ||
product=='' ||
availability==''
){
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "update-stock.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
$("#category").change(function () {
if ($(this).data('options') == undefined) {
$(this).data('options', $('select.switchable option').clone());
}
var id = $(this).val();
var that = this;
$("select.switchable").each(function () {
var thisname = $(this).attr('name');
var theseoptions = $(that).data('options').filter('.' + thisname + '_' + id);
$(this).html(theseoptions);
});
});
//then fire it off once to display the correct elements
$('#category').trigger('change');
});/** Document Ready Functions END **/
</script>
<?php } ?>
This is my code for update-stock.php that supposed to be updating the database:
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST) {
$stock_id = $_POST['stock_id'];
$brand = $_POST['brand'];
$category = $_POST['category'];
$product = $_POST['product'];
$availability = $_POST['availability'];
$update = array(
'p_id' => $product,
'brand_id' => $brand,
'cat_id' => $cat,
'availability' => $availability
);
$where_clause = array(
'stock_id' => $stock_id
);
$updated = $database->update( 'stock', $update, $where_clause, 1 );
}
?>
I have a 2 problems.
Update doesn't work at all. I am just getting the message Please Enter Valid Data
My form doesn't show up the correct value of the PRODUCT NAME. Example: In the database and my main table that read information from database product name is 2.1.1 but when I click on edit and open my pop-up form that show up 2.1.3 for example.
Thank you so much in advance for your help.
This one works PERFECT fetch_brand.php:
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST['rowid']) {
$id = $_POST['rowid']; //escape string
$query = "SELECT * FROM brand WHERE brand_id = $id";
$results = $database->get_results( $query );
foreach( $results as $row ){
$cat_id = $row['cat_id'];
?>
<form method="post" name="form">
<input id="brand_id" name="brand_id" type="hidden" value="<?php echo $row['brand_id'];?>"/>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">CATEGORY</label>
<select id="category" name="category" class="form-control">
<?php
$qex = "SELECT * FROM category";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['cat_id']; ?>"<?php
if ($cat_id == $rowex['cat_id'])
echo 'selected'; ?>><?php echo $rowex['cat_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">BRAND NAME</label>
<input type="text" id="brand_name" name="brand_name" value="<?php echo $row['brand_name'];?>" class="form-control"/>
</div>
</div>
<div class="clearfix"></div>
<div>
<input type="submit" value="Update Data" class="pull-right btn btn-primary submit" style="margin-right:15px;"/>
<span class="pull-left error" style="display:none;margin-left:15px;"> Please Enter Valid Data</span>
<span class="pull-left success" style="display:none;margin-left:15px;"> Data updated!</span>
<div class="clearfix"></div>
</div>
</form>
<?php
}
?>
<script type="text/javascript" >
$(document).ready(function(){
$(function() {
$(".submit").click(function() {
var brand_id = $("#brand_id").val();
var brand_name = $("#brand_name").val();
var category = $('select[name="category"]').val()
var dataString =
'brand_id='+ brand_id +
'&brand_name=' + brand_name +
'&category=' + category
;
if(
brand_id=='' ||
brand_name=='' ||
category==''
){
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "update-brand.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
});/** Document Ready Functions END **/
</script>
<?php } ?>
update-product.php :
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST) {
$p_id = $_POST['p_id'];
$brand = $_POST['brand'];
$category = $_POST['category'];
$product = $_POST['product'];
$update = array(
'product_name' => $product,
'brand_id' => $brand,
'cat_id' => $cat
);
$where_clause = array(
'p_id' => $p_id
);
$updated = $database->update( 'product', $update, $where_clause, 1 );
}
?>
This one works excellent! So I am pretty sure that I made a mistake in my code for the stock.
Related
I'm trying to push information from MYSQL, in a PHP File named edit_v and, in my main file "editar_v" I want to fill the input fields inside my forms so after that, user can edit the info related to the vehicle that is stored in my database. For that, I'm using Ajax, so the page doesn't get reloaded/changed.
Here is my main code of editar_v.php:
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<form method="POST" action="editar_v.php">
<div class="form-row">
<div class="form-group col-md-12">
<label for="input_veiculo_editar">Escolha o veículo que pretende editar:</label>
<select class="custom-select my-1 mr-sm-2" id="dropdown_matricula">
<option selected>Veículos Disponíveis</option>
<?php
$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
$sql = "SELECT id, matricula FROM veiculo";
$result = $conn->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
echo "<option value='".$row['id']."'>".$row['matricula']."</option>";
}
}
?>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for"input_marca">Marca do Veículo:</label>
<input type="text" class="form-control" id="input_marca" disabled value="NOTHING">
</div>
<div class="form-group col-md-6">
<label for="input_modelo">Modelo do Veículo:</label>
<input type="text" class="form-control" id="input_modelo" disabled>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for"input_cilindrada">Cilindrada (CV):</label>
<input type="text" class="form-control" id="input_cilindrada" disabled>
</div>
<div class="form-group col-md-6">
<label for="input_potencia">Potencia do Veículo:</label>
<input type="text" class="form-control" id="input_potencia" disabled>
</div>
</div>
<div class="form-group">
<label for="input_combustivel">Combustível:</label>
<input type="text" class="form-control" id="input_combustivel" disabled>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for"input_ano">Ano do Veículo:</label>
<input type="text" class="form-control" id="input_ano" disabled>
</div>
<div class="form-group col-md-6">
<label for="input_modelo">Modelo do Veículo:</label>
<input type="text" class="form-control" id="input_modelo" disabled>
</div>
</div>
<div class="form-group">
<label for="input_escolaID">Escola de Condução a que pertence:</label>
<select class="custom-select my-1 mr-sm-2" id="inlineFormCustomSelectPref" disabled>
<option selected></option>
<?php
$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
$sql = "SELECT id_escola, nome FROM escola";
$result = $conn->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
echo "<option value='".$row['id_escola']."'>".$row['nome']."</option>";
}
}
?>
</select>
</div>
<input type="button" value="Procurar Veículo" id="procuraveiculo">
<input type="button" value="Editar Veículo" id="adicionar_veiculo">
<span id="jsonresultado"></span>
</form>
</div>
</div>
</div>
Inside the same file, i have the following javascript / jquery:
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
console.log("Document ready!");
$("#procuraveiculo").on('click', function() {
var e = document.getElementById("dropdown_matricula");
var strUser = e.options[e.selectedIndex].text;
alert(strUser);
$.ajax({
method: "POST",
url: "admin_pages/veiculo_pages/edit_v.php",
data: {matriculaPHP:strUser},
complete: function(data) {
var yourDataStr = JSON.stringify(data);
var result = yourDataStr;
console.log(result[0].marca);
},
error : function (data) {
console.log("error:"+data.message);
console.log("DATA ERROR:: " + data.msg);
},
dataType: "JSON",
});
});
});
</script>
So in this part of the code, i give the user the option to select one of the available vehicles in the database.
After that, i send it to php file in matriculaPHP, and this is working properly.
Now, there is my edit_v.php:
<?php
$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
$matricula = $_POST['matriculaPHP'];
$sql = "SELECT marca, modelo, cilindrada, potencia, combustivel, ano, mes, escola_id_escola FROM veiculo WHERE matricula='$matricula'";
$result = $conn->query($sql);
if($conn->query($sql) == TRUE)
{
echo "Base de dados conectada!";
}
else
{
echo "Error " . $sql . "<br>" . $conn->error;
}
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
print json_encode($data);
header('Content-type: application/json');
echo json_encode($data);
?>
Conclusion: When i execute my code, i get the right values from the database. Example: [{"marca":"Citroen","modelo":"C3","cilindrada":"1100","potencia":"60","combustivel":"Gasolina","ano":"2002","mes":"6","escola_id_escola":"1"}]
But when i try to read the code inside the JSON/Javascript, it gives me the error of UNDEFINED.
I would like to get some of your help so i can solve this problem and keep working in my project.
First of all, your edit_v.php file is not outputting valid JSON due to the line that prints the connection status of the database.
If you want to do that then you'll have to output all the data as part of an array.
For example:
header('Content-type: application/json');
$res = array(
'success' => false,
'errors' => array(),
'data' => null
);
$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo")
$matricula = $_POST['matriculaPHP'];
$sql = "SELECT marca, modelo, cilindrada, potencia, combustivel, ano, mes, escola_id_escola FROM veiculo WHERE matricula='$matricula'";
$result = $conn->query($sql);
if($conn->query($sql) == TRUE)
{
// echo "Base de dados conectada!";
$res['success'] = true;
$res['data'] = array();
while ($row = $result->fetch_assoc())
{
$res['data'][] = $row;
}
}
else
{
$res['errors'][] = "Error " . $sql . "<br>" . $conn->error;
}
echo json_encode($data);
Also, the Content-Type header has to be set before any output is made.
In the complete function of your JQuery request, you are converting the JSON data to a String using JSON.stringify(...) which should not be. You should try changing the complete function to success and use the data as is.
...
success: function(data) {
console.log(data[0].marca);
},
...
Problem is with JavaScript and PHP JSON.
When there is only one element in array, there is no record zero.
Please use code: console.log(data.marca) instead of console.log(data[0].marca) and you will see result.
You have to check if in JSON is just one element array or few and then use proper code.
Solved
finally I solved my problem with the help of this big community!
Editar_v.php jquery:
$("#procuraveiculo").on('click', function() {
var e = document.getElementById("dropdown_matricula");
var strUser = e.options[e.selectedIndex].text;
alert(strUser);
$.ajax({
method: "POST",
url: "admin_pages/veiculo_pages/edit_v.php",
data: {matriculaPHP:strUser},
success: function(data) {
var marca = data[0].marca;
var modelo = data[0].modelo;
var cilindrada = data[0].cilindrada;
var potencia = data[0].potencia;
var combustivel = data[0].combustivel;
var ano = data[0].ano;
var mes = data[0].mes;
var idEscola = data[0].escola_id_escola;
And now, the PHP file: edit_v.php:
<?php
header('Content-type: application/json');
$res=array(
'success' => false,
'errors' => array(),
'data' => null
);
$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
$matricula = $_POST['matriculaPHP'];
$sql = "SELECT marca, modelo, cilindrada, potencia, combustivel, ano, mes, escola_id_escola FROM veiculo WHERE matricula='$matricula'";
$result = $conn->query($sql);
if($conn->query($sql) == TRUE)
{
// echo "Base de Dados conectada!";
$res['success'] = true;
$res['data'] = array();
while($row = $result->fetch_assoc())
{
$res['data'][] = $row;
}
}
else
{
$res['errors'][] = "Error " . $sql . "<br>" . $conn->error;
}
echo json_encode($res['data']);
?>
This is working very well, and now I do understand how jquery works in this situations. Also understood what was my fault in PHP.
My thanks to #Omari Celestine and #Norbul and to stackoverflow community.
hello i'm using Yii framework and oracle database. i need some help to solve this problem. i've a form for sending an email. my form looks like this
email desc: _______|v| (dropdown value form database)
email subject : _________ (this field will automatically filled with data of selected email subject)
email body : _______ (this field will automatically filled with data of selected email subject)
my table:
email_desc| subject| body_email
payment1 | payment for house rent | address: **** city: jakarta
ex: i choose email_desc as payment1, email subject will automatically filled as "payment for rent" and email body will automatically filled as address: **** city: jakarta
here is my form
<div class="control-group">
<?php echo $form->labelEx($model,'EMAIL_DESC', array('class'=>'control-label')); ?>
<?php echo $form->dropDownlist($model,'EMAIL_DESC',
(CHtml::listData (TrnProjImplement::model()->getList(),'EMAIL_DESC','EMAIL_DESC')),
array(
'empty'=>'--Pilih salah satu--',
'value'=>$model->EMAIL_DESC,
'id'=>"dropDown",
'ajax'=>array(
'type'=>'GET',
'url'=>CController::createUrl('email/field'),
'update'=>'#subject',
'data'=>array('EMAIL_DESC'=>'js: this.value'),
),
));
?>
<span class="help-inline text-error"><?php echo $form->error($model,'EMAIL_DESC'); ?></span>
</div>
<div class="control-group">
<?php echo $form->labelEx($model,'SUBJECT', array('class'=>'control-label')); ?>
<?php echo $form->textField($model,'SUBJECT',array('size'=>60,'maxlength'=>100, 'style'=>'width:600px', 'id'=>"subject"));?>
<?php //echo CHtml::activeTextField($model, 'SUBJECT',
// array(
// 'ajax'=>array(
// 'type'=>'POST',
// 'url'=>Yii::app()->createUrl('email/create'),
// 'id'=>'subject',
// ),
// ));
?>
<span class="help-inline text-error"><?php echo $form->error($model,'SUBJECT'); ?></span>
</div>
<!--<div class="control-group" id="body-email">-->
<div class="control-group">
<?php echo $form->labelEx($model,'BODY_EMAIL', array('class'=>'control-label')); ?>
<?php echo $form->textArea($model,'BODY_EMAIL',array('size'=>1000,'maxlength'=>1000,'style'=>'height:200px; width:600px;', 'id'=>"body-email")); ?>
<span class="help-inline text-error"><?php echo $form->error($model,'BODY_EMAIL'); ?></span>
</div>
javascript
<script>
function insertField(){
var desc = document.getElementById("dropDown").value;
var subj = document.getElementById("subject").value;
var body = document.getElementById("body-email").value;
$.ajax({
type : "POST",
url : "<?php echo Yii::app()->createUrl("emaildetail/field"); ?>",
data : {
"desc" : desc,
"subj" : subj,
"body" : body,
},
success: function (){
alert('asd');
},
});
</script>
my controller
public function actionField(){
if(isset($_POST['desc'])){
$connection=Yii::app()->db;
$desc = Yii::app()->request->getPost('desc');
$subj = Yii::app()->request->getPost('subj');
$body = Yii::app()->request->getPost('body');
$sql = 'SELECT SUBJECT FROM EMAIL_DETAIL WHERE EMAIL_DESC = $desc';
$sql2 = 'SELECT BODY_EMAIL FROM EMAIL_DETAIL WHERE EMAIL_DESC = $desc';
$model2 = EMAIL_DETAIL::model()->findByAttributes(array('EMAIL_BODY'=>$desc));
if(isset($desc)){
$subj = $model->SUBJECT;
$body = $model->EMAIL_BODY;
}
}
}
i could get the value of email_desc but i still cant automatically fill other field
You can change your code as following solution.
Please change your form as below code :
<div class="control-group">
<?php echo $form->labelEx($model,'EMAIL_DESC', array('class'=>'control-label')); ?>
<?php echo $form->dropDownlist($model,'EMAIL_DESC',
(CHtml::listData (TrnProjImplement::model()->getList(),'EMAIL_DESC','EMAIL_DESC')),
array(
'empty'=>'--Pilih salah satu--',
'value'=>$model->EMAIL_DESC,
'id'=>"dropDown",
'ajax'=>array(
'type'=>'POST',
'url'=>CController::createUrl('email/field'),
'data'=>array('EMAIL_DESC'=>'js: this.value'),
'success'=> 'function(response) {if (response.status == "success") {
$("#SUBJECT").val(response.subj);
$("#BODY_EMAIL").val(response.body);
} else {
$("#SUBJECT").val("");
$("#BODY_EMAIL").val("");
}
}',
'error'=> 'function(){alert("AJAX call error..!!!!!!!!!!");}',
),
));
?>
<span class="help-inline text-error">
<?php echo $form->error($model,'EMAIL_DESC'); ?>
</span>
</div>
<div class="control-group">
<?php echo $form->labelEx($model,'SUBJECT', array('class'=>'control-label')); ?>
<?php echo $form->textField($model,'SUBJECT',array('size'=>60,'maxlength'=>100, 'style'=>'width:600px', 'id'=>"subject"));?>
<span class="help-inline text-error"><?php echo $form->error($model,'SUBJECT'); ?></span>
</div>
<div class="control-group">
<?php echo $form->labelEx($model,'BODY_EMAIL', array('class'=>'control-label')); ?>
<?php echo $form->textArea($model,'BODY_EMAIL',array('size'=>1000,'maxlength'=>1000,'style'=>'height:200px; width:600px;', 'id'=>"body-email")); ?>
<span class="help-inline text-error"><?php echo $form->error($model,'BODY_EMAIL'); ?></span>
</div>
Please change your Controller code :
<?php
public function actionField() {
if (Yii::app()->request->isAjaxRequest){
$desc = Yii::app()->request->getPost('EMAIL_DESC');
$model = EMAIL_DETAIL::model()->findByAttributes(array('EMAIL_BODY' => $desc));
if (!empty($model)) {
$data['status'] = 'success';
$data['subj'] = $model->SUBJECT;
$data['body'] = $model->EMAIL_BODY;
} else {
$data['status'] = 'error';
$data['subj'] = '';
$data['body'] = '';
}
echo json_encode($data);
Yii::app()->end();
} else
throw new CHttpException(400, '404_error_message');
}
?>
I hope this will helps you. Thanks!
I am unable to fetch the data in the second dropdown(which is depended upon the first dropdown). e.g. when we select country then the relevant state should be displayed but it doesn't. see my code.
my html
<?php
require 'dbconfig.php';
?>
<label class="control-label">Select Distict</label>
<div class="form-group">
<div class="col-lg-6">
<select class="form-control" name=dist id=dist>
<option value='' selected>Select</option>
<?Php
$ddObj = new USER($DB_con);
$table= "tbl_dist";
$sel = $ddObj->dropdowndist($table);
foreach ($sel as $val) {
echo "<option value=$val[dist_id]>$val[dist_name]</option>";
}
?>
</select>
</div>
</div>
<label class="control-label">Select Block</label>
<div class="form-group">
<div class="col-lg-6">
<select class="form-control" name=block id=block>
</select>
</div>
</div>
my jquery
<script>
$(document).ready(function() {
$('#dist').change(function(){
var dist_id=$('#dist').val();
$('#block').empty(); //remove all existing options
$.get('ddblock.php',{'dist_id':dist_id},function(return_data){
$.each(return_data.data, function(key,value){
$("#block").append("<option value='" + value.block_id +"'>"+value.block_name+"</option>");
});
}, "json");
});
});
</script>
ddblock.php
<?Php
$dist_id=$_GET['dist_id'];
if(!intval($dist_id)){
echo "Data Error";
exit;
}
require 'class.user.php';
$ddObj = new USER($DB_con);
$table = "tbl_block";
$result = $ddObj->fetch_block($table,$dist_id);
$main = array('data'=>$result);
echo json_encode($main);
}
?>
class.user.php
public function fetch_block($table,$dist_id){
try
{
$sel = $this->db->prepare("SELECT * FROM $table WHERE block_dist_id=:dist_id");
$sel->bindValue(':dist_id', $dist_id);
$sel->execute();
$rs = $sel->setFetchMode( PDO::FETCH_ASSOC );
return $sel;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
This is my form
<?php
$sql15 = "select * from reviewed_title";
$query15 = sqlsrv_query( $link, $sql15);
$count = 1;
while( $row = sqlsrv_fetch_array( $query15, SQLSRV_FETCH_ASSOC) ) { ?>
<div class = "title_body">
<div class = "title_top">
<div class="form-group">
<h3><?php
$title_id = $row['id'];
echo $count .". ".$row['title'];
?>
</h3>
</div>
</div>
<?php
$sql16 = "select * from item_reviewed WHERE title_id = $title_id";
$count2=1;
$query16 = sqlsrv_query( $link, $sql16);
$query17 = sqlsrv_query($link, $sql16, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
$row_num = sqlsrv_num_rows($query17);
//$row_num = 5;
while( $row2 = sqlsrv_fetch_array( $query16, SQLSRV_FETCH_ASSOC) ) { ?>
<div class = "title_bottom"
<?php if($row_num != $count2){?> style="border-bottom: 1px solid #000000;" <?php }?> >
<div class="form-group">
<input type="hidden" name="item_reviewed_id" value="<?php echo $row2['id'];?>" class="item_reviewed_id">
<div class = "title_bottom_left">
<h6> <?php echo $count.".".$count2 .". ".$row2['items'];
?></h6>
</div>
<div class= "title_bottom_center">
<label class="col-sm-2 label2" for="email">Y,N,N/A:</label>
<!--<select name="action" class="select <select_<?php echo $row2['id'];?>" id="select_<?php echo $count."".$count2;?>">-->
<select name="action" class="select" >
<option value="">Select</option>
<option value="yes">Yes</option>
</select>
</div>
<div class ="title_bottom_right">
<label class="col-sm-2 label3" for="email">Comment:</label>
<!--<textarea name="comment" class="form-control comment commentttt comment_<?php echo $row2['id'];?>>" <id="comment_<?php echo $count."".$count2;?>" placeholder="Comment"></textarea>-->
<textarea name="comment" class="form-control comment commentttt" placeholder="Comment"></textarea>
</div>
</div>
</div>
<?php $count2++;}?>
</div>
<?php $count++; }?>
Here I get 33 input fields, 33 select fields and 33 hidden fields.From table item_reviewed here i get 33 row. My jQuery code is ..
var ittem_id = new Array();
var j = 1;
$(".item_reviewed_id" ).each(function( i ) {
ittem_id[j] = $(this).val();
j++;
});
alert(j);
Here I get 1552 values. How i can get 33 values in jQuery ?
if you ve 1552 item and that loop output only 33 rows you must ve some other elements with class .item_reviewed_id in your page.
Use 2 classes to be sure you re selecting the right elements. JQuery map could be a very easy way to map your elements values
<input type="hidden" name="item_reviewed_id" value="<?php echo $row2['id'];?>" class="item_reviewed_id thisclass">
var ittem_id = $('.item_reviewed_id.thisclass').map(function(){
return $(this).val();
});
console.log(ittem_id); //this will be an array with your values!
Here is an image of what I'm trying to accomplish -
Example of my Database Table -
My goal is to get a similar product to the product that is currently displaying without refreshing the page. I am trying to find similar products is by using check boxes.
I first got the id using $_GET['id'] which should be equal to one of the values in my table.
I then used PDO Fetch to get the product name, brand, quanity and price of that particular id and store it as a string.
What I need help with is using JQuery/AJAX to get the checkboxes that are checked and then send the information to a PHP file that would check if filter results match with any data from the table.
How can I do this?
This is my product.php file
<?php
require ('includes/db.php');
$id = $_GET['id']; //Getting the ID in URL. ex products.php?id=12
$stmt = $handler->prepare("SELECT * FROM products WHERE id = '$id' ");
$result = $stmt->execute(array());
$products = $stmt->fetch(PDO::FETCH_ASSOC);
$prod_name = $products['prod_name']; //Product Name
$brand = $products['brand']; //Product Brand
$quantity = $products['quantity']; //Product Quantity
$calories = $products['calories']; //Product Calories
$price = $products['price']; //Product Price
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo "$brand $prod_name"; ?></title>
</head>
<body>
<h1><?php echo $prod_name; ?></h1>
<br />
<p>Brand = <?php echo " $brand"; ?></p>
<p>Quantity = <?php echo " $quantity"; ?></p>
<p>Calories = <?php echo " $calories"; ?></p>
<p>Price = <?php echo " $price"; ?></p>
<br />
<p style="text-align: center;">Find Similar Products</p>
<form>
<div class="checkboxes">
<label>
<input name="brand" type="checkbox" value="<?php echo $brand; ?>">
<span>Brand</span> <!--Brand Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="quanitity" type="checkbox" value="<?php echo $quantity; ?>">
<span>Quantity</span> <!--Quantity Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="calories" type="checkbox" value="<?php echo $calories; ?>">
<span>Calories</span> <!--Calories Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="price" type="checkbox" value="<?php echo $price; ?>">
<span>Price</span> <!--Price Checkbox-->
</label>
</div>
</form>
</body>
</html>
I managed to solve this out, glad I didn't give up.
My product.php File
<?php
require ('/db.php');
$id = $_GET['id']; //Getting the ID in URL. ex products.php?id=12
$stmt = $handler->prepare("SELECT * FROM products WHERE id = '$id' ");
$result = $stmt->execute(array());
$products = $stmt->fetch(PDO::FETCH_ASSOC);
$prod_name = $products['prod_name']; //Product Name
$brand = $products['brand']; //Product Brand
$quantity = $products['quantity']; //Product Quantity
$calories = $products['calories']; //Product Calories
$price = $products['price']; //Product Price
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo "$brand $prod_name"; ?></title>
</head>
<body>
<h1><?php echo $prod_name; ?></h1>
<br />
<p>Brand = <?php echo " $brand"; ?></p>
<p>Quantity = <?php echo " $quantity"; ?></p>
<p>Calories = <?php echo " $calories"; ?></p>
<p>Price = <?php echo " $price"; ?></p>
<br />
<p style="text-align: center;">Find Similar Products</p>
<form method="post" action="">
<div class="checkboxes">
<label>
<input name="brand" type="checkbox" value="<?php echo $brand; ?>">
<span>Brand</span> <!--Brand Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="quanitity" type="checkbox" value="<?php echo $quantity; ?>">
<span>Quantity</span> <!--Quantity Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="calories" type="checkbox" value="<?php echo $calories; ?>">
<span>Calories</span> <!--Calories Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="price" type="checkbox" value="<?php echo $price; ?>">
<span>Price</span> <!--Price Checkbox-->
</label>
</div>
</form>
<div class="filter_container">
<div style="clear:both;"></div>
</div>
<script type="text/javascript" src="/js/filter.js"></script>
<input name="prod_name" value="<?php echo $prod_name ?>" style="display:none;"/>
<!--Hidden product name-->
</body>
</html>
Here is my JS File
$(document).ready(function() {
function showValues() {
var brand;
var quantity;
var calories;
var price;
//Gets product name
var prod_name = $('input[name="prod_name"]').val();
//Gets brand
if($('input[name="brand"]').is(':checked'))
{brand = $('input[name="brand"]').val();} else {brand = ""}
//Gets quantity
if($('input[name="quantity"]').is(':checked'))
{quantity = $('input[name="quantity"]').val();} else {quantity = ""}
//Gets calories
if($('input[name="calories"]').is(':checked'))
{calories = $('input[name="calories"]').val();} else {calories = ""}
//Gets price
if($('input[name="price"]').is(':checked'))
{price = $('input[name="price"]').val();} else {price = ""}
$.ajax({
type: "POST",
url: "/query.php",
data: {'brand':brand, 'quantity':quantity, 'calories':calories, 'prod_name':prod_name},
cache: false,
success: function(data){
$('.filter_container').html(data)
}
});
}
//Call function when checkbox is clicked
$("input[type='checkbox']").on( "click", showValues );
//Remove checked when checkbox is checked
$(".checkboxes").click(function(){
$(this).removeAttr('checked');
showValues();
});
});
Here is my PHP File
<?php
include('/db.php');
$prod_name = $_POST['prod_name'];
$Cbrand = $_POST['brand'];
$Cquantity = $_POST['quantity'];
$Ccalories = $_POST['calories'];
$Cprice = $_POST['price'];
if(!empty($Cbrand))
{
$data1 = "brand = '$Cbrand' AND";
}else{
$data1 = "";
}
if(!empty($Cquantity))
{
$data2 = "quantity = '$Cquantity' AND";
}else{
$data2 = "";
}
if(!empty($Ccalories))
{
$data3 = "calories = '$Ccalories' AND";
}else{
$data3 = "";
}
if(!empty($Cprice))
{
$data4 = "price = '$Cprice'";
}else{
$data4 = "";
}
$main_string = "WHERE $data1 $data2 $data3 $data4"; //All details
$stringAnd = "AND"; //And
$main_string = trim($main_string); //Remove whitespaces from the beginning and end of the main string
$endAnd = substr($main_string, -3); //Gets the AND at the end
if($stringAnd == $endAnd)
{
$main_string = substr($main_string, 0, -3);
}else if($main_string == "WHERE"){
$main_string = "";
}
else{
$main_string = "WHERE $data1 $data2 $data3 $data4";
}
if($main_string == ""){ //Doesn't show all the products
}else{
$sql = "SELECT COUNT(*) FROM products $main_string";
if ($res = $handler->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
$sql = "SELECT * FROM products $main_string";
foreach ($handler->query($sql) as $pro) {
if(($pro['prod_name'] == $prod_name) && ($res->fetchColumn() < 2))
{
//The product currently being displayed is blank when using the filter
}
else{
?>
<!------------------------------------------------------------------------------------------------------------------------------------------------->
<div class="form-result">
<td><?=strtoupper($pro['brand']) + " " + strtoupper($pro['prod_name']); ?></td>
</div>
<!------------------------------------------------------------------------------------------------------------------------------------------------->
<?php
}
}
} /* No rows matched -- do something else */
else {
?>
<div align="center"><h2 style="font-family:'Arial Black', Gadget, sans-serif;font-size:30px;color:#0099FF;">No Results with this filter</h2></div>
<?php
}
}
}
$handler = null;
$res = null;
?>