Wordpress custom table query conflict? - mysql

I am going mad....
I have custom table: wp_wwiz_customers
and among other columns there i have user_status and when I try to update status using wp db query like this:
$wpdb->update('wp_wwiz_customers', array( 'user_status' => 'CRAZY' ),array('id' => $entryid)
and I am using exit( var_dump( $wpdb->last_query ) ); to see response is:
string 'UPDATE `wp_wwiz_customers` SET `user_status` = 0 WHERE `id` = '4'' (length=65)
Ok, my query seems normal, so why in the world WP puts 0 instead of value.... and I tried to change name of table user_status to user_statusss like in this query and there I have expected result:
$wpdb->update('wp_wwiz_customers', array( 'user_statusss' => 'CRAZY' ),array('id' => $entryid)
// Results as:
string 'UPDATE `wp_wwiz_customers` SET `user_statusss` = 'CRAZY' WHERE `id` = '4'' (length=73)
Ok, so what is my best bet here ? I just can't change column name right now... is there any option to make this work if this is conflict.... ? ...or maybe I am missing something ?

I am again faster to ask than to read documentation....
obviously (sometimes) it is mandatory to place format of data you are entering....
$wpdb->update('wp_wwiz_customers', array( 'user_status' => 'CRAZY' ),array('id' => $entryid),array('%s')
",array('%s')" part tells WP that this is string... and it works now.

Related

mysql query for category and date

How can I query the wordpress database so that I'm only display the number of posts from a certain category starting at a certain date?
I’ve tried something like this but it doesn’t work:
<?php
$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts WHERE term_id = '4' AND post_date >= '2014-01-01 00:00:00' " );
echo "<p>User count is {$user_count}</p>";
?>
What am I doing wrong?
Use wordpress native WP-Query:
$args = array(
'post_type' => 'post',
'date_query' => array(
'year ' => 2015,
),
'cat' => 5,
'posts_per_page'=> -1
);
$query = new WP_Query( $args );
$numberOfPosts = $query->post_count;
$numberOfPosts should hold the number you are looking for. Just paste this where you used your original code which you've shared with us.
Read more here: https://codex.wordpress.org/Class_Reference/WP_Query
Excerpt from the above mentioned url:
posts_per_page (int) - number of post to show per page (available with Version 2.1, replaced showposts parameter). Use 'posts_per_page'=>-1 to show all posts (the 'offset' parameter is ignored with a -1 value). Set the 'paged' parameter if pagination is off after using this parameter. Note: if the query is in a feed, wordpress overwrites this parameter with the stored 'posts_per_rss' option. To reimpose the limit, try using the 'post_limits' filter, or filter 'pre_option_posts_per_rss' and return -1
You can find a bunch of other options there aswell to tweak your query, to get the desired result. This should give the result you want for now.

Codeigniter mysql where not equal to query

Mysql codeigniter query is not working properly.
Suppose if mysql table looks like this:
user_id|user_name
1|john
2|alex
3|sam
Here user_name is unique
The following query should return false if user_name=john and user_id=1 and true if say user_name=john and user_id=2.
$this->db->get_where('user', array('user_name' => $name,'user_id !=' => $userid));
But it returns true in the case user_name=john and user_id=1.
Can anyone suggest me an alternative way of querying not equal to.
print($this->db->last_query()) gives:
SELECT * FROM (user) WHERE user_name = 'john' AND user_id != '1'
Why dont you use simple $this->db->query('your query');
Simply try this, Add the desired condition in the where function.
$this -> db -> where('invitee_phone !=', $user_phone);
You can go follwoing way too. It work for me
$total = 5;
$CI = get_instance();
$CI->load->database();
$CI->db->order_by('id','asc');
$topusers = $CI->db->get_where('users',array('user_type != 1 && `status` =' => 1),$total,0);
echo $CI ->db ->last_query();
die;
and if still not work for you can go with #rohit suggest: $this->db->query('your query');
Type 1:
Using ->where("column_name !=",$columnname) is fine for one column.
But if you want to check multi columns, you have to form an array inside where clause.
Like this
$whereArray = array(
"employee_name" => $name,
"employee_id !=" => $id,
);
$this->db->select('*')->from('employee')->where($whereArray);
Type 2:
We can just write exactly what we want inside where.
Like
$thi->db->where(("employee_id =1 AND employee name != 'Gopi') OR designation_name='leader#gopis clan'");
Type 2 is good for working with combining queries, i mean paranthesis "()"
you can follow this code:
$query = $this->db->select('*')->from('employee')->where('user_name', $name)->where('user_id !=', $userid)->get();
$last_query = $this->db->last_query();
$result = $query->result_array();
if you pass $name = 'john' and $userid = '1' then it return empty array.
The problem with using $this->db->query('your query'); is that it is not portable. One of the most important reasons to embrace the query builder methods is so that no matter what database driver you use, CodeIgniter ensures that the syntax is appropriate.
If a bit of discussion was possible, I'd probably like to hear why you need composite primary identifiers in your table and I'd like to see what your table schema looks like. However, I think the time for discussion has long passed.
Effectively, you want to return a boolean result stating the availability of the combination of the username AND the id -- if one is matched, but not both, then true (available).
To achieve this, you will want to search the table for an exact matching row with both qualifying conditions, count the rows, convert that integer to a boolean, then return the opposite value (the syntax is simpler than the explanation).
Consider this clean, direct, and portable one-liner.
return !$this->db->where(['user_name' => $name,'user_id' => $userid])->count_all_results('user');
this will return false if the count is > 0 and true if the count is 0.

Can I use subqueries in a 'containable' condition?

In my CakePHP I have ModelA which hasMany ModelB. ModelB has an int value Q.
Can I query ModelA and use containable to ensure that only those ModelB records with the maximum value for Q?
I've tried this:
$this->ModelA->contain(array(
'ModelB.Q =(SELECT MAX(ModelB.Q) FROM modelb ModelB WHERE ModelA_id = ' . $id . ')'
));
But it throws a MySQL error because CakePHP interprets the right hand side of that equality operator as a field (at least I think that's why) and so dots it.
... WHERE `Draw`.`round` =.(SELECT MAX.(`Draw`.`round`) ...
Is there a way to do this? I'd prefer not to have to drop down into $query() mode, if at all possible.
EDIT OK, after trying to follow the advice on the page that api55 suggested, I have this code:
$dbo = $this->Tournament->getDataSource();
$conditionsSubQuery['"Draw"."tournament_id"'] = $id;
$maxRounds = $dbo->buildStatement(array(
'fields' => array('MAX(Draw.round) AS prevRound'),
'table' => $dbo->fullTableName($this->Tournament->Draw),
'alias' => 'Draw',
'limit' => null,
'offset' => null,
'joins' => array(),
'conditions' => $conditionsSubQuery,
'order' => null,
'group' => null
),
$this->Tournament
);
$maxSubQuery = ' "Draw"."round" = (' . $maxRounds . ') ';
$maxSubQueryExpression = $dbo->expression($maxSubQuery);
$this->Tournament->contain(array(
'Entrant.selected = 1',
$maxSubQueryExpression
));
$tournament = $this->Tournament->read(null, $id);
But when it runs, it gives me 7 notice/warnings. The first 6 are to do with an object being passed instead of a string:
preg_match() expects parameter 2 to be string, object given
And 6 variations on this:
Object of class stdClass to string conversion
The last is less clear:
Model "Tournament" is not associated with model ""
I suspect I'm being colossally stupid, but there we go.
The contain uses conditions as a normal find, a subquery can be generated and put in conditions. So you should be able to do this as well. Try the subquery part in here and tell me how did it go ;)
This way of generating subqueries for conditions shouldn't fail :D since is the cakephp way.
If you got an error or something comment the answer to see if i can help.

codeigniter mysql query problem

I execute a simple insert query, however this insert is done multiple times sometimes unexpectedly. The code for insert is :
$query=$this->db->query("INSERT INTO clientaccesshistory (jobid, clientid,firstname,lastname,clientname,menu,submenu,starttime) VALUES ('$time','$userID','$firstname','$lastname','$clientname','Monitor/Verify', '$this->job_name',current_timestamp() )");
When i look in the database though this information is sometimes there 3 times, sometimes its just once like it is supposed to be. I think this is some issue with connecting to mysql, and then retries till it inserts three times?
I tested the front end to see if the function is actually be called more than once by putting an alert there, but no problem there whatsoever.
Your code almost certainly has to be in a variable loop of some kind. This code, like wonk says, will not add more than one record, ever.
This won't be of much help, but you can try using this-
$arr = array(
jobid => $time,
clientid => $userID,
firstname => $firstname,
lastname => $lastname,
clientname => $clientname,
menu => 'Monitor/Verify',
submenu => $this->job_name,
starttime => current_timestamp()
);
$this->db->insert('clientaccesshistory', $arr);

Insert a time + n in mySQL using Zend_db_table!

$data = array (
'next' => "NOW() + 5",
'interval' => $dom["USER"][0]["STATUSES_COUNT"][0]["data"],
'good' => $good,
'tries' => $p->tries + 1
);
$where = $service->getAdapter()->quoteInto('id = ?', $p->id);
$service->update($data, $where);
to insert something to a database using PHP on zend and mySQL.
The "next" => "NOW()" wont work. I could put the CURRENT_TIMESTAMP as default value, but what i actually want is to insert the timestamp refering this moment, plus some time.
I could rewrite some parts of the program to use pure php dates(instade of pure mySQL dates). Dont know what is best, or what should i do. Do you know how i could make this update work with mySQL doing the timing?
I solved it with the next statement, very usefull:
'next' => new Zend_Db_Expr('TIMESTAMPADD(MINUTE,1,NOW())'),