How can I implement this SQL query using CodeIgniter Query Builder? - php

I am a beginner using codeigniter query builder class. How can I do this SQL in Query builder Codeigniter..?
Any help is appreciated. Thanks!
SET #interval = 15;
SET #store = 1;
SET #id = 0;
SET #start_dt = '2022-10-12 13:30:00';
SET #end_dt = '2022-10-12 22:30:00';
SELECT
mrt.shoptype_code,
DATE_ADD(#start_dt, INTERVAL vt1.num MINUTE) AS v_dt,
(
SELECT count(*)
FROM s_reservation
WHERE store_code = #store AND id <> #id AND shop_type = mrt.shoptype_code AND status=1 AND start_time <= v_dt AND v_dt < end_time
) AS reservations
FROM
(
SELECT #num := 0 AS num UNION
SELECT #num := #num + #interval FROM information_schema.COLUMNS
) AS vt1
CROSS JOIN
m_shoptype AS mrt
WHERE mrt.store_code = #store
HAVING v_dt BETWEEN #start_dt AND #end_dt
Here I'm trying...
$this->db->SELECT('mrt.shoptype_code AS reservations');
$this->db->DATE_ADD('#start_dt', 'INTERVAL vt1.num MINUTE');
$this->db->SELECT('count(*)');
$this->db->where('store_code = #store AND id <> #id AND shop_type = mrt.shoptype_code AND status=1 AND start_time <= v_dt AND v_dt < end_time');
$this->db->join('m_shoptype as mrt','true');
$result = $this->db->get('s_reservation as reservations')->result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Status " . $row["reservations"]. "<br>";
}
}
else {
echo "Na data found..! ";
}

Related

PHP PDO / MySQLi doesn't return rows while query has mysql user-variables

I want to execute and get the results of the following query:
$query = <<<SQL
set #num := 0, #priority := '';
select * from (
select
id, status_ts,
#num := if(#priority = priority, #num + 1, 1) as _row_number,
#priority := priority as priority
FROM ($priority_query) as get_priority
ORDER BY priority DESC, status_ts ASC
) as items where items._row_number <= CEIL(priority);
SQL;
The $sql = $PDO->query($query); $sql->rowCount() returns 0, there are no result rows. I've tested the query by executing it directly in the DB and it works.
The way to go was to make a multiple query, changing set to select and then properly iterating through the results.
$query = <<<SQL
select #num := 0, #priority := '';
select * from (
select
id, status_ts,
#num := if(#priority = priority, #num + 1, 1) as _row_number,
#priority := priority as priority
FROM ($priority_query) as get_priority
ORDER BY priority DESC, status_ts ASC
) as items where items._row_number <= CEIL(priority);
SQL;
PDO
$sql = $pdo->query($query);
if ($sql && $sql->nextRowset()) {
$items = [];
$numRows = $sql->rowCount();
if (($numRows > 0)) {
$items = $sql->fetchAll(\PDO::FETCH_OBJ);
}
} else {
$error = $this->DB->pdo->errorInfo();
throw new \Exception($error[2]);
}
MySQLi
$mysqli->multi_query($query);
$mysqli->next_result();
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
}

How to conditionally run PHP code only when query returns results?

I hope someone can help me with the best way to structure this code.
I run an oil club as a volunteer and if there are no quotes for a specific oil type, then the page fails due to empty variables being used in queries further down the code.
Ideally I would like to default to $win_supplier_red_id = 0 if the query returns no results, but I'm not sure the best way to catch it and where is the best place in the code.
$sql2a= "Select Quote_id from tbl_quote where (select min(quote_price) as best_red from tbl_quote where fuel_type_id =2 AND timestamp > date_sub( NOW(), INTERVAL 7 DAY ) AND quote_price > 10) = quote_price AND timestamp > date_sub( NOW(), INTERVAL 7 DAY ) Order by timestamp Limit 1";
$stmt2a = $db->prepare($sql2a);
$stmt2a->execute();
$res2a = $stmt2a->fetchObject();
$best_red_quote = $res2a->Quote_id;
$sql2= "SELECT qt.quote_id, ft.fuel_type_id, ft.fuel_name, st.supplier_id, st.company_name as company_name, st.email, qt.supplier_id, qt.timestamp, qt.fuel_type_id, min( qt.quote_price ) AS best_red
FROM tbl_quote qt
INNER JOIN `tbl_suppliers` st ON qt.supplier_id = st.supplier_id
INNER JOIN `tbl_fuel-type` ft ON qt.fuel_type_id = ft.fuel_type_id
WHERE qt.Quote_id = $best_red_quote
Order by timestamp";
$stmt2 = $db->prepare($sql2);
$stmt2->execute();
$res2 = $stmt2->fetchObject();
$best_red = $res2->best_red;
$winning_supplier_red = $res2->company_name;
$win_supplier_red_id = $res2->supplier_id;
$stmt2 = $db->prepare($sql2);
$stmt2->execute();
$res2 = $stmt2->fetchObject();
if (is_object($res2)) {
$best_red = $res2->best_red;
$winning_supplier_red = $res2->company_name;
$win_supplier_red_id = isset($res2->supplier_id) ? $res2->supplier_id : 0;
} else {
$best_red = '';
$winning_supplier_red = '';
$win_supplier_red_id = 0;
}

