I'm looping through contacts, pulling out specific data then want to update a particular column on the current row. How can I do that?
The line is at the very bottom, I just want to change it from a 0 to 1.
require('../mailin.php');
$mailin = new Mailin("https://api.sendinblue.com/v2.0","Your access key");
$customer_data = $wpdb->get_results("SELECT * FROM imp_customer_log WHERE updated_in_sib = '0'");
foreach( $customer_data as $customer ) {
$customer_id = $customer[0];
$customer_event = $customer[1];
$customer_data = $customer[2];
$customer_sib = $customer[3];
$user = get_user_by( 'id', $customer_id );
$user_email = $user->user_email;
$data = array(
"email" => $user_email,
"attributes" => array(
$customer_event => $customer_data,
),
);
var_dump($mailin->create_update_user($data));
// Change updated_in_sib to 1 for current row
}
i assume that this is a wordpress. you can use the update function in wpdb something look like this.
$wpdb->update('imp_customer_log', ['customer_sib' => 1], ['id' => $customer_id]);
you can check the it on documentation. https://codex.wordpress.org/Class_Reference/wpdb#UPDATE_rows
for php (not wordpress)
$sql = "UPDATE imp_customer_log SET customer_sib=1 WHERE id=" . $customer_id;
$connection->query($sql);
I think you're using Wordpress. Take a look at these wordpress docs for update, used just like get_results() in your question.
https://developer.wordpress.org/reference/classes/wpdb/update/
$wpdb->update( string $table, array $data, array $where, array|string $format = null, array|string $where_format = null )
Related
I'm a PHP newbie trying to extend the Wordpress API on our BuddyPress website. I've created a database table which I plan on using to store a user's friends (or in our specific case "favourite members"). I would like to write an API endpoint to return a user's friends using the user's id as an input (i.e. "myapi/v1/favouritemembers/[user id]"). This is what I've done so far;
/*** Grab favourite members for a specified user ***/
function favourite_members( $data ) {
$favourites = get_favourite_members(array(
'user_id' => $data['user_id'],
) );
if ( empty( $favourites ) ) {
return null;
}
return $favourites;
}
function get_favourite_members( $data ){
global $wpdb;
$sql = $wpdb->prepare( "SELECT member_id FROM wp_my_favourite_members WHERE user_id = %d", $data['user_id'] );
return $wpdb->get_results( $sql );
}
/*** Register register_rest_route ***/
add_action( 'rest_api_init', function () {
register_rest_route( 'myapi/v1', '/favouritemembers/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'favourite_members',
) );
} );
I'm having trouble getting this to work correctly, the endpoint just returns an empty response. If I replace the query
"SELECT member_id FROM wp_my_favourite_members WHERE user_id = %d", $data['user_id'] with "SELECT member_id FROM wp_my_favourite_members WHERE user_id = 1" then it works as expected, so I'm suspecting there may be something wrong with the way I am dealing with the input parameters in the get_favourite_members function, but I'm not sure.
I've worked it out, I was almost there, just needed to change
register_rest_route( 'myapi/v1', '/favouritemembers/(?P<id>\d+)'
to
register_rest_route( 'myapi/v1', '/favouritemembers/(?P<user_id>\d+)'
so the parameter names match.
I want to call the method $wpdb->get_results(),
and I need to add parameters (WHERE clauses) to the SQL query.
The thing is, I want to build a generic function that will receive a parameters object and will generate an SQL query which includes my parameters.
So, for example, if this is my base query:
$taxis = $wpdb->get_results("SELECT * FROM $table", ARRAY_A); // base query
And these are my parameters:
$params = array(
'color' => 'blue',
'model' => 'ford'
);
It will call get_results with the following query:
SELECT * FROM $table WHERE color='blue' AND model='ford';
Is there a way to build a function that will have this behaviour?
*NOTES:
I don't know how many parameters are going to be in the parameters object nor which parameters they will be (that is why it has to be generic).
I do know, (in my case) that the only SQL CLAUSES I am going to need are WHERE =.
See the code comments for an explanation on what is happening in each step:
<?php
// make sure this doesn't come from user input, as it is inserted into the query directly
$tableName = $wpdb->prefix . "yourtable";
$columnWhitelist = array( 'color', 'model' );
$params = array(
'color' => 'blue',
'model' => 'ford'
);
// filter param keys by allowed column names defined in $columnWhitelist
$params = array_filter(
$params,
function ( $key ) use ( $columnWhitelist ) {
return in_array( $key, $columnWhitelist );
},
ARRAY_FILTER_USE_KEY
);
$whereClauseParts = array();
// put column/value pairs of $params into $placeholderValues array
$placeholderValues = array();
foreach ( $params as $column => $value) {
$whereClauseParts[] = "`$column` = %s";
$placeholderValues[] = $value;
}
// put together the WHERE clause with placeholders
$whereClause = implode(' AND ', $whereClauseParts );
// put together the whole query tring
$queryString = "SELECT * FROM `$tableName` WHERE " . $whereClause;
// you can use this to see what your prepared query will roughly look like,
// but with missing single quotes around the values
// die( vsprintf(
// $queryString,
// $placeholderValues
// ) );
$wpdb->get_results(
$wpdb->prepare(
$queryString,
$placeholderValues
)
);
I try to insert data to a table in CI 3 that has fields as below:
pageid is auto increment and I write code in model as this:
$data = array(
'title'=>$title,
'description'=>$des,
'url'=>'page/view/'.pageid
);
$this->db->insert('page',$data);
The problem is that the pageid is unknown as the field name. What should I do because I want to concatenate pageid to url?
You need two query for it
1)You need to insert title and description first and get last page id from database
$data = array(
'title' => $title,
'description' => $des
);
$this->db->insert('page', $data);
$page_id = $this->db->insert_id();// get last pageid
2)Update url second
$data = array(
'url' => 'page/view/'.$page_id
);
$this->db->where('pageid'$page_id);// update with page id
$this->db->update('page', $data);
OK so you can add all data first then after insert just update the url
field.
$data = array(
'title' => $title,
'description' => $des,
'url'=>'page/view/'
);
$this->db->insert('page', $data);
$page_id = $this->db->insert_id();
2)Now update URL
$update= array(
'url' => 'page/view/'.$page_id
);
$this->db->where('page_id'$page_id);
$this->db->update('page', $update);
Hope this will help you
Common & Easy Method
Goto
Phpmyadmin
select your database, then go to page table.
Click structure on top.
Click Change, in front of id field.
Then there is check box with AI(Auto Increment)
Check that and click save
If with code(use this)
public function FunctionName()
{
$query = $this->db->query("SELECT id FROM pages ORDER BY id DESC LIMIT 1");
$result = $query->result_array();
$id = $result['id']; // or some times $result[0]['id']
$data = array(
'title' => $title,
'description' => $des,
'url' => 'page/view/'.pageid,
'id' => $id
);
$this->db->insert('page',$data);
}
Just do like this:
$data = array(
'title'=>$title,
'description'=>$des
);
$this->db->insert('page',$data);
$page_id = $this->db->insert_id();
//To pass page_id to url column
$this->db->where('page_id', $page_id);
$data_1 = array('url'=>'page/view/'.$pageid);
$this->db->update('page', $data_1);
You can first get the highest Auto-Incremented id from select query and then, Use insert query for inserting the new row.
eg.
$id = $this->db->query("Select max(page_id) AS page_id from pages");
if($id->num_rows() > 0){
$result = $id->result_array();
$page_id = $result[0]['page_id'] +1;
}
// if table is empty
else{
$page_id = 1;
}
$data = array(
'title' => $title,
'description' => $des,
'url'=>'page/view/'.$page_id );
$this->db->insert('page',$data);
Please check it image for add auto increment id in phpmyadmin.
Here is the code:
$the_question = $_POST['question'];
$the_answer = $_POST['answer'];
$dummy_num[] = $_POST['dummy_answer_1'];
$dummy_num[] = $_POST['dummy_answer_2'];
$dummy_num[] = $_POST['dummy_answer_3'];
//Get Hidden Test ID and Q_order
$test_id = $_POST['test_id'];
$q_order = $_POST['q_order'];
//Submit Question
$data_submit_q = array (
'type' => 1,
'question' => $the_question,
'done' => 1
);
$this->db->where('test_id', $test_id);
$this->db->where('q_order', $q_order);
$this->db->update('questions', $data_submit_q);
$question_id = $this->db->insert_id();
$time_created = date('Y-m-d H:i:s');
//Submit Answer
$data_submit_a = array (
'test_id' => $test_id,
'question_id' => $question_id,
'option' => $the_answer,
'company_id' => $data['company']->id,
'job_id' => $data['session_job_id'],
'time_created' => $time_created
);
$this->db->insert('options', $data_submit_a);
$answer_id = $this->db->insert_id();
//Let question know that answer is right.
$data_submit_qr = array (
'answer_id' => $answer_id
);
$this->db->where('id', $question_id);
$this->db->where('test_id', $test_id);
$this->db->update('questions', $data_submit_qr);
Setting the answer id removes the value of the question id, then on updating the database the answer id has no value also. Even though it does right before.
The method $this->db->insert_id() retrieves the ID when performing database inserts (as the name hints).
You're using it after an update, that's why your $question_id gives problems (I think it would be set to FALSE, but I don't know for sure what does that method return when called on the wrong context). WHen you do your last update you use this as a WHERE condition, and if it is not set...
It's not that your second call to insert_id() wipes out the first, I suspect is more like the first one is already NOT SET (or FALSE)
It seems that there is a bug with insert_id, you can try using:
$query = $this->db->query('SELECT LAST_INSERT_ID()');
$row = $query->row_array();
$lastInsertId = $row['LAST_INSERT_ID()'];
Hope it helps
I'm having some issues getting codeigniter active record to produce a query like this:
SELECT fruits.* FROM fruits
WHERE fruits.color = 'red'
AND ( fruits.size = 'medium' OR fruits.name = 'kiwi' OR fruits.length = 7 );
Basically I want to have several or clauses but one where clause that is always enforced.
$this->db->select( 'fruits.*' );
$this->db->from( 'fruits' );
$this->db->where( 'fruits.color', 'red' );
$this->db->or_where( 'fruits.size', 'medium' );
$this->db->or_where( 'fruits.name', 'kiwi' );
$this->db->or_where( 'fruits.length', 7 );
Produces something like:
SELECT fruits.* FROM fruits WHERE fruits.color = 'red' OR fruits.size = 'medium' OR fruits.name = 'kiwi' OR fruits.length = 7;
I need to enforce that color is always red.
Is there a decent way to do this?
There is no way to achieve this properly using CodeIgniter Active Record.
The only way that's not too ugly is using a custom string with the where() function like this:
$this->db->select( 'fruits.*' );
$this->db->from( 'fruits' );
$where = "fruits.color = 'red' AND ( fruits.size = 'medium' OR fruits.name = 'kiwi' OR fruits.length = 7 );";
$this->db->where( $where );
IMPORTANT: note that using a custom string, your variable WILL NOT be escaped, thus, you need to use $this->db->escape()
$this->db->select( 'fruits.*' );
$this->db->from( 'fruits' );
$color = 'red';
$size = 'medium';
$name = 'kiwi';
$length = 7;
$where = "fruits.color = '".$this->db->escape($color)."' AND ( fruits.size = '".$this->db->escape($size)."' OR fruits.name = '".$this->db->escape($name)."' OR fruits.length = '".$this->db->escape($length)."');";
$this->db->where( $where );
Edit:
I got confused on the good query, I corrected it :)