I am using PHP, MySql, jQuery.
I have a html table. I want to get the contents of the html table, and store it in mysql db.
I have taken the contents of the html table in an array using jquery.
This is my jquery code.
var myTableArray = [];
$("#my_tbe tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
So 'myTableArray' will gives me the id, name, code.
1,sam,z123
2,kim,z234
Here is my MySql Table.
---------------------
id | name | code
---------------------
3 | sample1 | kkk
4 | sample2 | iii
---------------------
i am getting values in jquery through .text(). How do i insert these values into my DB.
Thanks.
First of all, you need to send request via Aajx.
var request = $.ajax({
url: "insert.php", // Action file
type: "POST", // POST method
data: { data : myTableArray }, // Your data
});
In insert.php you will get something like this:
$_POST["data"] = array(
array(1, "sam", "z123"),
array(2, "kim", "z234")
);
Mysql insert sytnax looks like:
INSERT INTO table (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
You need to loop through your data and fill your data into syntax above.
$values = array();
foreach($_POST["data"] as $insert){
$values[] = "({$insert[0]}, '{$insert[1]}', '{$insert[2]}')";
}
{$insert[0]} is missing quotes, beacue is integer. You can use NULL instead if is autoincrement.
Your values are ready, now put them into query:
$query = "INSERT INTO table (id, name, code) VALUES".implode(',', $values).";";
You are ready to execute query string!
I preffer use prepared statements like following solution:
$values = array();
$data = array();
foreach($_POST["data"] as $insert){
$values[] = "(?, ?, ?)";
$data = array_merge($data, $insert);
}
Now $data contains all your data.
Related
So I am trying to send the "id" of a selected row in datatable in javascript to a php page so I could delete it from database.
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0] });
the variable "ids" is sent by post method
$.post( "deleterow.php", { v1: ids });
but it didn't worked so i try to see the response from post method and it says
"notice array to string conversion in C on line ... "
the line is of php page where i am writing the delete query
$id = $_POST["v1"];
$query = "DELETE FROM `package` WHERE `id` = '$id'";
The whole php page works fine when trying with other values.
Because you send an array here:
$.post( "deleterow.php", { v1: ids });
so v1 contains an array of elements. But in your php code you treat it as a single element:
$id = $_POST["v1"];
Hence the notice array to string conversion.
If you send an array of elements, you have to get it as an array and treat is as an array. To create a correct SQL string you should append each ID, like this:
$ids = json_decode($_POST["v1"]);
$query = "DELETE FROM `package` WHERE";
$first = true;
foreach ($ids as $id) {
if ($first) {
$first = false;
} else {
$query += " OR";
}
$query += " `id` = '$id'"
}
This way you loop the array and append a id = ID for each array element.
Now, this is important, this code is prone to SQL injection, a really bad security problem. Read this to get more info about this: How can I prevent SQL injection in PHP?
I have a php function that will get a list of name from column in users database. What I want to do is to get all the values from the column name and insert it into an array.
What I've done from the php side is :
header('Content-type: application/json');
include ('../Core/Initialization.php');
$courseName = $_POST['courseName'];
$semester = $_POST['semester'];
$sql = mysql_query("SELECT DISTINCT `name` FROM `users` WHERE `programme` = '$courseName' AND `semester` = '$semester'") or trigger_error(mysql_error().$sql);
$column = mysql_fetch_assoc($sql);
$arr = array();
foreach($column as $value) {
$arr[] = array('name' => $value['name']); //I have tried it this way but it didn't work when I try to display the values.
}
echo json_encode($arr);//I have tried to remove the array and just json_encode($column). I have successfully print out the first values, but fail to print out the next values collected from the column.
The js function that will process/print out the name:
function nameProcess(data) {
alert(data.name); //This will only display the full values from the first(?) index
nameArray = data.name;
for (var i=0; i < nameArray.length; i++) {
alert(nameArray[i]); //But, this loop only displays one character each time of the alert. Example: Each character from the word "Hello" will show up one by one as alert.
}
}
});
Is there any better way to do this? What I want to do is, exporting all values from column name into an array, and iterate each of its value as an option of a a select box. But for now, how do I fix the problem?
First of all, don't use mysql_* functions as they are deprecated and
removed totally PHP 7.
Back to your question, you can fetch mysql multi-dimensional array with MySQL only with loop.
Corrected code:
$sql = mysql_query("SELECT DISTINCT `name` FROM `users` WHERE `programme` = '$courseName' AND `semester` = '$semester'") or trigger_error(mysql_error().$sql);
$res = mysql_query($sql); // Missing this.
$column = ;
$arr = array();
while ($value = mysql_fetch_assoc($res)) {
$arr[] = $value['name'];
}
echo json_encode($arr);
Note: The PHP MySQL commands you are using are deprecated. It's recommended to use the PDO class (as MySQLi is also deprecated).
It depends on the pre-processing you are performing, but from what I can see based on the information you provided, you are passing each element of the returned data through to nameProcess.
So a return data of
array(
array('name' => 'John Smith',
array('name' => 'Jane Doe',
array('name' => 'Foo Bar'
);
Will require the nameProcess function to be invoked 3 times.
So each time you go through to define
nameArray = data.name;
nameArray becomes a string since data.name is 'John Smith' the first invoke, 'Jane Doe' the second invoke, and 'Foo Bar' the last invoke.
So when you call
alert(nameArray[i]);
It's calling the character at position i within the string.
nameArray[0]; // 'J'
nameArray[1]; // 'o'
nameArray[2]; // 'h'
nameArray[3]; // 'n'
// etc
If you change it to:
function nameProcess(data) {
alert(data.name);
nameArray = data.name;
alert(nameArray);
}
It will alert the full name.
The way around this would be to ensure that you pass the JSON parsed data to the function without the pre-processing, in which case your original code should work if you change it to:
function nameProcess(data) {
alert(data.name);
nameArray = data.name;
for (var i=0; i < nameArray.length; i++) {
alert(nameArray[i].name);
}
}
Recently I have been trying to make an auto-complete search.
I looked up some infos and figured out that there is a way to
use PHP variables at the source... but however when I try to get a
list of the places name, I get the results into an array
$db = new OBJ_mysql($config_budapest);
$places = array();
//- getting the list of the cities
$autocomplete= $db->query("SELECT DISTINCT Helyseg FROM M_munka WHERE Publikus = '1' AND Aktiv = 1 AND Jovahagyott = 1");
$autocomp_q= $autocomplete->fetchAllArray();
$writeauto = json_encode($autocomp_q); /* ECHO ALL THE RESULTS */
//array push
array_push($places,$autocomp_q);
<script type="text/javascript">
$(function() {
var availableClients = [<?php echo json_encode($places);?> ];
$("#tags").autocomplete({
source: availableClients,
});
});
</script>
Result:
Updated Result:
As far as I can see in your code, $places is an array of your query result. It seems you are creating an array of arrays (array with other arrays inside it)
Did you try to assign the query result to $places, something like this:
$db = new OBJ_mysql($config_budapest);
//- getting the list of the cities
$autocomplete= $db->query("SELECT DISTINCT Helyseg FROM M_munka WHERE Publikus = '1' AND Aktiv = 1 AND Jovahagyott = 1");
$autocomp_q= $autocomplete->fetchAllArray();
$writeauto = json_encode($autocomp_q); /* ECHO ALL THE RESULTS */
$places = $autocomp_q;
Hope it helps!
this is the code i have, actually i am inserting a array in json encode data and getting back via jquery.
$list_type_query = "select * from assettype";
//the asset type table contains (id & type) column
$query = mysqli_query($conn, $list_type_query);
while($r = mysqli_fetch_array($query)){
$result_value = array("Status" => "haslist", "list" => $r);
}
this is jquery side.
case "loaddefaultmodel":
var showtype = $('#sh');
var showvalue = '<span>'+data['list']+'</span>';
showtype.html(showvalue);
break;
$('#sh') is a div i need to show all type content in the span inside the div.
if i use the data['list'][0]['type'] i getting a object 0 value.
how to show all value one by one dynamically in div.
I think the issue in your php code.
Because in every loop, the $r just get every current index data, And $result_value just get current index data.
You can try this...
$list_type_query = "select * from assettype";
//the asset type table contains (id & type) column
$query = mysqli_query($conn, $list_type_query);
$all_data = array();
while($r = mysqli_fetch_array($query)){
$all_data[] = $r;
}
$result_value = array("Status" => "haslist", "list" => $all_data);
I have 3 dropdowns with list of places that I wanted to sort in ascending order. The first dropdown of places is sorted using codeigniter active record order_by function and the places were successfully sorted in ascending order.However,using onchange javascript function,when I choose a place in the first dropdown then populate the second dropdown of places excluding the place I have chosen in the first dropdown, the places returned were not sorted in ascending order even though there is order_by function I have in my query. I suspect that this is because of the json formatted data returned in onchange. Here are my codes. Thanks for the help.
This code sorts the data properly in ascending order
function get_dropdown_barangay(){
$query = $this->db->select('ID,brgy_name')
->from('tbl_barangay')
->order_by('brgy_name','asc')
->get()
->result_array();
$dropdown = array('0'=>'Select Barangay');
foreach($query as $value){
$dropdown[$value['ID']] = $value['brgy_name'];
}
return $dropdown;
}
Output Image:
Onchange code, the returned places are not sorted in ascending order
$('#brgy_id_1').change(function(){
var brgy_id = $("#brgy_id_1").val();
alert(brgy_id);
var data_val = {'brgy_id':brgy_id};
$.ajax({
type: "POST",
url:"<?php echo base_url();?>admin/get_barangay_list",
data:data_val,
dataType:'json',
success: function(data)
{
$('#brgy_id_2').empty();
$.each(data,function(id,val)
{
var opt = $('<option />'); // here we're creating a new select option for each group
opt.val(id);
opt.text(val);
$('#brgy_id_2').append(opt);
});
}
});
}); //end change
admin.php
function get_barangay_list(){
if(isset($_POST['brgy_id2'])){
$brgy_array_id = array('0'=>$_POST['brgy_id'],'1'=>$_POST['brgy_id2']);
} else{
$brgy_array_id = array('0'=>$_POST['brgy_id']);
}
$result=$this->core_model->get_barangay_list($brgy_array_id);
$this->output->set_header('Content-Type: application/json',true);
echo json_encode($result);
}
model.php
function get_barangay_list($brgy_array_id){
$query = $this->db->select('ID,brgy_name')
->from('tbl_barangay')
->where_not_in('ID',$brgy_array_id)
->order_by('brgy_name','asc')
->get()
->result_array();
$dropdown = array('0'=>'Select Barangay');
foreach($query as $value){
$dropdown[$value['ID']] = $value['brgy_name'];
}
return $dropdown;
}
Output Image showing data are not sorted in ascending order
One way to implement kinghfb's comment :
On the server side : build an array
$dropdown = array();
$dropdown[] = array('id' => 0, 'label' => 'Select city');
for ($query as $value) {
$dropdown[] = array('id' => $value['ID'], 'label' => $value['brgy_name']);
}
On the client side (javascript) : change your loop code :
$.each(data,function(id,val) {
var opt = $('<option />'); // here we're creating a new select option for each group
opt.val(val.id);
opt.text(val.label);
$('#brgy_id_2').append(opt);
});
You are losing your order here, because you are setting new keys (problem is described here Change array key without changing order).
So you have to keep the keys and due this you have to change the js part as well, because you can´t access the data using key-value anymore.
function get_dropdown_barangay(){
$query = $this->db->select('ID,brgy_name')
->from('tbl_barangay')
->order_by('brgy_name','asc')
->get()
->result_array();
$dropdown = array('0'=>'Select Barangay');
foreach($query as $value){
$dropdown[] = array("id" => $value["ID"], "name" => $value['brgy_name']); // setting new value and keep an numeric key which represents the order
}
return $dropdown;
}
and the js has to be like:
$('#brgy_id_1').change(function(){
var brgy_id = $("#brgy_id_1").val();
alert(brgy_id);
var data_val = {'brgy_id':brgy_id};
$.ajax({
type: "POST",
url:"<?php echo base_url();?>admin/get_barangay_list",
data:data_val,
dataType:'json',
success: function(data)
{
$('#brgy_id_2').empty();
$.each(data,function(object)
{
var opt = $('<option />'); // here we're creating a new select option for each group
opt.val(object.id);
opt.text(object.value);
$('#brgy_id_2').append(opt);
});
}
});
});
I had highlighted the changes, but I don´t know hot to use bold in code at SO....
You could sort your JSON using underscore
Just pass in your JSON and a sort function. Like so:
var cityJSON = [{city: 'San Vinente'}, {city: 'Pequnio'}, {city: 'Pili Drive'}, {city: 'Jc Aquino'}, {city: 'Banza'}];
console.log(cityJSON); // unsorted
cityJSON = _.sortBy(cityJSON, function(item){return item.city});
console.log(cityJSON); // sorted