Php number each query result

I am making a leaderboard, I want to number it like 1st place 2nd place etc in a html table field.
How to I number each row of information coming out?
Something like
$result + 1 ?
My query
$result = mysqli_query($con,"SELECT * FROM playerdata WHERE Admin='0' ORDER BY Bank DESC LIMIT 1");
while($row = mysqli_fetch_array($result)) {
$bank = $row['bank'];
}
Thanks.
You can sort through the query results using:
$result = mysqli_query($con,"SELECT * FROM playerdata WHERE Admin='0' ORDER BY Bank DESC LIMIT 900");
$rows = mysqli_num_rows($result);
for($x = 1; $x <= $rows; $x++) {
$row = mysqli_fetch_array($result);
echo "#{$x} " . $row['bank'];
}
This will start counting down, showing "#1... #2... #3..." etc. You can also do this with your while loop:
$result = mysqli_query($con,"SELECT * FROM playerdata WHERE Admin='0' ORDER BY Bank DESC LIMIT 900");
$x = 1;
while($row = mysqli_fetch_array($result)) {
$bank = $row['bank'];
echo "#{$x} " . $bank;
$x++;
}
With query itself you can build the result, I think this is what u needed. Not sure
SELECT #curRank := #curRank + 1 AS rank, a.*
FROM playerdata a, (SELECT #curRank := 0) r
WHERE Admin='0' ORDER BY Bank DESC LIMIT 900
In php
$result = mysqli_query($con,"SELECT #curRank := #curRank + 1 AS rank, a.*
FROM playerdata a, (SELECT #curRank := 0) r
WHERE Admin='0' ORDER BY Bank DESC LIMIT 900");
while($row = mysqli_fetch_array($result)) {
$rank = $row['rank'];
$bank = $row['Bank'];
}

How do I get the result into a variable MYSQL

I have the following PHP script. How do I get the correct results. Each query should only return a number. I need to get rank in this case. I was also wondering how to combine those two queries into one statement.
function getRankings($country, $deviceid)
{
$queryWorld = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score ) AS rank FROM
ScoreTable b WHERE DeviceID='$deviceid' ORDER BY rank LIMIT 1";
$queryCountry = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score AND Country='$country') AS rank FROM ScoreTable b WHERE DeviceID='$deviceid' ORDER BY rank LIMIT 1";
$resultWorld = mysql_query($queryWorld) or die(mysql_error());
$rowWorld = mysql_fetch_row($resultWorld);
$resultCountry = mysql_query($queryCountry) or die(mysql_error());
$rowCountry = mysql_fetch_row($resultCountry);
$arr = array();
$arr[] = array("WorldRanking" => $rowWorld[0], "CountryRanking" => $rowCountry[0]);
echo json_encode($arr);
}
If I type the queries individually into MYSQl I get the correct answers. But the echo produces
[{"WorldRanking":null,"CountryRanking":null}]
It should be something like
[{"WorldRanking":"4","CountryRanking":"1"}]
I think I need to get the value of rank but I do not know how.
try your code like this, but I don't know this code correct or not:
function getRankings($country, $deviceid)
{
$queryWorld = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score ) AS rank FROM
ScoreTable b WHERE DeviceID='$deviceid' ORDER BY rank LIMIT 1";
$queryCountry = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score AND Country='$country') AS rank FROM ScoreTable b WHERE DeviceID='$deviceid' ORDER BY rank LIMIT 1";
$resultWorld = mysql_query($queryWorld) or die(mysql_error());
while ($rowWorld = mysql_fetch_row($resultWorld)){
$value1 = $rowWorld['filedname1'];
}
$resultCountry = mysql_query($queryCountry) or die(mysql_error());
while($rowCountry = mysql_fetch_row($resultCountry)){
$value2 = $rowWorld['filedname2'];
}
$arr[] = array("WorldRanking" => $value1, "CountryRanking" => $value2);
print_r($arr);
}
<?php
function getRankings($country, $deviceid)
{
$queryWorld = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score ) AS rank FROM
ScoreTable b WHERE DeviceID=$deviceid ORDER BY rank LIMIT 1";
$queryCountry = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score AND Country='$country') AS rank FROM ScoreTable b WHERE DeviceID=$deviceid ORDER BY rank LIMIT 1";
$resultWorld = mysql_query($queryWorld) or die(mysql_error());
$no_of_results_in_resultWorld = mysql_num_rows($resultWorld);
if($no_of_results_in_resultWorld > 0){
$rowWorld = mysql_fetch_row($resultWorld);
}
$resultCountry = mysql_query($queryCountry) or die(mysql_error());
$no_of_results_in_resultCountry = mysql_num_rows($resultCountry);
if($no_of_results_in_resultCountry > 0){
$rowCountry = mysql_fetch_row($resultCountry);
}
$arr = array();
$arr[] = array("WorldRanking" => $rowWorld[0], "CountryRanking" => $rowCountry[0]);
echo json_encode($arr);
}
check whether it is returning results or not.

