how to convert multiple array to string in php - php

Hi All,
i'm getting all the data from database for array format i need to pass that data to second drop down list like (group option value),please any one help me.
This is my php code:
<?php
//error_reporting(0);
$servername = "localhost";
$username = "root";
$password = "";
$db = "essae";
$data = "";
$subcategory_id = "";
$subcategory_name = array();
$conn = mysqli_connect($servername, $username, $password,$db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$category= $_GET["category_id"];
$sql = "SELECT es_category.category_id,es_category_description.name FROM es_category INNER JOIN es_category_description ON es_category.category_id=es_category_description.category_id WHERE parent_id='$category'";
$result = $conn->query($sql);
if ($result->num_rows > 1){
$sql_getrec ="SELECT es_category.category_id AS sub_cat_id,es_category_description.name AS sub_cat_name FROM es_category INNER JOIN es_category_description ON es_category.category_id=es_category_description.category_id WHERE parent_id='$category'";
$sub_category= $conn->query($sql_getrec);
if ($sub_category->num_rows > 1){
while ($row=mysqli_fetch_array($sub_category)){
$subcategory_id = $row['sub_cat_id'];
//$subcategory_name['sub_category_name'][] = $row['sub_cat_name'];
$sql_getrec = "SELECT es_product_description.name AS prod_name FROM es_product_to_category LEFT JOIN es_product_description ON es_product_description.product_id=es_product_to_category.product_id LEFT JOIN es_product ON es_product_description.product_id = es_product.product_id WHERE es_product_to_category.category_id = $subcategory_id AND es_product.status=1";
$sub_product=$conn->query($sql_getrec);
while ($prow=mysqli_fetch_array($sub_product)){
$subcategory_name['sub_category_name'][$row['sub_cat_name']]['products_name'][] = $prow['prod_name'];
}
}
echo "<pre>";print_r($subcategory_name);
}
}
else {
$sql_getrec = "SELECT es_product_description.name FROM es_product_to_category LEFT JOIN es_product_description ON es_product_description.product_id=es_product_to_category.product_id LEFT JOIN es_product ON es_product_description.product_id = es_product.product_id WHERE es_product_to_category.category_id='$category' AND es_product.status=1";
$result_getrec=$conn->query($sql_getrec);
while ($row=mysqli_fetch_array($result_getrec)){
$data .= $row['name'].",";
}
$data = rtrim($data,",");
}
print_r($data);
?>
This is my Html code:
<php?
$decocedData1 = json_decode($str_json_format, TRUE);
//print_r($decocedData1);die;
$decode = $decocedData1;
?>
<div>
<select name="category" id="category" />
<option selected ="selected">Select category</option>
<?php foreach($decode as $key => $value) { ?>
<option value="<?php echo $value['category_id']; ?>"><?php echo $value['name']; ?></option>
<?php } ?>
</select>
</div>
<div><select name="category12" id="category12" />
</select>
</div>
this is my j query and ajax method code:
<script type="text/javascript">
$(document).ready(function(){
$('#category').change(function(){
var category_id=$('#category').val();
$.ajax({
type: "get",
url: 'data_product.php?category_id='+category_id,
success: function(data) {
var products = data.split(",");
state_html = '';
state_html = '<option>Please Select product</option>'
$.each(products, function (index, productName) {
state_html += "<option value='"+productName+"'>"+productName+"</option>";
});
$('#category12').html(state_html);
},
});
})
});
</script>

You may use Type Casting in php
Type casting in PHP works much as it does in C: the name of the
desired type is written in parentheses before the variable which is to
be cast.
<?php
$array = array("name", "age", "mobile", "email");
var_dump($array);
(string)$array;
var_dump($array);
?>

This is not your final answer but you can try below code and figure out your variable names
$('#category12').empty();
$.each(data, function (index) {
var optgroup = $('<optgroup>');
optgroup.attr('label',data[index].name);
$.each(data[index].children, function (i) {
var option = $("<option></option>");
option.val(i);
option.text(data[index].children[i]);
optgroup.append(option);
});
$("#category12").append(optgroup);
});
$("#category12").multiselect('refresh');

you can do a jquery each in the result of your ajax
$.each(products, function(key, value) {
$('#category12')
.append($("<option></option>")
.attr("value",value)
.text(value));
});
$(function(){
//sample result, this will be your ajax result....
var products = ["Candy", "Cotton Candy", "Iced Candy"];
//clear again the select element.
$('#category12').empty();
$.each(products, function(key, value) {
$('#category12')
.append($("<option></option>")
.attr("value",value)
.text(value));
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="category12"></select>

Related

Unable to get html data From option value

I am getting the id of selected option value But the table data is not displayed with option change. I am not getting error and not able to find what is mistake.
dashboard.php
<select id="employee">
<option value="" selected="selected"></option>
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db_name = "test2";
$lastId="";
//create connection
$con = mysqli_connect($host, $user, $pass, $db_name);
$sql = "SELECT asset_type,department,cost FROM track_data";
$resultset = mysqli_query($con, $sql) or die("database error:". mysqli_error($conn));
while( $rows = mysqli_fetch_assoc($resultset) ) {
?>
<option value="<?php echo $rows["id"]; ?>"><?php echo $rows["asset_type"]; ?></option>
<?php } ?>
</select>
<div id="display" style="color: black">
<div class="row" id="heading" style="color: black"><h3><div class="col-sm-4"><strong>Employee Name</strong></div><div class="col-sm-4"><strong>Age</strong></div><div class="col-sm-4"><strong>Salary</strong></div></h3></div><br>
<div class="row" id="records" style="color: black"><div class="col-sm-4" id="emp_name"></div><div class="col-sm-4" id="emp_age"></div><div class="col-sm-4" id="emp_salary"></div></div>
</div>
<script type="text/javascript">
$(function () {
// $("#show_table").show();
$(document).ready(function(){
// code to get all records from table via select box
$("#employee").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'id='+ id;
$.ajax({
url: 'getEmployrr.php',
dataType: "json",
data: dataString,
cache: false,
success: function(employeeData) {
if(employeeData) {
$("#emp_name").text(employeeData.asset_type);
$("#emp_age").text(employeeData.department);
$("#emp_salary").text(employeeData.cost);
$("#records").show();
} else {
$("#heading").hide();
$("#records").hide();
}
}
});
})
});
});
</script>
getEmployrr.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db_name = "test2";
$lastId="";
//create connection
$con = mysqli_connect($host, $user, $pass, $db_name);
if($_REQUEST['id']) {
$sql = "SELECT asset_type,department,cost FROM track_data WHERE id='".$_REQUEST['id']."'";
$resultset = mysqli_query($con, $sql) or die("database error:". mysqli_error($con));
$data = array();
while( $rows = mysqli_fetch_assoc($resultset) ) {
$data = $rows;
}
echo json_encode($data);
} else {
echo 0;
}
?>
I am getting the head but not able to get the values inside the div. I am not getting any type of errors but values are not displaying. How can I solve the issue.
In first SQL query :
$sql = "SELECT asset_type,department,cost FROM track_data";
You don't select id, try to add it to your query :
$sql = "SELECT id,asset_type,department,cost FROM track_data";

variable fails when passing inside a query

I am passing the $place variable to a query in listplace.php using a ajax call. The ajax call works perfectly in php1.php code, but the $place value is not passed over the query. Please help!
listplace.php too works perfectly but when i try to pass $place in where condition it fails.
php1.php code
<select id="name">
<option selected disabled>Please select</option>
</select>
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET['place'] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>
<?php } ?>
listplace.php
<?php
//connect to the mysql
$db = #mysql_connect('localhost', 'root', 'password') or die("Could not connect database");
#mysql_select_db('test', $db) or die("Could not select database");
$place = $_POST['place'];
$sql = #mysql_query("select product_name from products_list where product_name = '$place'");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r['product_name'];
}
if (count($rows)) {
echo json_encode(['option'=> $rows]);
}else {
echo json_encode(['option'=> false]);
}
?>
An improvement will be to start using prepared statements. This is just an addition to Exprator's answer
This will prevent SQL injection attacks.
$sql_con = new mysqli('localhost', 'root', 'password', 'test');//get connection
$place = $_POST['place'];//posted variable
if($stmt = $sql_con->prepare("select product_name from products_list where product_name =?")) {//prepare returns true or false
$stmt->bind_param("s", $place); //bind the posted variable
$stmt->execute(); //execute query
$stmt->bind_result($product_name);//bind the result from query securely
$rows = array();//create result array
while ($stmt->fetch()) {//start loop
$rows[] = $product_name;//grab everything in array
}
if (count($rows)) {//check for number
echo json_encode(['option'=> $rows]);
} else {
echo json_encode(['option'=> false]);
}
change this line
data: {place: '<?= $_GET['place'] ?>'},
to
data: {place: '<?= $_GET["place"] ?>'},

get data from database using ajax not working

i have this code:connection to database
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$conn = new mysqli("localhost", "root", "", "jquery");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
now i already have data indatabase in table called city witch it have only id and desc and this is the code
if (isset($_POST['city'])) {
$sql = "SELECT * FROM city";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$results = [];
while($row = $result->fetch_assoc()) {
$results[] = $row;
}
echo json_encode($Results);
}
else
{
echo "empty";
}
}
here is the html part:
<select required="required" id="city">
<option disabled selected value=''> select a city </option>
</select>
and here is the function:
function city() {
$.ajax({
"url": "divs.php",
"dataType": "json",
"method": "post",
//ifModified: true,
"data": {
"F": ""
}
})
.done(function(data, status) {
if (status === "success") {
for (var i = 0; i < data.length; i++) {
var c = data[i]["city"];
$('select').append('<option value="'+c+'">'+c+'</option>');
}
}
})
.always(function() {
});
}
so the problem is that there is nothing in select list its always empty, any help? thank u
One small mistake is here:
You are using
echo json_encode($Results);
instead of
echo json_encode($results);
In PHP variable names are case sensitive. So, use proper case for all the variables.
You are not getting the response data in HTML <SELECT> TAG here is what you can do.
image to table
HTML FILE CODE:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form action="" method="post">
<select>
</select>
</form>
<script>
$(document).ready(function(){
city();
});
function city(){
$.ajax({
type:'POST',
url: 'divs.php',
data: {city:1},
success:function(data){
var res = JSON.parse(data)
for(var i in res){
var showdata = '<option value="'+res[i].city_name+'">'+res[i].city_name+'</option>';
$("select").append(showdata);
}
}
});
}
</script>
</body>
</html>
HERE IS THE PHP CODE
`
<?php
$conn = new mysqli('localhost','root','','demo');
if($conn->connect_error){
die ("Connection Failed".$conn->link->error);
}
if(isset($_POST['city'])){
$sql = "SELECT * FROM city";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$results[] = $row;
}
echo json_encode($results);
}
else
{
echo "no city available";
}
}
?>
`
HERE IS THE OUTPUT IMAGE
You have used $results but while echoing you are using $Results which is a different variable so use,
echo json_encode($results);
Also, you are telling that city has only id and desc so in JS code use desc instead of city
$.ajax({
type:'POST',
url: 'divs.php',
data: {city:1},
success:function(data) {
var res = JSON.parse(data);
$(res).each(function(){
var c = this.city_name; // use city_name here instead of city
$('select').append('<option value="'+c+'">'+c+'</option>');
});
}
});

$POST and $GET to get value from dropdown

a.html
function load(str)
{
xhttp.open("GET","a.php?q="+str,true);
xhttp.send();
}
}
<select name = "select" onchange ="load(this.value)">
<option selected = "selected">Select a movie</option>
<option value= "asc">Name in ascending order</option>
<option value = "genre">Genre</option>
</select>
a.php
$asc = $_POST['asc'];
$genre = $_POST['genre'];
if (!empty($_GET[$asc])) {
$sql = "SELECT * FROM movies order by Name ASC";
} else if (!empty($_GET[$genre])) {
$sql = "SELECT * FROM movies order by Genre ASC";
}
$db = mysql_connect("localhost","root","123");
$db_select = mysql_select_db('m',$db);
if ( ( $result = mysql_query( $sql, $db ) ) ) {
echo $result;
}
I want to select the value from dropdown button. For instance asc, and pass the value to a.php ($asc = $_POST['asc']). How could I do that?
<html>
<head></head>
<body>
<select class="movie" name="select">
<option selected = "selected">Select a movie</option>
<option value= "asc">Name in ascending order</option>
<option value = "genre">Genre</option>
</select>
<div class="showMovie"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$('.movie').change(function(){
var movieType= $('.movie').val();
$.ajax({url:"a.php?movieType="+movieType,cache:false,success:function(result){
$(".showMovie").html(result);
}});
});
</script>
</body>
</html>
a.php
<?php
$movieType = $_GET['movieType'];
if ($movieType == "asc") {
$sql = "SELECT * FROM movies order by Name ASC";
} else if ($movieType == "genre") {
$sql = "SELECT * FROM movies order by Genre ASC";
}
$db = mysql_connect("localhost","root","123");
$db_select = mysql_select_db('m',$db);
if (($result = mysql_query($sql, $db))) {
while($movieName = mysql_fetch_array($result)) {
echo $movieName['Name']."<br>";
}
}
?>
with your JS function, you send it via a "get" method.
so you have your value into $_GET['q'] ...
If you want to do a POST request, use a form, or an XmlHttp function:
function load(obj)
{
var xmlhttp = new XMLHttpRequest();
xmlxttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
//called when xmlhttp event occurs, here when we receive the response
console.log(xmlhttp.responseText); //Print the response into the console
}
}
xmlhttp.open("POST", "a.php");
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); //we send it as form
xmlhttp.send(obj.value + "=" + encodeURICompopent(obj.innerHTML));
}
And call load(this) instead of load(this.value)
In php, to check is value is sent, just use isset:
if (isset($_POST['asc'])) //do something;
But I dislike this way to send values, it is deprecated: request parameters names should be static....
a.html
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#select_name').on('change', function() {
var str = $(this).val();
$.ajax({
type: "POST",
url: "a.php",
data: { q:str},
success: function(theResponse) {
// Output from ajaxpage.php
alert(theResponse); // comment this
}
});
});
});
</script>
<select name = "select_name" id = "select_name">
<option selected = "selected">Select a movie</option>
<option value= "asc">Name in ascending order</option>
<option value = "genre">Genre</option>
</select>
a.php
<?php
$db = mysql_connect("localhost","root","123");
$db_select = mysql_select_db('m',$db);
$q = isset($_POST['q']) ? $_POST['q'] : '';
if ($q == 'asc')
{
$sql = "SELECT * FROM movies order by Name ASC";
}
else if ($q == 'genre')
{
$sql = "SELECT * FROM movies order by Genre ASC";
}
else
{
echo 'Nothing';exit();
}
$qry = mysql_query($sql);
if (mysql_num_rows($qry) > 0)
{
$result = mysql_fetch_object($sql) ;
echo $result;
}
?>

