Reading a Textarea with jquery , splitting each line in Array then with ajax posting that array in mysql through php but in results only first value inserted.
Table:
CREATE TABLE IF NOT EXISTS addresses (
id int(8) NOT NULL PRIMARY KEY,
user_id int(8) DEFAULT NULL,
address_value varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Here is Jquery Code :
$('#insertad').click(function(){
var lines = $('#txtArea').val().split('\n');
var phparray = new Object();
for(var i = 0;i < lines.length;i++){
phparray[i] = lines[i]; //store value in object
}
$.post('functions.php?action=insertad', {array1:$.param(phparray)}, function(resp){
$('.text-success').html(resp);
if(resp == 'Added'){
$('.text-success').html('Added Address :');
}
});
});
Here is PHP Code :
if ($action == 'insertad') {
$pieces = explode('&', $_POST['array1']); //explode passed serialized object
$phparray = array();
foreach ($pieces as $piece) {
list($key, $value) = explode('=', $piece);
$phparray[$key] = $value; //make php array
}
$length = count($phparray);
for ($i = 0; $i < 7; $i++) {
$sql = "select address_value from addresses where address_value = '$phparray[$i]'";
$qry = mysql_query($sql);
$numrows = mysql_num_rows($qry);
if ($numrows > 0) {
echo "One Found !!" ;
} else {
$sql = "insert into addresses (address_value) values ('$phparray[$i]')";
$qry = mysql_query($sql);
if ($qry) {
echo "Added";
}
}
}
}
Try this please...
JS:
var $textarea = $('textarea'); // maybe you have to specific your selector!
var textArray = $textarea.val().split("\n"); // this array is already done, your have not todo next for() loop
$.post('functions.php', {
action: 'insertad',
array1: textArray
}, function(results) {
$.each(results, function(reslt) {
if(result === 'Added') {
$('.status').append(result);
}
else {
$('.status').append(result);
}
});
});
PHP:
if($action === 'insertad') {
$results = [];
$input = $_POST['array1'];
foreach($input AS $textLine) {
$escapedTextLine = mysqli_real_escape_string($resource, $textLine);
$result = mysqli_query($resource, 'select address_value from addresses where address_value = "'.$escapedTextLine.'"');
$affectedRows = mysqli_num_rows($result);
if($affectedRows > 0) {
$results[] = 'One Found !!';
}
else {
$result = mysqli_query($resource, 'INSERT INTO `adresses` (`address_value`) VALUES("'.$escapedTextLine .'");
if($result) {
results[] = 'Added!';
}
}
}
return $results; // we return all done results to check this array in ajax response
}
Notice: I wrote the code blind, so maybe you have to make some small changes for e.g. your variables or something like that.
Notice 2: I write the code with mysqli, so you have to rewrite your Database connection setup code.
Please never forget to use mysqli_real_escape_string do something with user contents.
Related
I have a php which will include my datas inside my database.
But in my page I have a div which can be replicated, so I send this informations into an array (imploded with a "#!#" to avoid any kind of wrong explode when I insert it on my database).
My problem is that if the user doesn't insert anything on the first div content fields I shall not do the insert, and it still does.
if ($_GET['action_ent'] != "#!##!##!#")
{
$myInputs = $_GET['action_ent'];
foreach ($myInputs as $eachInput)
{
$valores = $eachInput;
print_r($valores);
$dummy = explode('#!#', $valores);
$acao = $dummy[0];
$resp_acao = $dummy[1];
$inic_plan_acao = $dummy[2];
$fim_plan_acao = $dummy[3];
$inicio_acc = explode("/", $inic_plan_acao);
$fim_acc = explode("/", $fim_plan_acao);
$inicio_action = $inicio_acc[2]."-".$inicio_acc[1]."-".$inicio_acc[0];
$fim_action = $fim_acc[2]."-".$fim_acc[1]."-".$fim_acc[0];
$result2 = mysql_query("INSERT INTO `demv3`.`entraves_action` (`action_id`, `ent_id`, `resp_ent`, `data_fim`,`action_desc`,`action_resp`,`action_comeco`,`action_fim`) VALUES ('0', '$ent_id', '$resp_ent', '$data_fim', '$acao', '$resp_acao', '$inicio_action', '$fim_action')");
}
}
else
{
echo "NOTHING";
}
Try checking the first item in the foreach:
if ($_GET['action_ent'] != "#!##!##!#")
{
$myInputs = $_GET['action_ent'];
foreach ($myInputs as $eachInput)
{
if(empty($eachInput)) {
echo 'NOTHING';
break;
}
$valores = $eachInput;
print_r($valores);
$dummy = explode('#!#', $valores);
$acao = $dummy[0];
$resp_acao = $dummy[1];
$inic_plan_acao = $dummy[2];
$fim_plan_acao = $dummy[3];
$inicio_acc = explode("/", $inic_plan_acao);
$fim_acc = explode("/", $fim_plan_acao);
$inicio_action = $inicio_acc[2]."-".$inicio_acc[1]."-".$inicio_acc[0];
$fim_action = $fim_acc[2]."-".$fim_acc[1]."-".$fim_acc[0];
$result2 = mysql_query("INSERT INTO `demv3`.`entraves_action` (`action_id`, `ent_id`, `resp_ent`, `data_fim`,`action_desc`,`action_resp`,`action_comeco`,`action_fim`) VALUES ('0', '$ent_id', '$resp_ent', '$data_fim', '$acao', '$resp_acao', '$inicio_action', '$fim_action')");
}
}
else
{
echo "NOTHING";
}
Just be aware that if any other input besides the first one is empty it will break the loop. In order to avoid major changes in your logic you can resolve this with a counter or a boolean flag:
if(empty($eachInput) && $counter == 0) {
echo 'NOTHING';
break;
}
i used an exsiting code from a tutorial and need to change it.
The original code doesnt use an array, but i need it.
In my index.php i am calling the function with a tag:
else if ($tag == 'getinvbykost') {
$kstalt = $_POST['kstalt'];
$get = $db->GetInvByKost($kstalt);
if ($get != false) {
// echo json with success = 1
$response["success"] = 1;
$response["ean"] = $get["ean"];
$response["name"] = $get["name"];
$response["betriebsdatenalt"] = $get["betriebsdatenalt"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "nicht erfolgreich";
echo json_encode($response);
}
}
the function GetInvByKost($kstalt); is defined in DB_Functions.php.
the part is:
public function GetInvByKost($kstalt) {
$result = mysql_query("SELECT ean, name, betriebsdatenalt FROM geraete WHERE kstalt='$kstalt' AND accepted='0'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
while ($result = mysql_fetch_assoc($result)){
}
return $result;
//echo $result[1];
}
else {
// user not found;
return false;
}
}
the problem is, the function GetInvByKost returns an array.
the part in the index.php
$response["success"] = 1;
$response["ean"] = $get["ean"];
$response["name"] = $get["name"];
$response["betriebsdatenalt"] = $get["betriebsdatenalt"];
isnt made for an array, only for a single line.
how do i can get the values in the array to build my output?
mysql_fetch_assoc($result) returns a flat array. This means you can't access returned array by a key. So $get["ean"] is wrong and $get[1] is correct. You can access result of mysql_fetch_assoc($result) only by index, not key. You have SELECT ean, name, betriebsdatenalt... in your query, so index of "ean" is equal to 0, "name" is equal to 1 and so on. Therefore, 3 parts of your code should be change in this way:
`$get["ean"]` => ` $get[0]`
`$get["name"]` => `$get[1]`
`$get["betriebsdatenalt"]` => `$get[2]`
Update:
So, the index.php file should be like this:
else if ($tag == 'getinvbykost') {
$response = array();
$kstalt = $_POST['kstalt'];
$get = $db->GetInvByKost($kstalt);
if ($get != false) {
// echo json with success = 1
$response["success"] = 1;
$response["ean"] = $get[0];
$response["name"] = $get[1];
$response["betriebsdatenalt"] = $get[2];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "nicht erfolgreich";
echo json_encode($response);
}
}
I have a small code make this result :
{"nomdupharmacie":[{"pid":"71","name":"dft","longi":"9.010505676269531","lati":"34.1575970207261","matricule":"M65203124"},{"pid":"72","name":"erezrzer","longi":"7.529407627880573","lati":"34.63767601827405","matricule":"123"},{"pid":"73","name":"qsd","longi":"8.83832462131977","lati":"35.172592315800905","matricule":"333"}],"success":1}
with this php code :
// get all products from products table
$result = mysql_query("SELECT *FROM nomdupharmacie") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["nomdupharmacie"] = array();
$v = "12";
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["pid"] = $row["pid"];
$product["name"] = $row["name"];
$product["longi"] = $row["longitude"];
$product["lati"] = $row["latitude"];
$product["matricule"] = $row["personnel_number"];
// push single product into final response array
array_push($response["nomdupharmacie"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
i have to test for example :
$value = "555"
if $value exists in column of matricule so get alert
so the questionis how to make test if the value exists in the Matricule column or not ??
You should look into using PDO or ADOdb instead of mysql_query which is deprecated.
The only option is to compare manually like this:
1) create a function that receives an array x and value v to check
function isMatriculeInArray($x, $v)
{
foreach($x as $z)
{
if($z["matricule"] == $v)
{
return true;
}
}
return false;
}
2) check if matricule is in there
if(!isMatriculeInArray($response["nomdupharmacie"], $v)
{
array_push($response["nomdupharmacie"], $product);
}
I have a php file that i connect to it with ajax and callback value is JSON
when i get data from php it dosnt show and when alert data i see Object
Where is my problem ?
PHP:
if(isset($_SERVER["HTTP_X_REQUESTED_WITH"])){
$query = mysql_query("select * from tab");
for ($i=0;$i<mysql_num_rows($query);$i++){
while($row = mysql_fetch_assoc($query)){
$title['t'][i] = $row['title'];
$title['d'][i] = $row['description'];
}
}
echo(json_encode($title));
exit();
?>
JS:
$('#button').click(function(){
$.ajax({
url : "test2.php",
data : $("#tab"),
type : "GET",
success : function(b){
b = eval('('+ b +')');
console.log((b['t']));
alert(b);
}
});
});
How can i get all of data from this JSON and show me corect it ?
Here's a full working example with single row fetch and multi row fetch, without using mysql_ syntax and using prepared statements to prevent sql injections.
And yes, DON'T use mysql specific syntax, like I mentioned here: I cant get the form data to go into database. What am I doing wrong?
function example()
{
var select = true;
var url = '../scripts/ajax.php';
$.ajax(
{
// Post select to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'select' : select // the variable you're posting.
},
success : function(data)
{
// This happens AFTER the PHP has returned an JSON array,
// as explained below.
var result1, result2, message;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
result1 = data[i].result1;
result2 = data[i].result2;
message = data[i].message;
// Do something with result and result2, or message.
// For example:
$('#content').html(result1);
// Or just alert / log the data.
alert(result1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
}
Now we need to receive the posted variable in ajax.php:
$select = isset($_POST['select']) ? $_POST['select'] : false;
The ternary operator lets $select's value become false if It's not set.
Make sure you got access to your database here:
$db = $GLOBALS['db']; // An example of a PDO database connection
Now, check if $select is requested (true) and then perform some database requests, and return them with JSON:
if($select)
{
// Fetch data from the database.
// Return the data with a JSON array (see below).
}
else
{
$json[] = array
(
'message' => 'Not Requested'
);
}
echo json_encode($json);
flush();
How you fetch the data from the database is of course optional, you can use JSON to fetch a single row from the database or you can use it return multiple rows.
Let me give you an example of how you can return multiple rows with json (which you will iterate through in the javascript (the data)):
function selectMultipleRows($db, $query)
{
$array = array();
$stmt = $db->prepare($query);
$stmt->execute();
if($result = $stmt->fetchAll(PDO::FETCH_ASSOC))
{
foreach($result as $res)
{
foreach($res as $key=>$val)
{
$temp[$key] = utf8_encode($val);
}
array_push($array, $temp);
}
return $array;
}
return false;
}
Then you can do something like this:
if($select)
{
$array = array();
$i = 0;
$query = 'SELECT e.result1, e.result2 FROM exampleTable e ORDER BY e.id ASC;';
foreach(selectMultipleRows($db, $query) as $row)
{
$array[$i]["result1"] = $row['result1'];
$array[$i]["result2"] = $row['result2'];
$i++;
}
if(!(empty($array))) // If something was fetched
{
while(list($key, $value) = each($array))
{
$json[] = array
(
'result1' => $value["result1"],
'result2' => $value["result2"],
'message' => 'success'
);
}
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
Or, if you want to KISS (Keep it simple stupid):
Init a basic function which select some values from the database and returns a single row:
function getSingleRow($db, $query)
{
$stmt = $db->prepare($query);
$stmt->execute();
// $stmt->execute(array(":id"=>$someValue)); another approach to execute.
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
$array = (
'result1' => $result['result1'],
'result2' => $result['result2']
);
// An array is not needed for a single value.
return $array;
}
return false;
}
And then fetch the row (or the single value) and return it with JSON:
if($select)
{
// Assume that the previously defined query exists.
$results = getSingleRow($db, $query);
if($results !== false)
{
$json[] = array
(
'result1' => $results['result1'],
'result2' => $results['result2'],
'message' => 'success'
);
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
And if you want to get the value of $("#tab") then you have to do something like $("#tab").val() or $("#tab").text().
I hope that helps.
I suggest to use either:
b = jQuery.parseJSON(data)
see more here
or
$.getJSON
instead of eval()
Problem:
I am trying to delete all sublevels of a category by using a class. Currently I can only make it delete two sublevels, not three.
The database table:
CREATE TABLE betyg_category (
CID int(11) NOT NULL AUTO_INCREMENT,
Item varchar(100) NOT NULL,
Parent int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (CID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The PHP class:
<?php
class ItemTree
{
var $itemlist = array();
function ItemTree($query)
{
$result = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error());
while ($row = mysql_fetch_assoc($result))
{
$this->itemlist[$row['CID']] = array(
'name' => $row['Name'],
'parent' => $row['Parent']
);
}
}
function get_tree($parent, $with_parent=0)
{
$item_tree = array();
if ($with_parent == 1 && $parent != 0)
{
$item_tree[$parent]['name'] = $this->itemlist[$parent]['name'];
$item_tree[$parent]['parent'] = $this->itemlist[$parent]['parent'];
$item_tree[$parent]['child'] = $this->get_tree($parent);
return $item_tree;
}
foreach ($this->itemlist as $key => $val)
{
if ($val['parent'] == $parent)
{
$item_tree[$key]['name'] = $val['name'];
$item_tree[$key]['parent'] = $val['parent'];
$item_tree[$key]['child'] = $this->get_tree($key);
}
}
return $item_tree;
}
function make_optionlist ($id, $class='', $delimiter='/')
{
$option_list = '';
$item_tree = $this->get_tree(0);
$options = $this->make_options($item_tree, '', $delimiter);
if (!is_array($id))
{
$id = array($id);
}
foreach($options as $row)
{
list($index, $text) = $row;
$selected = in_array($index, $id) ? ' selected="selected"' : '';
$option_list .= "<option value=\"$index\" class=\"$class\"$selected>$text</option>\n";
}
return $option_list;
}
function make_options ($item_tree, $before, $delimiter='/')
{
$before .= empty($before) ? '' : $delimiter;
$options = array();
foreach ($item_tree as $key => $val)
{
$options[] = array($key, '- '.$before.$val['name']);
if (!empty($val['child'])) {
$options = array_merge($options, $this->make_options($val['child'], $before.$val['name'], $delimiter));
}
}
return $options;
}
function get_navlinks ($navid, $tpl, $startlink='', $delimiter=' ยป ')
{
// $tpl typ: {name}
$search = array('{id}', '{name}');
$navlink = array();
while (isset($this->itemlist[$navid]))
{
$replace = array($navid, $this->itemlist[$navid]['name']);
$navlink[] = str_replace($search, $replace, $tpl);
$navid = $this->itemlist[$navid]['parent'];
}
if (!empty($startlink))
{
$navlink[] = str_replace($search, array(0, $startlink), $tpl);
}
$navlink = array_reverse($navlink);
return implode($delimiter, $navlink);
}
function show_tree ($parent=0, $tpl='%s', $ul_class='', $li_class='')
{
$item_tree = $this->get_tree($parent);
return $this->get_node($item_tree, $parent, $tpl, $ul_class, $li_class);
}
function get_node ($item_tree, $parent, $tpl, $ul_class, $li_class)
{
// $tpl typ: {name}
$search = array('{id}', '{name}');
$output = "\n<ul class=\"$ul_class\">\n";
foreach ($item_tree as $id => $item)
{
$replace = array($id, $item['name']);
$output .= "<li class=\"$li_class\">".str_replace($search, $replace, $tpl);
$output .= !empty($item['child']) ? "<br />".$this->get_node ($item['child'], $id, $tpl, $ul_class, $li_class) : '';
$output .= "</li>\n";
}
return $output . "</ul>\n";
}
function get_id_in_node ($id)
{
$id_list = array($id);
if (isset($this->itemlist[$id]))
{
foreach ($this->itemlist as $key => $row)
{
if ($row['parent'] == $id)
{
if (!empty($row['child']))
{
$id_list = array_merge($id_list, get_id_in_node($key));
} else
{
$id_list[] = $key;
}
}
}
}
return $id_list;
}
function get_parent ($id)
{
return isset($this->itemlist[$id]) ? $this->itemlist[$id]['parent'] : false;
}
function get_item_name ($id)
{
return isset($this->itemlist[$id]) ? $this->itemlist[$id]['name'] : false;
}
}
?>
Scenario:
Say you have the following structure in a :
Literature
-- Integration of sources
---- Test 1
It will result in the following in the database table:
When I try to delete this sublevel, it will leave the last sublevel in the database while it should delete it. The result will be:
The PHP code:
//Check if delete button is set
if (isset($_POST['submit-deletecategory']))
{
//Get $_POST variables for category id
$CategoryParent = intval($_POST['CategoryList']);
//Check if category is selected
if ($CategoryParent != "#")
{
//Get parent category and subsequent child categories
$query = "SELECT CID, Item AS Name, Parent FROM " . TB_CATEGORY . " ORDER BY Name";
$items = new ItemTree($query);
if ($items->get_item_name($_POST['CategoryList']) !== false)
{
//Build up erase list
$CategoryErase = $items->get_id_in_node($CategoryParent);
$CategoryEraseList = implode(", ", $CategoryErase);
}
else
{
$CategoryEraseList = 0;
}
//Remove categories from database
$query = "DELETE FROM " . TB_CATEGORY . " WHERE CID IN ($CategoryEraseList)";
$result = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error());
//Return a confirmation notice
header("Location: settings.php");
exit;
}
}
Thank you in advance for any guidance I can get to solve the issue.
Here is a way to do it : use a recursive function, which will first look for the leaf item (the deepest in your tree). You remove children first, then the parent. And for each child, you remove child's children first, etc...
deleteSub(1);
function deleteSub($cat_id) {
$request = "SELECT * FROM ". TB_CATEGORY ." WHERE Parent = ".$cat_id;
$results = mysql_query($request);
while($child = mysql_fetch_array($results))
{
deleteSub($child["CID"]);
}
$request = "DELETE FROM ". TB_CATEGORY ." WHERE CID = ".$cat_id;
return mysql_query($request);
}
A better way could be use this kind of recursive function to store CIDs in an array, then make a single DELETE request, but I think you'll be able to adapt this code.
I'm not going to read or try to understand the entire code, but it seems to me you need some sort of recursion function. What I basicly would do is create a function that goes up in the hierachy and one that goes down.
Note: It has been a while since i've written anything in procedural mysql, so please check if the mysql_num_rows(),mysql_fetch_array and so on is written in the correct manner
EDIT: I've just noticed you only wanted a downwards deletion and therefore zessx's answer is more valid
<?php
function recursiveParent($id) {
$sql = 'SELECT parent FROM betyg_category WHERE CID=' . $id;
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
while($r = mysql_fetch_array($result,MYSQLI_ASSOC)) {
recursiveParent($r['parent']);
}
}
$sql = 'DELETE FROM betyg_category WHERE CID=' . $id;
mysql_query($sql);
}
function recursiveChild($parent) {
$sql = 'SELECT CID FROM betyg_category WHERE parent=' . $parent;
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
while($r = mysql_fetch_array($result,MYSQLI_ASSOC)) {
recursiveChild($r['CID']);
}
}
$sql = 'DELETE FROM betyg_category WHERE parent=' . $parent;
mysql_query($sql);
}
function delete($id) {
recursiveParent($id);
recursiveChild($id);
}
?>
This is my way to do. instead of recursive the query to run, i get all the child's id first then only run query. here the code refer:-
First, defined a variable called $delete_node_list as array. (to store all node id that need to be delete)
function delete_child_nodes($node_id)
{
$childs_node = $this->edirectory_model->get_child_nodes($node_id);
if(!empty($childs_node))
{
foreach($childs_node as $node)
{
$this->delete_child_nodes($node['id']);
}
}
$this->delete_node_list[] = $node_id;
}
in mysql..
$sql = 'DELETE FROM betyg_category WHERE CID IN '.$this->delete_node_list;
mysql_query($sql);