MySQL query with one variable

I have a table called 'main_table' with 3 columns :
'player', 'points' and 'drop_date'
I have 1 variable ($date) with different values:
$date == '2012-06-01'
$date == '2012-05-01'
$date == '2012-04-01'
I Have 1 MySQL query:
$query = "
select *
from main_table
where `drop_date` > '$date'
AND `drop_date` <= DATE_ADD('$date', INTERVAL 1 YEAR)
LIMIT 1
";
GOAL :
I would like to run ONE query with different passes (1pass per value)
I have tried :
<?php
$date['date'] = '2012-06-01';
$date['date'] = '2012-05-01';
$date['date'] = '2012-04-01';
foreach($date as $title => $actual_date) {
query = "
select *
from main_table
where `drop_date` > '$actual_date'
AND `drop_date` <= DATE_ADD('$actual_date', INTERVAL 1 YEAR)
LIMIT 1
";
$result = mysql_query($query) or die(mysql_error());
}
while($row = mysql_fetch_array($result)) {
echo $row['Player'];
echo $row['Points'];
}
You keep overwriting the same variable over and over... and then you run the query but only fetch results for the last one. How do you expect it to work?
Try this:
$date = Array("2012-06-01","2012-05-01","2012-04-02");
foreach($date as $actual_date) {
if( $result = mysql_fetch_assoc(mysql_query("select * from `main_table` where `drop_date`>'".$actual_date."' and `drop_date`<=date_add('".$actual_date."',interval 1 year) limit 1"))) {
echo $result['Player'];
echo $result['Points'];
}
}
Note that I skipped putting the query in a variable, and putting the query result in a variable, and just one-lined the whole thing. Since you have limit 1 the query will only return one row, so there is no need to while-loop it.
Just move your while in the foreach loop.
<?php
$date[0] = '2012-06-01';
$date[1] = '2012-05-01';
$date[2] = '2012-04-01';
foreach($date as $title => $actual_date)
{
query = "select * from main_table where `drop_date` > '$actual_date' AND `drop_date` <= DATE_ADD('$actual_date', INTERVAL 1 YEAR) LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['Player'];
echo $row['Points'];
}
}
Do not overwrite your values. Do this to keep all 3 values.
<?php
$date['date'][] = '2012-06-01';
$date['date'][] = '2012-05-01';
$date['date'][] = '2012-04-01';
print_r($date);
?>
OUTPUT:
Array
(
[date] => Array
(
[0] => 2012-06-01
[1] => 2012-05-01
[2] => 2012-04-01
)
)
Then use
foreach ($date['date'] as $actual_date) {
$query = "
select *
from main_table
where `drop_date` > '$actual_date'
AND `drop_date` <= DATE_ADD('$actual_date', INTERVAL 1 YEAR)
LIMIT 1";
echo $query."<br />";
}
OUTPUT:
select *
from main_table
where `drop_date` > '2012-06-01'
AND `drop_date` <= DATE_ADD('2012-06-01', INTERVAL 1 YEAR)
LIMIT 1
<br />
select *
from main_table
where `drop_date` > '2012-05-01'
AND `drop_date` <= DATE_ADD('2012-05-01', INTERVAL 1 YEAR)
LIMIT 1
<br />
select *
from main_table
where `drop_date` > '2012-04-01'
AND `drop_date` <= DATE_ADD('2012-04-01', INTERVAL 1 YEAR)
LIMIT 1
<br />

Categories