I'm always getting Call to a member function fetchAll() on boolean in, I'm using Microsoft Access I'm new at PDO so I don't know if I do it right
My Error:
Fatal error
: Uncaught Error: Call to a member function fetch() on boolean in C:\xampp\htdocs\newtimein_timeout\filter.php:46 Stack trace: #0 {main} thrown in
C:\xampp\htdocs\newtimein_timeout\filter.php
on line
46
<?php
$dbName = 'C:\xampp\htdocs\newtimein_timeout\att2000.mdb';
if (!file_exists($dbName)) {
die("Could not find database file.");
}
$connect = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)}; Server=localhost;
Port=3306; DBQ=$dbName; Uid=; Pwd=;");
$output = '';
$query = "select a.USERID, a.CHECKTIME, a.CHECKTYPE, b.Name,
b.Badgenumber,date_format(a.CHECKTIME, '%Y-%m-%d') as Date,
(CASE
WHEN date_format(c.CHECKTIME, '%h:%i:%s') IS NULL THEN '--:--:--'
ELSE date_format(c.CHECKTIME, '%h:%i:%s')
END) as start_time,
(CASE
WHEN date_format(d.CHECKTIME, '%h:%i:%s') IS NULL THEN '--:--:--'
ELSE date_format(d.CHECKTIME, '%h:%i:%s')
END) as break_out,
(CASE
WHEN date_format(e.CHECKTIME, '%h:%i:%s') IS NULL THEN '--:--:--'
ELSE date_format(e.CHECKTIME, '%h:%i:%s')
END) as break_in,
(CASE
WHEN date_format(f.CHECKTIME, '%h:%i:%s') IS NULL THEN '--:--:--'
ELSE date_format(f.CHECKTIME, '%h:%i:%s')
END) as end_time
from checkinout a
left join (select USERID, CHECKTIME from checkinout where CHECKTYPE='I') c
ON a.USERID=c.USERID AND date_format(a.CHECKTIME, '%Y-%m-%d')=date_format(c.CHECKTIME, '%Y-%m-%d')
left join (select USERID, CHECKTIME from checkinout where CHECKTYPE='0') d
ON a.USERID=d.USERID AND date_format(a.CHECKTIME, '%Y-%m-%d')=date_format(d.CHECKTIME, '%Y-%m-%d')
left join (select USERID, CHECKTIME from checkinout where CHECKTYPE='1') e
ON a.USERID=e.USERID AND date_format(a.CHECKTIME, '%Y-%m-%d')=date_format(e.CHECKTIME, '%Y-%m-%d')
left join (select USERID, CHECKTIME from checkinout where CHECKTYPE='O') f
ON a.USERID=f.USERID AND date_format(a.CHECKTIME, '%Y-%m-%d')=date_format(f.CHECKTIME, '%Y-%m-%d')
left join userinfo b
ON a.USERID=b.USERID
WHERE a.USERID > 0";
if(!empty($_POST["name"])){
$query .= " AND b.Name like '%".$_POST["name"]."%' ";
}
if(!empty($_POST["from_date"]) && (!empty($_POST["to_date"])) ) {
$query .= " AND date_format(a.CHECKTIME, '%Y-%m-%d') BETWEEN '".$_POST["from_date"]."' AND '".$_POST["to_date"]."' ";
}
$query .= " GROUP BY Date";
$result = $connect->query($query);
if ($row = $result->fetchAll()){
echo '<div style="font-size:18px;" class="col-sm-12"><b>ID NUMBER:</b> ' . $row['Name'] . '</div>';
echo '<div style="font-size:18px;" class="col-sm-12"><b>EMPLOYEE NAME:</b> ' . $row['Badgenumber'] . '</div>';
}
$output .= '
<table class="table table-striped table-bordered">
<thead class="thead-dark">
<tr>
<th style="width:220px">Date</th>
<th>Time In</th>
<th>Break Out</th>
<th>Break In</th>
<th>Time Out</th>
</tr>
</thead>
';
if($result->fetchColumn() > 0)
{
while($row = $result->fetchAll())
{
$date=date_create($row['CHECKTIME']);
$dDate = date_format($date,"M d, Y (D)");
$output .= '
<tr>
<td>'. $dDate .'</td>
<td>'. $start_time .'</td>
<td>'. $break_out .'</td>
<td>'. $break_in .'</td>
<td>'. $end_time .'</td>
</tr>
';
}
}
else
{
$output .= '
<tr>
<td colspan="5">No Data Found</td>
</tr>
';
}
$output .= '</table>';
echo $output;
?>
Related
This question already has answers here:
Getting data posted in between two dates
(12 answers)
Closed 1 year ago.
Currently I'm using CodeIgniter to retrieve my data in a particular timeframe. All these entries have a status. I want to group all the entries that have the same status and display it in thier respective headings. Currently this is my model class where I have the following entry to return all the entries in a particular date range:
public function get_records($st_date,$end_date){
$this->db->select('*');
$this->db->from('crm_listings');
$this->db->where('(added_date BETWEEN "' . $st_date . '" AND "' . $end_date . '")');
echo $this->db->count_all_results();
}
And my controller class:
function fetch_status(){
$output ='';
$startDate = '';
$endDate = '';
$this->load->model('crm/user_model');
if($this->input->post('startDate')){
$startDate = $this->input->post('startDate');
}
if($this->input->post('endDate')){
$endDate = $this->input->post('endDate');
}
$data = $this->user_model->fetch_date($startDate,$endDate);
$output .= '
<div class="table-responsive">
<table class="table table-bordered table-striped">
<tr>
<th>Draft</th>
<th>Unpublish</th>
<th>Publish</th>
<th>Action</th>
<th>Unlisted</th>
<th>Sold</th>
<th>Let</th>
</tr>
';
if($data->num_rows() > 0)
{
foreach($data->result() as $row)
{
$output .= '
<tr>
//Dont know what to put in here
</tr>
';
}
}
else
{
$output .= '<tr>
<td colspan="7">No Data Found</td>
</tr>';
}
$output .= '</table>';
echo $output;
}
I have tried using the following command in my phpmyadmin which is giving me the output that I want, but I don't know how to make the query in codeigniter.
SELECT sum(case when status = 'D' then 1 else 0 end) AS Draft,
sum(case when status = 'L' then 1 else 0 end) AS Let,
id FROM `crm_listings`
WHERE added_date BETWEEN '2021-09-24' AND '2021-09-28' ORDER BY `added_date` DESC
Here the dates have to be replaced with $startDate and $endDate.
$sql = "SELECT
sum(case when status = 'D' then 1 else 0 end) AS Draft,
sum(case when status = 'L' then 1 else 0 end) AS Let,
id
FROM `crm_listings`
WHERE added_date BETWEEN '" . $st_date . "' AND '".$end_date."'
ORDER BY `added_date` DESC";
$response = count($this->db->query($sql));
echo $response;
OR
echo $response->num_rows();
I have this function that displays information from a mysql table and it works perfectly when i call it.
However, I am having trouble understanding how to alter it so that it includes pagination and not display everything within the table.
Here's the function's code:
function tabla_presupuestos() {
$conexion_bd = conectar();
$consulta = "
SELECT d.idPre
, em.nombre as doctor
, pac.nombre as paciente
, d.diagnostico
, DATE_FORMAT(d.fechaEmision, '%M %e %Y') as fechaEmision
, DATE_FORMAT(d.fechaVencimiento, '%M %e %Y') as DiasRestantes
FROM empleado em
, paciente pac
, presupuestodental d
WHERE em.idEmpleado = d.idEmpleado
AND pac.idPaciente = d.idPaciente
ORDER
BY fechaEmision
";
$resultados_consulta = $conexion_bd->query($consulta);
$resultado = '<div style="width:auto; margin:0 auto;"><table class="table table-striped">';
$resultado .= '<thead bgcolor="lightblue"><tr><th scope="col">Doctor</th><th scope="col">Paciente</th><th scope="col">Diagnostico</th><th scope="col">Fecha de Emisión</th><th scope="col">Vencimiento</th><th scope="col"> </th><tr></thead>';
while ($row = mysqli_fetch_array($resultados_consulta, MYSQLI_ASSOC)) {
$resultado .= '<tbody><tr>';
$resultado .= '<td>'.$row["doctor"].'</td>';
$resultado .= '<td>'.$row["paciente"].'</td>';
$resultado .= '<td><a href="editardiagnostico.php?idPre='.$row["idPre"].'">'.$row["diagnostico"].'</td>';
$resultado .= '<td>'.$row["fechaEmision"].'</td>';
$resultado .= '<td>'.$row["DiasRestantes"].'</td>';
$resultado .= '<td><button class="btn btn-danger">Ocultar</button></td>';
$resultado .= '</tr>';
}
$resultado .= '</tbody></table></div>';
desconectar($conexion_bd);
return $resultado;
}
You need to do this three things:
Adding LIMIT and OFFSET to the query.
Getting total rows.
Adding paginations button.
In order to add pagination, you have to limit the data displaying, and it is better to get limited data from the database, so I added LIMIT and OFFSET to your query:
SELECT d.idPre,
em.nombre as doctor,
pac.nombre as paciente,
d.diagnostico,
DATE_FORMAT(d.fechaEmision, '%M %e %Y') as fechaEmision,
DATE_FORMAT(d.fechaVencimiento, '%M %e %Y') as DiasRestantes
FROM empleado em, paciente pac, presupuestodental d
WHERE
em.idEmpleado=d.idEmpleado AND
pac.idPaciente=d.idPaciente
ORDER BY fechaEmision
LIMIT ? OFFSET?
Then, you need to get total rows that are presentable and divide it by the rows displaying each time to get total pages. So this is the query for that(you may need to change it in order to get the correct rows count):
SELECT COUNT(*)
FROM empleado em, paciente pac, presupuestodental d
WHERE
em.idEmpleado=d.idEmpleado AND
pac.idPaciente=d.idPaciente
And now to add pagination, let's complete your function. I changed your codes a little in order to clean it:
/*
Counting all rows
*/
function rowCount($db) {
$query = "
SELECT COUNT(*)
FROM empleado em, paciente pac, presupuestodental d
WHERE
em.idEmpleado=d.idEmpleado AND
pac.idPaciente=d.idPaciente";
$stmt = $db->query($query);
return $stmt->fetch();
}
/*
Creating pagintaion links
*/
function pagination($currentPage, $totalPages) {
$html = '
<ul>';
for ($page = 0; $page < $totalPages;$page++)
if ($page == $currentPage)
$html .= '
<li>' . $page . '</li>';
else
$html .= '
<li>
<a href="{the table page link}/' . $page . '>' . $page . '</a>
</li>';
$html .= '
</ul>';
return $html;
}
/*
The page which should be displayed will be taken as a parameter
*/
function tabla_presupuestos($page = 0) {
// This is the number if row you want to display
$rowsPerPage = 10;
$totalPages = rowCount($conexion_bd)/$rowsPerPage;
$conexion_bd = conectar();
$consulta = "
SELECT d.idPre,
em.nombre as doctor,
pac.nombre as paciente,
d.diagnostico,
DATE_FORMAT(d.fechaEmision, '%M %e %Y') as fechaEmision,
DATE_FORMAT(d.fechaVencimiento, '%M %e %Y') as DiasRestantes
FROM empleado em, paciente pac, presupuestodental d
WHERE
em.idEmpleado=d.idEmpleado AND
pac.idPaciente=d.idPaciente
ORDER BY fechaEmision
LIMIT ? OFFSET ?";
$stmt = $conexion_bd->prepare($consulta);
// binding LIMIT and OFFSET to the query
$stmt->bind_param($rowsPerPage, $rowsPerPage*$page);
// executing statement and getting the result
$stmt->execute();
$result = $stmt->get_result();
$resultado = '
<div>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Doctor</th>
<th scope="col">Paciente</th>
<th scope="col">Diagnostico</th>
<th scope="col">Fecha de Emisión</th>
<th scope="col">Vencimiento</th>
<tr>
</thead>';
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$resultado .= '
<tbody>
<tr>
<td>' . $row["doctor"] . '</td>
<td>' . $row["paciente"] . '</td>
<td><a href="editardiagnostico.php?idPre=' . $row["idPre"] . '">' . $row["diagnostico"] . '</td>
<td>' . $row["fechaEmision"] . '</td>
<td>' . $row["DiasRestantes"] . '</td>
<td>
<a href="borrar_presupuesto.php?idPre=' . $row["idPre"] . '">
<button class="btn btn-danger">Ocultar</button>
</a>
</td>
</tr>';
}
$resultado .= '
</tbody>
</table>
' . pagination($page, $totalPages) . '
</div>';
desconectar($conexion_bd);
return $resultado;
}
I doing league table football and There is a profile of Team (Like : Team.php?team=XXX)
In this page I want to show, What position of TeamXXX in League Table
Page League Table
<?php
$number = 0;
$sql = "SELECT * FROM `leaguetable` WHERE `league` = 'leaguename' ORDER BY pts DESC";
$query = mysql_query($sql);
while($rs=mysql_fetch_assoc($query)){
$number++;
?>
<table>
<thead>
<tr>
<th>Position</th>
<th>Team</th>
<th>Points</th>
</tr>
</thead>
<tbody>
<td><?php echo $number; ?></td>
<td><?php echo $rs['team']; ?></td>
<td><?php echo $rs['pts']; ?></td>
</tbody>
</table>
<?php } ?>
Data in Table leaguetable
id team pts
In team.php I want to show position of TeamXXX
<?php
$getTeam = mysql_fetch_assoc(mysql_query("SELECT * FROM `leaguetable` WHERE `team`='"$_GET['team']"'");
?>
<table>
<thead>
<tr>
<th>Position</th>
<th>Team</th>
<th>Points</th>
</tr>
</thead>
<tbody>
<td>#########</td>
<td><? echo $getTeam['team']; ?></td>
<td><? echo $getTeam['pts']; ?></td>
</tbody>
</table>
How can I know what position of teamXXX in leaguetable?
Any help will be greatly appreciated. Thank you very much
query
select id, team, pts, rnk
from
(
select leag.id, leag.team, leag.pts,
#rnk := if(leag.pts = #lag, #rnk,
if(#lag := leag.pts, #rnk + 1, #rnk + 1)) as rnk
from leaguetable leag
cross join ( select #rnk := 0, #lag := null ) params
where league = 'FA Cup'
order by leag.pts desc
) rankings
where team = 'Chelsea'
;
example.php
<?php
/**
* Mysqli initial code
*
* User permissions of database
* Create, Alter and Index table, Create view, and Select, Insert, Update, Delete table data
*
* #package PhpFiddle
* #link http://phpfiddle.org
* #since 2012
*/
require_once "dBug!.php";
require "util/public_db_info.php";
$short_connect = new mysqli($host_name, $user_name, $pass_word, $database_name, $port);
if (mysqli_connect_errno())
{
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
/*
$sql = "create table leaguetable"
. "("
. " id integer primary key not null,"
. " team varchar(33) not null,"
. " pts integer not null default 0"
. ");";
$result = $short_connect->query($sql);
if(!$result)
{
die("Create table failed : " . mysqli_error($short_connect));
}
$sql = "insert into leaguetable"
. "( id, team, pts )"
. "values"
. "( 1, 'Liverpool', 22 ),"
. "( 2, 'Arsenal', 29 ),"
. "( 3, 'Chelsea', 23 ),"
. "( 4, 'Tottenham', 23)";
$result = $short_connect->query($sql);
if(!$result)
{
die("insert failed : " . mysqli_error($short_connect));
}
*/
//get all tables in the database
//$sql = "SHOW TABLES";
//get column information from a table in the database
//$sql="SELECT COLUMN_KEY, COLUMN_NAME, COLUMN_TYPE FROM information_schema.COLUMNS WHERE TABLE_NAME = 'books'";
//SQL statement for a table in the database
$sql = "select id, team, pts, rnk "
. "from"
. "("
. "select leag.id, leag.team, leag.pts,"
. "#rnk := if(leag.pts = #lag, #rnk,"
. " if(#lag := leag.pts, #rnk + 1, #rnk + 1)) as rnk "
. "from leaguetable leag "
. "cross join ( select #rnk := 0, #lag := null ) params "
. " where league = 'FA Cup' "
. "order by leag.pts desc;"
. ") rankings "
. where team = 'Chelsea';";
//result is boolean for query other than SELECT, SHOW, DESCRIBE and EXPLAIN
$result = $short_connect->query($sql);
if (($result) && ($result->num_rows > 0))
{
echo "<table>" . "<thead>" . "<tr>" . "<th>Position</th>" . "<th>Team</th>" . "<th>Points</th>" . "</tr>" . "</thead>" . "<tbody>";
//convert query result into an associative array
echo "<tr><td>" . $row['rnk'] . "</td><td>" . $row['team'] . "</td><td>" . $row['pts'] . "</td></tr>";
echo "</tbody></table>";
}
else
{
die("select failed : " . mysqli_error($short_connect));
}
$short_connect->close();
?>
output
<table>
<thead>
<tr>
<th>Position</th>
<th>Team</th>
<th>Points</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>Chelsea</td>
<td>23</td>
</tr>
</tbody>
</table>
sqlfiddle
Hope this will help
$number = 0;
$points=0;
$sql = "SELECT * FROM `leaguetable` WHERE `league` = 'leaguename' ORDER BY pts DESC";
$query = mysql_query($sql);
while($rs=mysql_fetch_assoc($query)){
if($points!=$rs['pts'])
$number++;
if($rs['team']==$_GET['team']){
if($points==$rs['pts'])
$position=$number-1;
else
$position=$number;
}
$poins=$rs['pts'];
}
If you don't mind using two queries (I wouldn't mind it), it's pretty easy: Just count how many teams have more points, and add one (so that if three teams are tied in second position, they all get position 2).
$result = mysql_query("SELECT count(*)+1 AS POSTN FROM leaguetable WHERE
league = 'leaguename' AND pts > $points");
$row = mysql_fetch_assoc($result);
$position = $row["POSTN"];
Doing it in one query is a bit messier, since you need to embed this query in your original one:
"SELECT *, (SELECT count(*)+1 FROM leaguetable table2
WHERE league = 'leaguename' AND table2.pts > leaguetable.pts) AS POSTN
FROM leaguetable WHERE team = '$currentteam'"
But why are you using the mysql_* API for new code? Haven't you noticed all the dire warnings in pink boxes in the documentation? Do yourself a favor and switch to mysqli today, starting with this program.
Also: Never just inject $_GET[param] into your query string! You're giving yourself an SQL injection attack waiting to happen... and brittle, error-prone code until then.
I'm developing a web application that works with WordPress database. In my website,(which works with WooCommerce and WPML) I have products in two languages - english (1st), serbian(2nd). I wrote an SQL code that get the products from database, with their regular and sale prices and etc., but I want to get ONLY products where lang = en (the products from english version). The problem is I don't know how to get them.
Simple SQL:
$sql = 'SELECT * from `wp_posts` WHERE post_type = product';
This is the method that SELECT from database:
// SELECT
public function select (
$table_1 = ' wp_posts ',
$table_2 = ' wp_postmeta ',
$rows = ' t1.id, t1.post_title, guid, post_type ',
$where = ' t1.post_status = "publish" AND t1.post_type = "product" OR t1.post_type = "product_variation" ',
$groupby = ' t1.ID, t1.post_title '
) {
// Connect to database and set charset
$this->connect();
$this->conn->set_charset('utf8');
// Published products
$sql = "SELECT $rows,
max(case when meta_key = '_regular_price' then t2.meta_value end) AS price,
max(case when meta_key = '_sale_price' then t2.meta_value end) AS sale,
max(case when meta_key = 'attribute_colors' then t2.meta_value end) AS colors,
max(case when meta_key = 'attribute_number' then t2.meta_value end)
FROM $table_1 AS t1
INNER JOIN $table_2 AS t2 ON ( t1.ID = t2.post_id )
WHERE $where
GROUP BY $groupby";
$result = mysqli_query($this->conn, $sql);
$published_products_count = mysqli_num_rows($result);
// Trashed products
$trashed_sql = "SELECT post_status FROM `wp_posts`
WHERE post_status = 'trash'";
$trashed_result = mysqli_query($this->conn, $trashed_sql);
$trashed_products_count = mysqli_num_rows($trashed_result);
// If results -> show them
if ($result) {
printf( "\t\t" . "<p>There are <strong>%d published</strong> products and <strong>%d trashed</strong>.</p>", $published_products_count, $trashed_products_count);
$table = '
<table class="pure-table pure-table-bordered">
<thead>
<tr>
<th>Row. №</th>
<th>ID</th>
<th>Product</th>
<th>Regular price</th>
<th>Sale price</th>
<th>Type</th>
<th>Edit</th>
</tr>
</thead>';
$row_number = 1;
while ($row = $result->fetch_assoc()) {
$table .= '
<tr>
<td>' . $row_number++ . '</td>
<td>' . $row["id"] . '</td>
<td>' . $row["post_title"] . '</td>
<td class="price">' . $row["price"] . '</td>
<td class="sale">' . $row["sale"] . '</td>
<td>' . $row["post_type"] . '</td>
<td>Edit</td>
</tr>';
}
$table .= '
</table>';
echo $table;
}
// If no results
else {
echo 'There isn't any products';
}
}
I hope somebody help me!
Thanks in advance! :)
P.S. The application is not based on WordPress!
WPML plugin creates several new tables to manage multilang, not affecting the standard WP posts tables. Specifically, it creates the wp_icl_translations table, where it stores relations between posts and languages.
You need to add two new JOIN statements to your query:
JOIN wp_icl_translations t ON wp_posts.ID = t.element_id AND t.element_type = 'post_product' JOIN wp_icl_languages l ON t.language_code=l.code AND l.active=1
Then, you can add a new condition to your WHERE statement like this:
AND t.language_code='en'
Hope this helps.
Regards.
I am pulling out data from my "facebook" table using this code that I then display in a table using the foreach() function:
$orders = $db->QueryFetchArrayAll("SELECT id,url,c_amount,amount,date,status FROM `facebook` WHERE `user`='".$data['id']."' ORDER BY `date` DESC LIMIT 30");
How would I go about pulling out data from multiple tables, for example from the "facebook" AND "twitter" table and then displaying it at the same time in my table?
Here is my full code for those that would need that:
<table class="table">
<thead>
<tr>
<td># (ID)</td>
<td>URL</td>
<td>Current Amount</td>
<td>Amount Wanted</td>
<td>Date</td>
<td>Status</td>
</tr>
</thead>
<tbody>
<?
$orders = $db->QueryFetchArrayAll("SELECT id,url,c_amount,amount,date,status FROM `facebook` WHERE `user`='".$data['id']."' ORDER BY `date` DESC LIMIT 30");
if(!$orders){ echo '<tr><td colspan="6" align="center"><b>Noting found!</b></td><tr>';}else{
foreach($orders as $order){
?>
<?
if($order['status'] == 0){
$status = '<label style="color: #999999;">Waiting for supplier</label>';
}
elseif ($order['status'] == 1) {
$status = '<label style="color: #f0ad4e;">In progress</label>';
}
elseif ($order['status'] == 2) {
$status = '<label style="color: #e25856;">Canceled/Refunded</label>';
}
elseif ($order['status'] == 3) {
$status = '<label style="color: #428bca;">Pending admin review</label>';
}
else{
$status = '<label style="color: #94b86e;">Completed</label>';
}
?>
<tr>
<td><?=$order['id']?></td>
<td><?=$order['url']?></td>
<td><?=$order['c_amount']?></td>
<td><?=$order['amount']?></td>
<td><?=date('Y-m-d h:i',$order['date'])?></td>
<td><?=$status?></td>
</tr><?}}?>
</tbody>
</table>
Use the UNION keyword.
Please note that both queries should have the same fields count and the same fields types.
Example :
$orders = $db->QueryFetchArrayAll(
"SELECT id,url,c_amount,amount,date,status FROM `facebook` WHERE `user`='"
. $data['id']
. "' UNION
SELECT field1, field2, field3, field4, field5 FROM `twitter` WHERE some_condition "
);
Hope it helps
You would want to use a union
$orders = $db->QueryFetchArrayAll("SELECT id,url,
c_amount,amount,date,status FROM `facebook`
WHERE `user`='".$data['id']."'
join ORDER BY `date` DESC LIMIT 30
UNION
SELECT id,url,
c_amount,amount,date,status FROM `twitter`
WHERE `user`='".$data['id']."'
join ORDER BY `date` DESC LIMIT 30");