PHP wpdb get_var query returning zero - php

I have the following code, which is adding some data to a database via server side API. The field order_number should be created via $OrderNumberNext, which is calculated by a count(*)+1 as order_num variable.
However, checking the database after this is done shows that this only ever calculates as 0 (zero). Should I be using a different function call for this?
function addChartToSet($chartId, $setId){
$chartWithId = $this->db->get_var($this->db->prepare("select id from chords where chord_id=%s",$chartId));
$setWithId = $this->db->get_var($this->db->prepare("select id from sets where set_id=%s",$setId));
$orderNumberNext = $this->db->get_var($this->db->prepare("select count(*)+1 as `order_num` from `chords_inside_sets` where `set_id`=%s",$setId));
$this->db->query($this->db->prepare("update sets set `last_updated_time`=NOW() where `set_id`=%s",$setId));
$this->db->query($this->db->prepare("insert into `chords_inside_sets` set `chord_id`=%s , `set_id`=%s, `order_number`= %s",$chartWithId,$setWithId,$orderNumberNext));
return array("last_updated_time"=> $this->getMaxUpdatedTimeForSet($setId), "query"=> $this->db->last_query);
}

You are adding 1 inside the query that fetches the data. It cannot work. Get your count first through the SELECT query, then add one on the next line, like this:
$orderNumberNext = $this->db->get_var($this->db->prepare("select count(*) as `order_num` from `chords_inside_sets` where `set_id`=%s",$setId));
$orderNumberNext++;

Related

INSERT SELECT FROM WHERE generating a row for every occurence of WHERE

