I am using the below code for insert data into DB.
if (isset($_POST['file_edit_note']) && isset($_POST['file_notes']) && !empty($_POST['file_edit_note'])) {
$my_post = array();
$my_post['ID'] = $_POST['file_edit_note'];
$my_post['post_content'] = $_POST['file_notes'];
$wpdb->insert($wpdb->prefix.'posts', array(
"post_content" => $_POST['file_notes'],
"post_parent" => $_POST['file_edit_note']),array( '%s'), array('%d'));
wp_redirect(get_permalink() . '?upd=1');
}
And,here the post ID is the parent. I try to get the post id and insert into the post_parent column on the child row. This part is working.
now i tried to retrieve the data in a loop.because when I open the parent in front end all the child comes from the parent.
<?php echo !empty($file->post_content)?$file->post_content:'Content not found.'; ?>
I am new to PHP. Please give me any Suggestions.
Related
I've an existing form which is passing the input data to the model in an array format. $postdata has all the data from the view and sending to model.
Controller:
$inquiry_id = $this->input->post('inquiry_id');
$postdata = $this->input->post();
$this->load->model('Design_model');
$this->Design_model->insertdata($postdata,$inquiry_id);
Model:
function insertdata($data = array(), $inquiry_id){
$sql = $this->db->query("select * from design where inquiry_id='".$inquiry_id."'");
if($sql->num_rows() == 0){
$sql_query = $this->db->insert('design', $data);
}
else{
$this->db->where('inquiry_id', $inquiry_id);
$this->db->update('design', $data);
}
}
Above is working fine. Now, I'd like to add few fields in the view and save in a different database table. Need to exclude the new field values from $postdata array getting saved. Need to find the best approach to do this. I can start with some name for all the new fields, so that we can add any filter if available to exclude from the $postdata.
You can use elements() function from Array helper.
$array = array(
'id' => 101,
'title' => 'example',
'desc' => 'something',
'unwanted' => 'bla bla'
);
$filtered_array = elements(array('id','title','desc'),$array); //you can use this directly to the post data
$this->Design_model->insertdata($filtered_array,$inquiry_id);
You can use array_merge() or array_push() functions to add new fields to the array.
Let's say you have following data
$postdata = array("name"=>"xyz",
"email"=>"xyz#gmail.com",
"age"=>"40",
"gender"=>"Male",
"occupation"=>"Engineer"
);
Of which first 3 records are from old fields and last 2 are from new fields as you saying.
You need to find last index of first set i.e. '3' Now you can do this.
$firstDb = array_splice($postdata,0,3); //here 3 is index we are using to get first 3 records from $postdata
$secondDb = array_slice($postdata,0,3); //here 3 is index we are using to get records from position 3 from $postdata
Output:
$firstDb = array("name"=>"xyz","email"=>"xyz#gmail.com","age"=>"40");
$secondDb = array("gender"=>"Male","occupation"=>"Engineer");
Now you can insert you records as you wish to. Happy coding
How to check if a column exists in query builder Codeigniter 3?
my database table name is "tags" and this table have two column (post_id and tag) here is my code to add tags to post:
//add post tags
public function add_post_tags($post_id)
{
//tags
$tags = trim($this->input->post('tags', true));
$tags_array = explode(",", $tags);
if (!empty($tags_array)) {
foreach ($tags_array as $tag) {
$tag = trim($tag);
if (strlen($tag) > 1) {
$data = array(
'post_id' => $post_id,
'tag' => trim($tag),
'tag_slug' => str_slug(trim($tag))
);
if (empty($data["tag_slug"]) || $data["tag_slug"] == "-") {
$data["tag_slug"] = "tag-" . uniqid();
}
//insert tag
$this->db->insert('tags', $data);
}
}
}
}
I want to check if data exists in the database update the post_id column if not exist insert new data
"post_id" column like "5,8,9"
I want to add the post number to the previous numbers when I update "post_id" column
for example after update "post_id" column This table is like this "5,8,9,11" here 11 is my last post id
Try using replace() instead :
$this->db->replace('tags', $data);
Basically it inserts a new record if it doesn't exist, it updates it according to its primary or unique key if it does exist.
I am new in php, I was trying to fetch data that I get from the following response but I want to set this data in sub array. How to do this? I have two different tables category and Product. How to Show Multiple Products Category wise.
Thanks in Advance!
{
"data" : [
{
"id" : "1",
"recipe_name" : "Tofu Tikka",
"ingredients" : "Firm tofu 1 pack (bite sized cube)\r\n",
"prepration" : "Press tofu with the help of plate to remove moisture
and leave for 30-40 minutes, then cut in cubes.\r\n",
"category_id":"1",
"category_name":"Today's Menu"
}
]
}
How to set above Response in sub Array like following way
{
"data":[
"category_id":"1",
"category_name":"Today's Menu"
"recipes::[
{
"id":"1",
"recipe_name":"Tofu Tikka",
"ingredients":"Firm tofu 1 pack ",
"prepration":"Press tofu with the help of plate"
}, {
"id":"2",
"recipe_name":"Tikka Paneer",
"ingredients":"Firm tofu 1 pack ",
"prepration":"Press tofu with the help of plate"
},
]
]
}
Below is my PHP File
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
// include database and object files
include_once '../config/database.php';
include_once '../objects/product.php';
// instantiate database and product object
$database = new Database();
$db = $database->getConnection();
// initialize object
$product = new Product($db);
// query products
$stmt = $product->read();
$num = $stmt->rowCount();
// check if more than 0 record found
if ($num>0) {
// products array
$products_arr=array();
$products_arr["data"]=array();
// retrieve our table contents
// fetch() is faster than fetchAll()
// http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// extract row
// this will make $row['name'] to
// just $name only
extract($row);
$product_item=array(
"id" => $id,
"recipe_name" => $recipe_name,
"ingredients" => html_entity_decode($ingredients),
"prepration" => $prepration,
"category_id" => $category_id,
"category_name" => $category_name
);
array_push($products_arr["data"], $product_item);
}
echo json_encode($products_arr);
} else {
echo json_encode(
array("message" => "No products found.")
);
}
?>
In your while loop, you can group the recipes first via category_id instead of pushing the whole row array. Then re-index using array_values().
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// extract row
// this will make $row['name'] to
// just $name only
extract($row);
// Check if category_id is already set
if (!array_key_exists($category_id, $products_arr["data"])) {
$products_arr["data"][$category_id] = array(
"category_id" => $category_id,
"category_name" => $category_name,
"recipes" => []
);
}
// Push the recipe details
$products_arr["data"][$category_id]["recipes"][] = array(
"id" => $id,
"recipe_name" => $recipe_name,
"ingredients" => html_entity_decode($ingredients),
"prepration" => $prepration
);
$products_arr["data"] = array_values($products_arr["data"]);
}
echo json_encode($products_arr);
Note: The output is a little bit different from your expected result. Because the output's data key has arrays based on categories instead of having category_id. Preventing more than one category from overwriting if you use category_id as key inside data
I will suggest you to use JOIN while getting records of category and its related products. It will need single query and single loop to generate array you want. Here is the sample query which you can use. It will get category name with each product record and do not show those categories who do not have products in it.
SELECT * FROM categories AS c LEFT JOIN offers AS p ON c.category_id=p.category_id WHERE p.offer_id IS NOT NULL
Note: - Do not use asterisk (*) in your search query, use table field names instead.
<?php
// initialize empty category array
$categoryArr = [];
// $row has product info with category id and name in it.
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
/* First key of categoryArr variable is category id. It will automatically create array key for each category.
* If an array key already exists, it will add prodcts in it.
*/
$categoryArr[$row['category_id']]['category_id'] = $row['category_id'];
$categoryArr[$row['category_id']]['category_name'] = $row['category_name'];
$categoryArr[$row['category_id']]['products'][] = $row;
}
/* Once loop done with its work. Need to reset array keys with the help of below function. */
$result = array_values($categoryArr);
echo json_encode($result); ?>
I have not tested it, its just to give you an idea. I hope you will improve it.
// I hope it's useful ..
$returnArr = array('category_id' => $category_id,'category_name' => $category_name,$products_arr["data"]); // in last "$products_arr["data"]" set your dynamic code ..
$arr = array('recipes' => $returnArr);
echo json_encode($arr['recipes']); // print json ..
I am trying to do a loop inside of a loop. But it's not returning my values like it should. See Comments in the code. It explains it better. Any advice would be appreciated!
/* LETS PRETEND I HAVE MY FIRST QUERY HERE */
/* THEN THE LOOP */
while ( $the_query->have_posts() ) : $the_query->the_post();
// Establish ID of the clinic from clinicpromo custom field
$clinicid = get_custom_field('assignclinic');
/* MY TROUBLE QUERY:*/
/* GET CLINIC BY ID - This should only retrieve 1 clinic */
$argsthree = array(
'ID' => $clinicid,
'post_type' => 'clinics'
);
$clinics_array = get_posts( $argsthree );
/* I AM TRYING TO QUERY THE CLINIC THAT THE PROMO BELONGS TO AND SAVE
ITS' CUSTOM FIELDS AND REGULAR FIELDS AS VARIABLES TO BE USED LATER */
foreach ( $clinics_array as $clinic ) :
$clinictitle = get_the_title($clinicid);
$cliniccity = get_custom_field('cliniccity');
$clinicstate = get_custom_field('clinicstate');
endforeach;
// How can I use these variables outside of the loop? Or is it possible?
// I keep getting "ArrayArrayArray... as results
echo $clinictitle;
echo $cliniccity;
echo $clinicstate;
/* These variables will be mixed with content from the first query of clinicspromo
/=============SIMPLIFIED UPDATE=========================/
$clinicid = get_custom_field('assignclinic'); // This is the ID of the clinic I am retrieving from ClinicPromos
$clinicpost = get_post($clinicid,array('post_type=clinicpromos'));
$clinictitle = get_the_title($clinicpost->ID);
$cliniccity = get_post_custom_values('cliniccity', $clinicpost->ID);
$clinicstate = get_post_custom_values('clinicstate', $clinicpost->ID);
echo $clinictitle;
echo $cliniccity;
echo $clinicstate;
Try this way, since you are already getting the post id you do not need to do get post
$clinicid = get_custom_field('assignclinic');
you do not need this $clinicpost = get_post($clinicid,array('post_type=clinicpromos'));
$clinictitle = get_the_title( $clinicid);
$cliniccity = get_post_meta($clinicid, 'cliniccity', true);
$clinicstate = get_post_meta($clinicid,'clinicstate', true);
echo $clinictitle;
echo $cliniccity;
echo $clinicstate;
I am adding data to three tables, I needed to get the last ID of the first table to use in the second table, which was successful with $this->db->insert_id() function, Trying that with the second table still gives me the ID of the first table. The arrangement of my code is:
function addcrm() {
//Post data collection array from the webform form
$customerdata = array(
"salutation"=>$this->input->post('salutation'),
"mobilenumber"=>$this->input->post('mobilenumber'),
"emailaddress"=>$this->input->post('emailaddress')
);
$this->db->insert('api_customer', $customerdata);
$customer=$this->db->insert_id();
$leaddata = array(
"fieldrep"=>$this->input->post('fieldrep'),
"fk_customerID"=>$customer,
"te"=>$this->input->post('takage'),
"othercost"=>$this->input->post('othercost')
);
$this->db->insert('api_lead', $leaddata);
$leadID = $this->db->insert_id();
for ($i =0; $i<count($_POST['w_product']); $i++){
$productdata = array(
"name" => $_POST['w_product'][$i],
"type" => $_POST['w_type'][$i],
"cost" => $_POST['w_cost'][$i],
"fk_leadID"=> $leadID
);
$this->db->insert('api_prod',$productdata);
}
$url = base_url('cXXXXXXXXXXXXXX);
redirect($url);
}
You are missing something obviously in the second call. ;)
$customer = $this->db->insert_id();
$leadIdD = $this->db->insert_id;
See? :)
Try working with the following methods:
$this->db->start_cache(); // Before query
$this->db->stop_cache(); // After query
$this->db->flush_cache(); // Clear query
This way you make clear and flushed queries.
if you are using an auto increment table you may try using MYSQL_LAST_INSERT_ID();
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html