Pass AJAX Variable to PHP and displaying MySQL results after selection from Dynamic Dropdown

I'm having a problem passing a variable selected from a dynamic drop dropdown to a PHP file. I want the PHP to select all rows in a db table that match the variable. Here's the code so far:
select.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#type").attr("disabled","disabled");
$("select#category").change(function(){
$("select#type").attr("disabled","disabled");
$("select#type").html("<option>wait...</option>"); var id = $("select#category option:selected").attr('value');
$.post("select_type.php", {id:id}, function(data){
$("select#type").removeAttr("disabled");
$("select#type").html(data);
});
});
$("form#select_form").submit(function(){
var cat = $("select#category option:selected").attr('value');
var type = $("select#type option:selected").attr('value');
if(cat>0 && type>0)
{
var result = $("select#type option:selected").html();
$("#result").html('your choice: '+result);
$.ajax({
type: 'POST',
url: 'display.php',
data: {'result': myval},
});
}
else
{
$("#result").html("you must choose two options!");
}
return false;
});
});
</script>
</head>
<body>
<?php include "select.class.php"; ?>
<form id="select_form">
Choose a category:<br />
<select id="category">
<?php echo $opt->ShowCategory(); ?>
</select>
<br /><br />
Choose a type:<br />
<select id="type">
<option value="0">choose...</option>
</select>
<br /><br />
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
<?php include "display.php"; ?>
<div id="result2"></div>
</body>
</html>
select.class.php
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowCategory()
{
$sql = "SELECT * FROM profession";
$res = mysql_query($sql,$this->conn);
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value="' . $row['id_cat'] . '">' . $row['prof_name'] . '</option>';
}
return $category;
}
public function ShowType()
{
$sql = "SELECT * FROM specialties WHERE id_cat=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$type = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['id_type'] . '">' . $row['sp_name'] . '</option>';
}
return $type;
}
}
$opt = new SelectList();
?>
And here's the display.php that I want the variable passed to. This file will select the criteria from the db and then print the results in select.php.
<?php
class DisplayResults
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowResults()
{
$myval = $_POST['result'];
$sql = "SELECT * FROM specialities WHERE 'myval'=sp_name";
$res = mysql_query($sql,$this->conn);
echo "<table border='1'>";
echo "<tr><th>id</th><th>Code</th></tr>";
while($row = mysql_fetch_array($res))
{
while($row = mysql_fetch_array($result)){
echo "<tr><td>";
echo $row['sp_name'];
echo "</td><td>";
echo $row['sp_code'];
echo "</td></tr>";
}
echo "</table>";
//}
}
return $category;
}
}
$res = new DisplayResults();
?>
I'd really appreciate any help. Please let me know if I can provide more details.
Link to db diagram: http://imgur.com/YZ0SuVw
The first dropdown draws from the profession table, the second from the specialties table. What I'd like to do is to display all of the rows in the jobs table that match the specialty selected in the dropdown box. This will require the result from the variable (result) from the dropdown to be converted into the spec_code that is in the job table. Not sure exactly how to do this. Thanks!
I just want to outline some points about following block of code:
where did you defined myval
data: {'result': myval}: result not require any quota change it to data: {result: myval}
why you need to get HTML from selected options? it's better to send option values the change
$("select#type option:selected").html();
to
$("select#type option:selected").val();
if(cat>0 && type>0)
{
var result = $("select#type option:selected").html();
$("#result").html('your choice: '+result);
$.ajax({
type: 'POST',
url: 'display.php',
data: {'result': myval},
});
}

Categories