I am trying to put together a function that does the following:
retrieve a JSON encoded string from a form
decode the string to a php array
loop through the generated php array to get the values for each part of the array so that I can update a MySql table
Here is my function code so far:
public function saveTestimonials() {
$existing_testimonials_update = $this->post('data');
$update_array = json_decode($existing_testimonials_update);
foreach ($update_array as $key => $testimonials) {
foreach($testimonials as $key => $value) {
//echo "$key = $value\n";
}
}
$db = Loader::db();
$sql = "UPDATE testimonials SET name=var, content=var WHERE id=var";
$db->query($sql);
$this->redirect('/dashboard/testimonials/');
}
Here is the array stored in the $update_array variable:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Mr. John Doe, Manager, ABC Ltd
[content] => my content 1.
)
[1] => stdClass Object
(
[id] => 2
[name] => Mr. Joe Smith, Manager, ABC Industries
[content] => my content 2.
)
[2] => stdClass Object
(
[id] => 3
[name] => Mr. Mike Smith, Manager, ABC Industries
[content] => my content 3.
)
[3] => stdClass Object
(
[id] => 4
[name] => Ms. Jane Doe, Manager, ABCD Ltd
[content] => my content 4.
)
)
I have got steps 1 and 2 working fine, however I am stuck on step 3.
I still learning PHP and struggle with syntax at times.
I have tried to work this one out on my own and have spent several hours on it, but just can't seem to figure this one out.
Any assistance is very much appreciated.
foreach ($update_array as $key => $testimonials) {
$name = mysql_real_escape_string($testimonials->name);
$content = mysql_real_escape_string($testimonials->content);
$id = intval($testimonials->id);
$sql = "UPDATE testimonials SET name='$name', content='$content' WHERE id=$id";
$result = mysql_query($sql);
if ($result === FALSE) {
die(mysql_error());
}
}
I'm using something like this. Might be a help to you!
function updateDbRecord($db, $table, $carry, $carryUrl) {
mysql_select_db($db) or die("Could not select database. " . mysql_error());
$resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
$fieldnames=array();
if (mysql_num_rows($resultInsert) > 0) {
while ($row = mysql_fetch_array($resultInsert)) {
$fieldnames[] = $row['Field'];
$array = array_intersect_key( $_POST, array_flip($fieldnames) );
}
}
foreach ($array as $key => $value) {
$value = mysql_real_escape_string($value);
$value = "'$value'";
$updates[] = "$key = $value";
}
$implodeArray = implode(', ', $updates);
$sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $implodeArray, $_POST['id']);
mysql_query($sql);
if ($carry == 'yes') {
redirect($carryUrl.'?id='.$_REQUEST['id'].'&'.$table);
} else { echo "Done!"; }
}
These are objects you're dealing with inside of the update_array, so you should be able to access them like this:
$update_array = json_decode($existing_testimonials_update);
foreach ($update_array as $key => $testimonials) {
$testimonials = (array) $testimonials;
foreach($testimonials as $key => $value) {
//echo "$key = $value\n";
}
}
Or, more simply, you can use the arrow operator ($testimonials->name) to access the variables.
You are getting an object from json_decode(). If you pass true as second argument to json_decode() you get an associative array.
http://php.net/manual/de/function.json-decode.php
try something like this
$db = Loader::db();
foreach ($update_array as $key => $testimonials) {
foreach($testimonials as $testimonial) {
// escape data to avoid sql injection
$id = mysql_escape_string($testimonial->id);
$name = mysql_escape_string($testimonial->name);
$content = mysql_escape_string($testimonial->content);
$sql = "UPDATE testimonials SET name='$name', content='$content' WHERE id='$id'";
$db->query($sql);
// TODO check for database error here
}
}
function update($table_name, $myarray, $my_wheres) {
$sql = "Update`".$table_name.
"` SET ";
$i = 0;
foreach($myarray as $key => $value) {
$sql.= $key." = '".$value."'";
if ($i < count($myarray) - 1) {
$sql.= " , ";
}
$i++;
}
if (count($my_wheres) > 0) {
$sql.= " WHERE ";
$i = 0;
foreach($my_wheres as $key => $value) {
$sql.= $key.
" = ".$value;
if ($i < count($my_wheres) - 1) {
$sql.= " AND ";
}
$i++;
}
}
return mysqli_query($sql);
}
Hope, this code can help you. Not try one by one update i think. Think performance.
Related
I have a multidimensional array composed of strings of various length as follow:
$a =
Array ( [0]
Array ( [0] AQWER, [1] CFG, [2] JUHTYREWQ, [3] K, [4] LO ),
Array [1]
Array ( [0] VFG, [1] yhtredw, [2] koeutydjwiq, [3] bg, [4] hytefs, [5] M),
Array [2]
Array ( [0] BHTWQ, [1] BH, [2] NJUy))
Equally, I have a mySQL table containing the following values
myTable
AQWER
CFG
JUHTYREWQ_K_LO
VFG
yhtredw
bg_hytefs
BHTWQ
BH_ NJUy
Desired outcome
I am trying to test and reformulate the array based on matches in the SQL table so that it looks like this:
$a =
Array ( [0]
Array ( [0] AQWER, [1] CFG, [2] JUHTYREWQ_K_LO ),
Array [1]
Array ( [0] VFG, [1] yhtredw, [2] koeutydjwiq, [3] bg_hytefs, [5] M),
Array [2]
Array ( [0] BHTWQ, [1] BH_NJUy))
And to still show values that have not been found (e.g. koeutydjwiq)
What I have tried so far:
I received great help in helping me manipulate $a so as to be able to test 1 string, 2 strings and 3 strings combinations.
However my code does not successfully pick up string combinations (that are definitely there in both the Array and the Table) and as a result, does not reformat the original array $a and I can't quite figure out why.
In fact more specifically, when calling the print_r($para) in the IF statements, I get .........
Here is my code:
foreach ($a as $val) {
for ($i=0; $i<count($val); $i++) {
// A_B_C
if (isset($val[$i+2])) {
$exagon = array();
$exagon = $val[$i] . '_' . $val[$i+1] . '_' . $val[$i+2];
$conn = mysqli_connect("localhost:8889","root","root","myDB");
$query = "SELECT * FROM `myTable` WHERE LIST = '".$exagon."'";
$para = array(
);
$result = mysqli_query($conn, $query);
//echo $result;
while($row = mysqli_fetch_array($result)) {
$para[] = array($row['LIST']);
}
if (isset($para) && !empty($para)) {
print_r($para);
array_splice($a, $i, $i+2, $para);
$i=$i+2;
}
else {
unset($para);
unset($exagon);
}
}
// A_B
elseif (isset($val[$i+1])) {
$exagon = array();
$exagon = $val[$i] . '_' . $val[$i+1];
$conn = mysqli_connect("localhost:8889","root","root","myDB");
$query = "SELECT * FROM `myTable` WHERE LIST = '".$exagon."'";
$para = array(
);
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)) {
$para[] = array($row['LIST']);
}
if (isset($para) && !empty($para)) {
print_r($para);
array_splice($a, $i, $i+1, $para);
$i=$i+1;
}
else {
unset($para);
}
}
// A
else {
echo $val[$i];
}
}
}
Admittedly, through research, I have found posts and manuals to guide me on using array_splice and calling out variables in a SQL query but it is quite possible multiple errors are present in this code
Please use below code. theses dynamic array also it's work check with your array data it's working fine
$conn = mysqli_connect("localhost:8889","root","root","myDB");
//These will create commbination
$finalArray = array();
$sampleArray = array(array('AQWER','CFG','JUHTYREWQ','K','LO'),array('mno','xxy','kkl'));
foreach($sampleArray as $key=>$val){
$combincationArr = array();
foreach($val as $k1=>$v1){
$combincationArr[] = $v1;
$prevStr = $v1;
for ($i=($k1+1); $i<(count($val)); $i++) {
$prevStr .= '_'.$val[$i];
$combincationArr[] = $prevStr;
}
}
if(!empty($combincationArr)){
$finalArray[$key] = $combincationArr;
}
}
$destArr = array();
foreach($finalArray as $key=>$val){
if(!empty($val)){
$para = array();
$query = "SELECT * FROM `myTable` WHERE FIND_IN_SET (LIST,'". implode(',', $val)."')";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)) {
$para[] = array($row['LIST']);
}
$destArr[] = $para;
}
}
echo "<pre>";print_r($destArr);die;
At the moment, i'm creating a dynamic menu for my own CMS (practising) in PHP, but I don't know to save the data in my database.
Database structure:
menuitem_id
menu_id
menuitem_order
menuitem_name
menuitem_page_id
parent_menuitem_id
I do get this output as a hierarchical tree, but that isn't the desired format for storing it into my database:
Array
(
[0] => Array
(
[id] => 2
)
[1] => Array
(
[id] => 1
[children] => Array
(
[0] => Array
(
[id] => 3
[children] => Array
(
[0] => Array
(
[id] => 4
)
[1] => Array
(
[id] => 5
)
)
)
[1] => Array
(
[id] => 6
)
)
)
)
However, I want to convert this to a parent ID array with new fresh ID's (I will truncate the table and insert new data). Something like this:
Array
(
[0] => 0
[1] => 0
[2] => 2
[3] => 3
[4] => 3
[5] => 2
)
How can this be done?
Note: i have read this article, but I need the opposite code of it.
You need a recursive function:
function flattenHierarchicalArray($arr, $parentId = null) {
$items = array();
foreach ($arr as $item) {
$items[] = array('id' => $item['id'], 'parentId' = $parentId);
if (isset($item['children'])) $items = array_merge($items, flattenHierarchicalArray($item['children'], $item['id']));
}
return $items;
}
I think I have the solution combined with AlliterativeAlice's PHP code.
I'm using the Nestable plugin. That extension creates my hierarchical tree and sets it in a hidden field in my form (done by JavaScript). I updated this code to create new IDs by adding this code:
var nestable_update = function(e){
//added for updating old IDs
$(".dd-item").each(function(index){
$(this).data("id", index+1);
});
var list = e.length ? e : $(e.target),
output = list.data("output");
if (window.JSON) {
output.val(window.JSON.stringify(list.nestable("serialize")));
} else {
output.val("JSON browser support required for this demo.");
}
};
$(".dd").nestable({
maxDepth:5
}).on("change", nestable_update);
nestable_update($(".dd").data("output", $("#nestable_output")));
I used your PHP code for getting the parentID (many thanks to AlliterativeAlice, because it's more efficient than my original PHP code):
function flatten_hierarchical_tree($arr, $parent_id=0) {
$items = array();
foreach ($arr as $item) {
$items[] = array('id' => $item['id'], 'parent_id' => $parent_id);
if (isset($item['children'])) $items = array_merge($items, flatten_hierarchical_tree($item['children'], $item['id']));
}
return $items;
}
For those who are interested in my final code. It works for storing the data in the database and build it again into a hierarchical tree + a printable tree for HTML.
JavaScript code for the nestable plugin:
var nestable_update = function(e){
$(".dd-item").each(function(index){
$(this).data("id", index+1);
});
var list = e.length ? e : $(e.target),
output = list.data("output");
if (window.JSON) {
output.val(window.JSON.stringify(list.nestable("serialize")));
} else {
output.val("JSON browser support required for this demo.");
}
};
$(".dd").nestable({
maxDepth:5
}).on("change", nestable_update);
nestable_update($(".dd").data("output", $("#nestable_output")));
Database structure:
menuitem_id
menu_id
menuitem_order
menuitem_name
menuitem_page_id
parent_menuitem_id
PHP functions for building trees (format storing data in database + format getting data from database):
function create_flatten_hierarchical_tree($tree, $parent_id=0) {
$items = array();
foreach ($tree as $item) {
$items[] = array("id" => $item["id"], "parent_id" => $parent_id);
if (isset($item["children"])) $items = array_merge($items, create_flatten_hierarchical_tree($item["children"], $item["id"]));
}
return $items;
}
function create_hierarchical_tree($tree, $root=0) {
$return = array();
foreach($tree as $child => $parent) {
if($parent["parent_menuitem_id"] == $root) {
if(isset($tree[$child]["menuitem_id"]) === true){
$parent['children'] = create_hierarchical_tree($tree, $tree[$child]["menuitem_id"]);
}
unset($tree[$child]);
$return[] = $parent;
}
}
return empty($return) ? null : $return;
}
function print_hierarchical_tree($tree, $rows_pages) {
if(!is_null($tree) && count($tree) > 0) {
$return .= "<ol class='dd-list'>";
foreach($tree as $item){
$options = "";
foreach($rows_pages as $row_pages){
$selected = "";
if($row_pages["page_id"] == $item["menuitem_page_id"]){
$selected = "selected";
}
$options .= "<option value='".$row_pages["page_id"]."' $selected>".$row_pages["friendly_url"]."</option>";
}
$return .= "<li class='dd-item' data-id='".$item["menuitem_id"]."'><div class='dd-handle'>drag</div><div class='item_wrapper'><div class='item'><div class='item_title'>".$item["menuitem_name"]."</div></div><div class='item_sub'><div class='label_input'><label for='menuitem_name".$item["menuitem_id"]."'>Menuitem name</label><input type='text' id='menuitem_name".$item["menuitem_id"]."' name='menuitem_name[]' value='".$item["menuitem_name"]."' /></div><div class='label_input'><label for='page_link".$item["menuitem_id"]."'>Page link</label><label class='select'><select id='page_link".$item["menuitem_id"]."' name='menuitem_page_id[]'>".$options."</select></label></div> <a onClick='delete_menuitem(".$item["menuitem_id"].");' class='button red_bg delete'>Delete</a></div></div>";
$return .= print_hierarchical_tree($item["children"], $rows_pages);
$return .= "</li>";
}
$return .= "</ol>";
}
return empty($return) ? null : $return;
}
Core code of menu_edit.php page:
<?php
$stmt_menuitems = $dbh->prepare("SELECT * FROM inno_mw_thurs_menuitems mi WHERE mi.menu_id=:menu_id");
$stmt_menuitems->bindParam(":menu_id", $_GET["menu_id"]);
$stmt_menuitems->execute();
if (!empty($stmt_menuitems->rowCount())) {
?>
<div class="dd">
<?php
$result = $stmt_menuitems->fetchAll();
$tree = create_hierarchical_tree($result);
$stmt_pages = $dbh->prepare("SELECT * FROM inno_mw_thurs_pages");
$stmt_pages->execute();
$rows_pages = $stmt_pages->fetchAll();
$tree = print_hierarchical_tree($tree, $rows_pages);
echo $tree;
?>
</div>
<?php
}
Core code of menu_edit_process.php page:
if(isset($_POST["menu_id"])){
$menu_id = $_POST["menu_id"];
$nestable_output = json_decode($_POST["nestable_output"], true);
$parent_menuitem_ids_arr = create_flatten_hierarchical_tree($nestable_output);
$stmt = $dbh->prepare("TRUNCATE TABLE inno_mw_thurs_menuitems");
$stmt->execute();
$stmt = $dbh->prepare("INSERT INTO inno_mw_thurs_menuitems (menu_id, menuitem_order, menuitem_name, menuitem_page_id, parent_menuitem_id) VALUES (:menu_id, :menuitem_order, :menuitem_name, :menuitem_page_id, :parent_menuitem_id)");
$menuitem_order_arr = array();
foreach($_POST["menuitem_name"] as $f => $name){
$menuitem_name = $_POST["menuitem_name"][$f];
$menuitem_page_id = $_POST["menuitem_page_id"][$f];
$parent_menuitem_id = $parent_menuitem_ids_arr[$f]["parent_id"];
if(array_key_exists($parent_menuitem_id, $menuitem_order_arr) && $parent_menuitem_id != 0){
$menuitem_order_arr[$parent_menuitem_id] += 1;
}
else{
$menuitem_order_arr[$parent_menuitem_id] = 0;
}
$stmt->bindParam(":menu_id", $menu_id);
$stmt->bindParam(":menuitem_order", $menuitem_order_arr[$parent_menuitem_id]);
$stmt->bindParam(":menuitem_name", $menuitem_name);
$stmt->bindParam(":menuitem_page_id", $menuitem_page_id);
$stmt->bindParam(":parent_menuitem_id", $parent_menuitem_id);
$stmt->execute();
}
header("location: menus_list.php");
}
Please, feel free to improve this code.
I've an array
Array (
[0] => value1
[1] => value2
[2] => value3
[(n)] => .....)
I want this as following:
$string1 = 'value1';
$string2 = 'value2';
$string3 = 'value3';
$string(n) = '....';
Please suggest the right way to get this.
You can use PHP extract() function.
extract($var_array, EXTR_PREFIX_ALL, "string");
Demo
Does this work for what you need?
foreach($array as $key => $row) {
$var = "string" . $key;
$$var = $row;
}
But you said you need to do a query with the values. Maybe something like this?
$sql = "SELECT * FROM mytable WHERE 1 = 1";
foreach($array as $key => $row) {
$sql .= " AND string" . $key . " = '" . $row . "'";
}
I have two array like
previous:
Array(
[name] => [asdfg]
[city] => [anand]
)
current:
Array(
[name] => [ud]
[state] => [anand]
)
Now i have to compare these two array and want to alter the changed current array key or values and wrap the elements like
Array(
[name] => [<span class='bold_view'> ud </span>]
[<span class='bold_view'> state </span>] => [anand]
)
$current['name']="<span class='bold_view'> ".$current['name']." </span>";
$current['<span class='bold_view'> state </span>']=$current['state'];
I have to say that it doesn't make much sense but here it is..
Copy this code and just execute : and see the view source (Ctrl+u)
<?php
$prev = array("name"=>"[asdfg]","city"=>"[anand]");
$curent = array("name"=>"[ud]","state"=>"[anand]");
$res = array();
foreach($prev as $key=>$val){
$res[$key] = $val;
if(array_key_exists($key,$curent)){
$res[$key] = "[<span class='bold_view'> ".$curent[$key]." </span>]";
}
if($new_key = array_search($val,$curent)){
unset($res[$key]);
$res["<span class='bold_view'> ".$new_key." </span>"] = $val;
}
}
print_r($res);
?>
$arr_pre = array(
"name"=>"asdfg",
"city"=>"anand",
"address" => "anand",
);
$arr_current= array(
"name"=>"ud",
"state"=>"anand",
"address" => "ananda"
);
$result = array_diff_assoc($arr_current,$arr_pre);
$count_curr = array_count_values($arr_current);
$count_old = array_count_values($arr_pre);
foreach ($result as $key => $value){
if(!array_key_exists($key,$arr_pre ))
{
$key_new = "<b>".$key."</b>";
if(!in_array($value,$arr_pre))
{
$val = "<b>".$value."</b>";
}
else if((isset($count_curr[$value]) != isset($count_old[$value])))
{
$val = "<b>".$value."</b>";
}
else
{
$val = $value;
}
unset($arr_current_info[$key]);
}
else {
$key_new = $key;
if(!in_array($value,$arr_pre))
{
$val = "<b>".$value."</b>";
}
else if((isset($count_curr[$value]) != isset($count_old[$value])))
{
$val = "<b>".$value."</b>";
}
else
{
$val = $value;
}
}
$arr_current_info[$key_new]=$val;
}
echo "<pre>";
print_r($arr_current_info);
I have done like this and i got perfect answer
I have a database table with a column where multiple strings are stored in each field, separated by a ;
I need to get a list of all unique values in that column. I know there has to be an easier way to do this, but I can't find my answer anywhere. Here is what I'm doing so far:
$result = mysql_query("SELECT DISTINCT column FROM modx_scripture_table WHERE column!=''", $con);
$filter_all = array();
while($row = mysql_fetch_array($result))
{
$filter_all[] = $row;
}
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}
$filter_flat = array_flatten($filter_all);
function array_explode($array) {
$result = array();
foreach ($array as $key => $value) {
$result[$key] = explode(';',$value);
}
return $result;
}
$filter_sploded = array_explode($filter_flat);
$filter_full = array_flatten($filter_sploded);
$filter_final = array_unique($filter_full);
print_r($filter_final);
Everything seems to be working except the array_unique. I'm still getting duplicate strings in $filter_final. What am I doing wrong?
After exploding the string use array_unique() for fnding unique values in an array.
Example:
$arr=array('1','2','3','4','5','3','1');
print_r(array_unique($arr));
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)