KoolReport's Forum

Official Support Area, Q&As, Discussions, Suggestions and Bug reports.
Forum's Guidelines

Input in SQL query #3174

Open Adolfo Alonso opened this topic on on Oct 18, 2023 - 15 comments

Adolfo Alonso commented on Oct 18, 2023

Hello, Im having trouble using a input on a SQL query.

MyReport.php:

protected function defaultParamValues()
{
	return array(
		"dateRange"=>array(
			date("Y-m-d", strtotime('-7 days')) . " 00:00:00",
			date("Y-m-d", strtotime('-0 days')) . " 23:59:59"
		),
		"customers"=>array(),
	);
}

protected function bindParamsToInputs()
{
	return array(
	"dateRange"=>"dateRange",
	"customers"=>"customers",
	);
}

....

public function setup()
{
	$this->src('automaker')
	->query("SELECT * FROM (
			SELECT 
			c.nombre AS conductor,
			(SELECT descripzam FROM (SELECT 
							conhistid,
							h.conductorid,
							h.sucursalid,
							c.nombre,
							s.descripzam,
							fecha
							FROM tbl_cond_suc_historial h
							INNER JOIN tbl_conductor c ON c.conductorid = h.conductorid
							INNER JOIN cat_sucursales s ON s.sucursalid = h.sucursalid
							WHERE c.sucursalid IN (18, 19, 23, 24)
							AND c.estatus =1
						UNION ALL
							SELECT 0, c.conductorid, c.sucursalid, c.nombre, (SELECT s.descripzam from cat_sucursales s WHERE s.sucursalid = c.sucursalid), fecha_ingreso 
							FROM tbl_conductor c
							WHERE c.sucursalid IN (18, 19, 23, 24)
							AND c.estatus =1) t WHERE t.conductorid = g.conductor AND t.fecha < g.eventtimemx ORDER BY fecha DESC LIMIT 1) AS sucursal,
			SUM(CASE
				WHEN confirmacion_clasificacion = 'conducción distraída' THEN 1 
				ELSE 0 END
			) AS 'conducción distraída',
			SUM(CASE
				WHEN confirmacion_clasificacion = 'conducción distraída de notificación obligatoria' THEN 1 
				ELSE 0 END
				) AS 'conducción distraída de notificación obligatoria',
			SUM(CASE
				WHEN confirmacion_clasificacion = 'uso del celular' THEN 1 
				ELSE 0 END
				) AS 'uso del celular',
			SUM(CASE
				WHEN confirmacion_clasificacion = 'somnolencia' THEN 1 
				ELSE 0 END
				) AS 'somnolencia',
			SUM(CASE
				WHEN confirmacion_clasificacion = 'bostezar' THEN 1 
				ELSE 0 END
				) AS 'bostezar',
			SUM(CASE
				WHEN confirmacion_clasificacion IN ('conducción distraída', 'conducción distraída de notificación obligatoria', 'uso del celular', 'somnolencia', 'bostezar') THEN 1 
				ELSE 0 END
				) AS 'total'
			FROM tbl_guardian g
			INNER JOIN tbl_conductor c ON c.conductorid = g.conductor
			WHERE g.eventtimemx > :start
			AND	g.eventtimemx < :end
			AND confirmacion_clasificacion NOT IN ('Conducción normal', 'cámara desalineada', 'sensores cubiertos')
			AND c.estatus = 1
			AND g.cla_fp <> 1
			AND g.conductor = :customers
			GROUP BY conductor, sucursal
			ORDER BY conductor, sucursal
			) a WHERE a.sucursal = 'TSP - LINDE TEPEJI'")
	->params(array(
	":start"=>$this->params["dateRange"][0],
	":end"=>$this->params["dateRange"][1],
	":customers"=>$this->params["customers"]
	))
	->pipe($this->dataStore('purchase_summary'));
	
	$this->src("automaker")->query("
	SELECT conductorid, nombre FROM tbl_conductor c
	WHERE c.estatus = 1
	AND c.sucursalid IN (18, 19, 23, 24)
	AND conductorid <> 22")
	->pipe($this->dataStore("customers"));
}    

MyReport.view.php

<form method="post">
	<div class="row">
		<div class="col-md-8 offset-md-2">
			<?php
				Select2::create(array(
					"name"=>"customers",
					"dataStore"=>$this->dataStore("customers"),
					"dataBind"=>array(
						"text"=>"nombre",
						"value"=>"conductorid",
					),
					"attributes"=>array(
						"class"=>"form-control",
					)
				));
			?>
			<br>
			<?php
				DateRangePicker::create(array(
				"name"=>"dateRange"
				))
			?>
		</div>
	</div>
	<div class="form-group text-center">
		<button class="btn btn-success"><i class="glyphicon glyphicon-refresh"></i>Cargar</button>
	</div>
	<pre><code><?php echo json_encode($this->params,JSON_PRETTY_PRINT) ?></code></pre>
</form>
Sebastian Morales commented on Oct 18, 2023

Is your "customers" parameter single or multiple?

If it's single, the default value in defaultParamValues() should be a number, string, etc, and not be array().

If it's multiple, your sql query where clause "g.conductor = :customers" should be changed to "AND g.conductor in (:customers)" and the Select2 create should include "multiple" => true.

Adolfo Alonso commented on Oct 18, 2023

Hi, its a multiple parameter, I changed from Select2 to MultiSelect. Please take a look at my code, I cant get it to work:

MyReport.php

protected function defaultParamValues()
{
	return array(
		"dateRange"=>array(
			date("Y-m-d", strtotime('-7 days')) . " 00:00:00",
			date("Y-m-d", strtotime('-0 days')) . " 23:59:59"
		),
		"customers"=>array(),
	);
}

protected function bindParamsToInputs()
{
	return array(
	"dateRange"=>"dateRange",
	"customers"=>"customers"
	);
}

...

public function setup()
	{
		$this->src('automaker')
		->query("SELECT * FROM (
				SELECT 
				c.nombre AS conductor,
				(SELECT descripzam FROM (SELECT 
								conhistid,
								h.conductorid,
								h.sucursalid,
								c.nombre,
								s.descripzam,
								fecha
								FROM tbl_cond_suc_historial h
								INNER JOIN tbl_conductor c ON c.conductorid = h.conductorid
								INNER JOIN cat_sucursales s ON s.sucursalid = h.sucursalid
								WHERE c.sucursalid IN (18, 19, 23, 24)
								AND c.estatus =1
							UNION ALL
								SELECT 0, c.conductorid, c.sucursalid, c.nombre, (SELECT s.descripzam from cat_sucursales s WHERE s.sucursalid = c.sucursalid), fecha_ingreso 
								FROM tbl_conductor c
								WHERE c.sucursalid IN (18, 19, 23, 24)
								AND c.estatus =1) t WHERE t.conductorid = g.conductor AND t.fecha < g.eventtimemx ORDER BY fecha DESC LIMIT 1) AS sucursal,
				SUM(CASE
					WHEN confirmacion_clasificacion = 'conducción distraída' THEN 1 
					ELSE 0 END
				) AS 'conducción distraída',
				SUM(CASE
					WHEN confirmacion_clasificacion = 'conducción distraída de notificación obligatoria' THEN 1 
					ELSE 0 END
					) AS 'conducción distraída de notificación obligatoria',
				SUM(CASE
					WHEN confirmacion_clasificacion = 'uso del celular' THEN 1 
					ELSE 0 END
					) AS 'uso del celular',
				SUM(CASE
					WHEN confirmacion_clasificacion = 'somnolencia' THEN 1 
					ELSE 0 END
					) AS 'somnolencia',
				SUM(CASE
					WHEN confirmacion_clasificacion = 'bostezar' THEN 1 
					ELSE 0 END
					) AS 'bostezar',
				SUM(CASE
					WHEN confirmacion_clasificacion IN ('conducción distraída', 'conducción distraída de notificación obligatoria', 'uso del celular', 'somnolencia', 'bostezar') THEN 1 
					ELSE 0 END
					) AS 'total'
				FROM tbl_guardian g
				INNER JOIN tbl_conductor c ON c.conductorid = g.conductor
				WHERE g.eventtimemx > :start
				AND	g.eventtimemx < :end
				AND confirmacion_clasificacion NOT IN ('Conducción normal', 'cámara desalineada', 'sensores cubiertos')
				AND c.estatus = 1
				AND g.cla_fp <> 1
				".
				(($this->params["customers"]!=array())?"AND g.conductor IN (:customers)":"")
				."
				GROUP BY conductor, sucursal
				ORDER BY conductor, sucursal
				) a WHERE a.sucursal = 'TSP - LINDE TEPEJI'")
		->params(array(
			":start"=>		$this->params["dateRange"][0],
			":end"=>		$this->params["dateRange"][1],
			":customers"=>	$this->params["customers"]
		))
		->pipe($this->dataStore('purchase_summary'));

MyReport.view.php

<form method="post">
	<div class="row">
		<div class="col-md-8 offset-md-2">
			<div class="form-group">
				<?php
					MultiSelect::create(array(
						"name"=>"customers",
						"dataStore"=>$this->dataStore("customers"),
						"dataBind"=>array(
							"text"=>"nombre",
							"value"=>"conductorid",
						),
						"attributes"=>array(
							"class"=>"form-control",
							"size"=>5,
						)
					));
				?>
			</div>
			<div class="form-group">
				<?php
					DateRangePicker::create(array(
						"name"=>"dateRange"
					))
				?>
			</div>
			<div class="form-group text-center">
				<button class="btn btn-success"><i class="glyphicon glyphicon-refresh"></i>Cargar</button>
			</div>
		</div>
	</div>
	<pre><code><?php echo json_encode($this->params,JSON_PRETTY_PRINT) ?></code></pre>
</form>
Sebastian Morales commented on Oct 19, 2023

Pls post error message, screenshots, and describe what the problem is. Rgds,

Adolfo Alonso commented on Oct 20, 2023

Hi, The user picks a driver and daterange, then I would like to use the driverid on a SQL query.

Im using <?php echo json_encode($this->params,JSON_PRETTY_PRINT) ?> to validate the values are sent in the form, which seem ok...

Thanks

Sebastian Morales commented on Oct 23, 2023

Pls echo your sql query with the requested parameter values replaced in and copy/paste the query to your database admin interface to see if it returns expected results or not.

Adolfo Alonso commented on Oct 23, 2023

How can I echo my query? Thanks

Sebastian Morales commented on Oct 23, 2023

Currently, you use this command:

->query("SELECT * FROM (
    ...")

Pls change it to:

$query = "SELECT * FROM (
    ...";
echo "query: " . $query . "<br>";
$this->src('automaker')
->query($query)
...
Adolfo Alonso commented on Oct 24, 2023

Hi Sebastian, please see the attached image, I can see the :customers variable is not putting the values in the query, but it is in the input array, thanks.

Sebastian Morales commented on Oct 24, 2023

You can replace :start, :end and :customers with the dateRange and customers values manually. Here we just want to verify independently that the query returns data or not. In the report's setup KoolReport automatically bind those parameters for you.

Adolfo Alonso commented on Oct 25, 2023

Hi Sebastian, the query is returning values. please advise

Sebastian Morales commented on Oct 25, 2023

When the query returns non-empty data with certain date range and customers, print out your datastore in report view like this:

var_dump($this->dataStore('purchase_summary')->data());

Let us know the result.

Adolfo Alonso commented on Oct 25, 2023

Hello, its vardump is not giving any data.... please advice

Same query with fixed values:

Sebastian Morales commented on Oct 25, 2023

Do you use form submit or ajax request to update the data table?

Adolfo Alonso commented on Oct 25, 2023

Hi Sebastian, I use form submit...

Sebastian Morales commented on Oct 26, 2023

Ok, pls try to convert the customers parameter before binding like this:

		->params(array(
			":start"=>		$this->params["dateRange"][0],
			":end"=>		$this->params["dateRange"][1],
			":customers"=>	array_map('intval', $this->params["customers"])
		)) 

Build Your Excellent Data Report

Let KoolReport help you to make great reports. It's free & open-source released under MIT license.

Download KoolReport View demo
help needed

None