How do you count the number of times a delete query has been successfully executed using wordpress default database class.
for example:
$delete = $wpdb->query("DELETE FROM table where and itemid > itemid");
I know one way is to fire a select count:
$deletecount = $wpdb->query("SELECT COUNT(*) FROM table where itemid > itemid");
but is there a direct way to know the count without executing a second query?
Thank you!
The $wpdb->query(...) function returns an integer value corresponding to the number of rows affected. So, if you delete 10 rows then it'll return 10, use it like:
$count = $wpdb->query('delete query');
Also you may use the delete method:
$count = $wpdb->delete( $table, $where, $where_format = null );
Returns the same affected rows on successful operation and false on failure. Read more on Codex.
Related
So I have the following table:
And I'm trying to write a Query where I can send the code BR_BN as a variable in my WHERE clause
and if I get BR_BN then I want to retrieve the records with this code AND the records with the Code_FS RB02. On the other side when I get the value AB_CP, I want to include the recordes with the Code_FS RB01.
Here's the Query I've tried so far:
DECLARE #Code_OB VARCHAR(20) = 'BR_BN'
SELECT * FROM Dummy_AV
WHERE FK = 2
OR
(#Code_OB = 'BR_BN' AND Code_FS = 'RB02' AND Code_FS = #Code_OB)
But it doesn't work, it retrieves all the records regardless of the FK, and/or the #Code_FS.
How can I achieve this?
Thanks for the help.
You don't note the FK = 2 being needed, yet you have it in front of an OR in the WHERE clause. I think this is what you're after, if it isn't exactly what you're aiming for hopefully it gets you on the right track. For future questions, always helpful to paste your sample data as data instead of an image.
DECLARE #Code_OB VARCHAR(20) = 'BR_BN'
SELECT * FROM Dummy_AV
WHERE FK = 2 -- you will get all rows where this is true
OR
((#Code_OB = Code_OB AND Code_FS = 'RB02') OR (Code_OB = 'AB_CP' AND Code_FS = 'RB01')) -- you will get all rows where one of these is true
I've been attempting to write a peewee select query which results in a table with 2 counts (one for the number of prizes associated with the lottery, and the for the number of packages associated with the lottery), as well as the fields in the Lottery model.
I've managed to write select queries with 1 count working (seen below), and then I've had to convert the ModelSelects to lists and join them manually (which I think is very hacky).
I did manage to write a select query where the results were joined, but it would multiply the packages count with the prizes count (I've since lost that query).
I also tried using a .switch(Lottery) but I didn't have any luck with this.
query1 = (Lottery.select(Lottery,fn.count(Package.id).alias('packages'))
.join(LotteryPackage)
.join(Package)
.order_by(Lottery.id)
.group_by(Lottery)
.dicts())
query2 = (Lottery.select(Lottery.id.alias('lotteryID'), fn.count(Prize.id).alias('prizes'))
.join(LotteryPrize)
.join(Prize)
.group_by(Lottery)
.order_by(Lottery.id)
.dicts())
lottery = list(query1)
query3 = list(query2)
for x in range(len(lottery)):
lottery[x]['prizes'] = query3[x]['prizes']
While the above code works, is there a cleaner way to write this query?
Your best bet is to do this with subqueries.
# Create query which gets lottery id and count of packages.
L1 = Lottery.alias()
subq1 = (L1
.select(L1.id, fn.COUNT(LotteryPackage.package).alias('packages'))
.join(LotteryPackage, JOIN.LEFT_OUTER)
.group_by(L1.id))
# Create query which gets lottery id and count of prizes.
L2 = Lottery.alias()
subq2 = (L2
.select(L2.id, fn.COUNT(LotteryPrize.prize).alias('prizes'))
.join(LotteryPrize, JOIN.LEFT_OUTER)
.group_by(L2.id))
# Select from lottery, joining on each subquery and returning
# the counts.
query = (Lottery
.select(Lottery, subq1.c.packages, subq2.c.prizes)
.join(subq1, on=(Lottery.id == subq1.c.id))
.join(subq2, on=(Lottery.id == subq2.c.id))
.order_by(Lottery.name))
for row in query.objects():
print(row.name, row.packages, row.prizes)
There is a condition if not satisfied then I just want to return no rows as my application will pick no row and will show no record msg on front end. Is there any other professional way?
For now I am using following query to return no row.
select 0
where 1 = 0
Even when you return no rows, you are still returning a schema. And most applications expect the same schema to be returned regardless of the number of rows. Even when 0 rows are returned.
If you can change the SQL in #SqlStr that you are executing with sp_executesql, I would insert into a temporary table in that query and then return the results of selecting from that temporary table:
Select * from #myTempTable where <conditionRequiredForResults>
You said you want to return no rows on your frontend and return nothing. Neither message nor row.
You just need to use if statement to avoid returning anything to your frontend
require_once 'db_connection.php';
$sql = "SELECT * FROM table_name WHERE <your filtering Condition>";
$result = mysqli_query($db_connection, $sql);
if (mysqli_num_rows($result) > 0) {
// If row to be fetched is more than 0
// Return something Example:
echo "Rows detected";
} else {
// If there is no row to be fetched
// Return nothing
}
And this should return nothing if no row fetched from database
Hello i am trying to write an existing xlsx file using phpspreadsheet with setActiveSheetIndexByName(sheetname) and setcellvalue with reference and value, but it updates only the last record. spent more than 12 hours on this.
i tried foreach instead of while and used a counter to increment, but none worked.
<?php
include_once('db.php');
$prospect = $_REQUEST['prospect'];
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$sql1 = mysqli_query($db,"select filename,sheetname, row, responsecol,compliancecol,response, compliance from spreadsheet where `prospect`='$prospect' and response <>'' order by row");
//$row=1;
while($row1 = mysqli_fetch_assoc($sql1))
{
$filename= $row1['filename']; //test.xlsx
$sheetname= $row1['sheetname']; // mysheet
$responsecol= $row1['responsecol'].$row1['row']; //D1
$response= $row1['response']; //response
$compliancecol= $row1['compliancecol'].$row1['row']; //C1
$compliance= $row1['compliance']; //compliance
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filename);
$spreadsheet->setActiveSheetIndexByName($sheetname)
->setCellValue($compliancecol,$compliance)
->setCellValue($responsecol,$response);
//$row++;
}
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save("newfile.xlsx");
exit;
?>
i wish each of the row from mysqli result updates each reference cell with value.
The easys way is to set a Limit of 1 to your MySQL query. That takes only one value from your data. If you will the last you should sort DESC.
$sql1 = mysqli_query($db,"select filename,sheetname, row, responsecol,compliancecol,response, compliance from spreadsheet where `prospect`='$prospect' and response <>'' order by row DESC LIMIT 1");
I am trying to check if the primary-key (entered manually by the user) exists already in the SQLite database or not (in order to decide whether to proceed with an insertion of a new record or to do an update for an existent one).
I've tried:
query.exce();
query.isEmpty();
and bellow I'm trying: guery.isNull();
However, they all give me the same result: they all say the record doesn't exist (return 0) and go to the insertion function. They return 0 even if the ref_no does exist).
Here is my code for isNull() function:
int DatabaseManager::checkRefNoExist(QString ref_no){
QSqlQuery query;
query.prepare("SELECT * FROM basic_info WHERE ref_no = :ref_no");
query.bindValue(":ref_no", ref_no);
query.exec();
if(query.isNull(ref_no.toInt())){
return 0; // whatever the ref_no is, it always comes here !!
} else {
return 1;
}
}
You are using ref_no.toInt() as column index. This does not make sense.
To check whether the query returned any result row, try to fetch the first result (with query.first() or query.next()).