I have two sales_orders and sales_invoices. My goal is to copy data from sales_orders to sales_invoices on the press of a button.
I am calling a function in PHP from a submit in a form that passes the WHERE variable (sales_order_id). I have confirmed the variable is being called correctly and when I do this statement direct in mysql it succeeds just as expected, but when I run it in my function it creates a row for every occurence of the sales_order_id (50 rows, as opposed to a single row). I am using 12345 for my sales_order_id.
What am I doing wrong?
Here is my query:
INSERT into sales_invoices(si_customer_id, si_purchase_order_number, ref, si_gross_total)
select so_customer_id, so_purchase_order_number, sales_order_id, sum(so_gross_total + so_vat_adjustment_value) as gross_total
from sales_orders where sales_order_id = 12345
and here is my PHP code
function create_invoice(){
if(isset($_POST['create_invoice'])){
$sales_order_id = escape_string($_POST['sales_order_id']);
$query = query("INSERT into sales_invoices(si_customer_id, si_purchase_order_number, ref, si_gross_total)
select so_customer_id, so_purchase_order_number, sales_order_id, sum(so_gross_total + so_vat_adjustment_value) as gross_total
from sales_orders where sales_order_id = $sales_order_id");
confirm($query);
}
}
All the varaibles work as they should, tested by echoing them out... sales_order_id is a hidden input on the form and is being pulled through as it should.
Thanks to everybody for their input. By changing the code to this
if(isset($_POST['create_invoice']) && $sales_order_id == $_POST['sales_order_id']){
it works as it should.
Thanks too, for the tip re. "Remove sum because it is used for vertical addition like summing the whole column."

CodeIgniter UPDATE works on first, but not successive AJAX calls

This is the weirdest problem. My update query works consistently if I write it as a query string. Here's my model function:
public function approveListing($params)
{
//This always works.
$sql = "UPDATE `assets` set approved = ".$params['approved']." WHERE as_id = ".$params['as_id']."";
$this->db->query($sql);
// and I use this select query to detect the actual updated value change.
$this->db->select('approved');
$this->db->where('as_id', $params['as_id']);
$query = $this->db->get('assets');
foreach($query->result() as $row)
{
$params['approved'] = $row->approved;
}
return $params;
}
...and the output will look something like this:
as_id = 260
approved = 1 (or 0, if the input param is 0)
But if I use the query builder method, rather than a sql string, it works exactly once:
public function approveListing($params)
{
// This only works on the first ajax call. After that, no update occurs.
$this->db->set('approved', $params['approved']); // this will be a value of 1 or 0
$this->db->where('as_id', $params['as_id']);
$this->db->update('assets');
$params['updated'] = $this->db->affected_rows();
// and I use this select query to detect the actual updated value change.
$this->db->select('approved');
$this->db->where('as_id', $params['as_id']);
$query = $this->db->get('assets');
foreach($query->result() as $row)
{
$params['approved'] = $row->approved;
}
return $params;
}
...and the output will look something like this:
as_id = 260
approved = 1
updated = 0 <!- notice this is the affected_rows() value. :( ->
$params['approved'] is either a 1 or a 0. The field approved in table assets is a BIT(1)
The function is being called from a controller function, which itself is being called from an ajax call, which sends the changes of a set of radio button clicks (either '1' or '0').
In the case of the query builder update, I am also capturing the affected_rows. The first time I do the query, the affected_rows() = 1. Every time thereafter, the affected_rows = 0, and by checking the record in PHPMyAdmin, I can see the value just doesn't want to change.
Well, I really dislike answering my own questions, but since I did find an answer, and since the question (though rare) is not "too local", but is, in fact, something other coders are going to run into if they try to update a MySQL data type BIT (why we don't see a lot of questions about data type BIT is because it's one of the newest MySQL or MariaDB data types), here is what's going on.
CodeIgniter query builder wraps the value with single quotes, like so:
UPDATE `assets` set approved = '1' WHERE as_id = 260
MySQL doesn't like that. You could either just hand write your query, like this:
$sql = "UPDATE `assets` set approved = ".$params['approved']." WHERE as_id = ".$params['as_id']."";
$this->db->query($sql);
...But that's not a good solution, it's a copout. The query builder should work.
What you have to do is to declare the value as an INT, and the way you do it is like this:
$this->db->set('approved', (int) $params['approved']);
$this->db->where('as_id', $params['as_id']);
$this->db->update('assets');

Get count query results via getSingleScalarResult() and groupBy() - exception

I want get results of my query (with limit 10) + count possible results.
I know there is similar questions and answers.
for example here
but if i trying get count possible rows (via getSingleScalarResult()) i will get excepton: The query returned multiple rows. Change the query or use a different result function like getScalarResult().
$query = $repository
->createQueryBuilder('t')
->select('COUNT(t.katId)', 't.hotel', 't.title', 't.desc', 'picture', 'MIN(t.price) AS price');
$query->where('t.visible = (:visible)')->setParameter('visible', 1);
// + some wheres, where in, more than....
$query->groupBy('t.hotel');
$query->setMaxResults(10);
echo $query->getQuery()->getSingleScalarResult();
exit();
I just need one integer whitch represent all results from my query.
How can i get this count number? Ideal in one shot to db.
EDIT:
if i remove $query->groupBy('t.hotel'); and in select keep only ->select('count(t.katId)'); then it work. But i need groupBy because it makes real count of results.
SOLUTION
I divided it on two queries so - to get results i rolled back changes to state before trying any count information, and make clone this query (before set setMaxResults and groupBy), change select (keep all wheres) and get count information.
I will be grateful if someone offers better solution
Get results:
removed COUNT() from select
asking for results changed to 'normal' ->getArrayResults
Get count:
$q = clone $query;
$q->select('count(distinct t.hotel) as count');
$r = $q->getQuery()->getArrayResult();
echo $r[0]['count'];
exit();
If you need keep the groupBy:
$query = $repository->createQueryBuilder('t')
$query->select('COUNT(t.katId)', 't.hotel', 't.title', 't.desc', 'picture', 'MIN(t.price) AS price');
$query->from(ENTITY STRING, 't', 't.hotel'); //here defined your array result key
$query->where('t.visible = (:visible)')->setParameter('visible', 1);
$query->groupBy('t.hotel');
$query->setMaxResults(10);
echo $query->getQuery()->getScalarResult();
exit();
Edit : New edit works ?
You are only interested in COUNT(t.katId), so you should drop other returned fields 't.hotel', 't.title', etc.
The result will then contain a single return value (single scalar result), so $query->setMaxResults(10) is not needed.

MySQL SELECT query works in PHPmyadmin, not in PHP

So, Im having a lot of trouble with executing a query in PHP. It executes well in phpmyadmin and gives me a neat list of results.
Here is the query I inserted into phpmyadmin:
SELECT RIGHT(`Pair`, LOCATE('_', REVERSE(`Pair`))-1)
FROM `poloniex`
WHERE LEFT(`Pair`, 3) = 'BTC';
For example an entry in the Column Pair: BTC_NXT
The query should return NXT (everything right of the "_").
Now, when switching over to php while I haven't edited the query at all, I don't get any result.
The dbconnection is already established; no problems on that front.
$query_get_pairs = "SELECT RIGHT(`Pair`,LOCATE('_',REVERSE(`Pair`))-1) FROM `poloniex` WHERE LEFT(`Pair`, 3) = 'BTC'";
$result_get_pairs = mysqli_query($dbc,$query_get_pairs);
var_dump($result_get_pairs) returns an empty array.
Summary:
poloniex is the table name.
Pair is the column name which
contains values like "BTC_NXT". The query should give me NXT.
You are not fetching anything, your code should be like:
$query_get_pairs = "SELECT RIGHT(Pair,LOCATE('_',REVERSE(Pair))-1) FROM poloniex WHERE LEFT(Pair, 3) = 'BTC'";
$result_get_pairs = mysqli_query($query_get_pairs);
$myResult = mysqli_fetch_assoc($result_get_pairs);
var_dump($myResult);

Python mysqldb data

I have a php form which saves these values to the database:
id
rand (a randomly generated string)
x_val
y_val
I am calling these values back from database in a python program using mysqldb:
import MySQLdb
db = MySQLdb.connect("localhost","root","","test" )
cursor = db.cursor()
sql = "SELECT id,rand,x_val,y_val FROM table"
try:
cursor.execute(sql)
results = cursor.fetchall()
results = {}
for row in results:
results[row[1]] = [row[0], row[2], row[3]]
rand = row[1]
x_val = row[2]
y_val = row[3]
except:
print "Error: unable to fecth data"
db.close()
UPDATE: It gives the Error -> Error: unable to fecth data
In this piece (as you can see) i want rand (i.e. row[1]) to serve as the identifier for the row. However, I am not able to find a way about how to use this as an identifier since rand = row[1] is called after the sql variable. In this example, I have used a static '63kfjf' rand value, which is just to show you the working. Is there a way?
After selecting your datas from DB, you can create a dictionnary with "rand" value as key:
Something like this:
dicResults = {}
for row in results:
dicResults[row[1]] = [row[0], row[2], row[3]]
I think you're trying to randomly select a row? If that is correct, this will work.
Change rand to an auto incrementing integer.
SELECT MAX(rand) FROM table; to determine the highest 'random'
value.
Generate a random value between 0 and MAX(rand)
SELECT * FROM table WHERE rand = $randomGeneratedValue;

Categories