I'm working with a simple HTML5 GET form... But building a query that will filter my results it shows me this error:
Fatal error: Uncaught ValueError: Unknown format specifier "{" in F:\symme\xampp\htdocs\www\libreria-final\libros.php:51 Stack trace: #0 F:\symme\xampp\htdocs\www\libreria-final\libros.php(51): sprintf('\r\n S...', 'AR', 'Push', 'Push', 'ARIEL2022E', 'FANTASIA') #1 {main} thrown in F:\symme\xampp\htdocs\www\libreria-final\libros.php on line 51
This is my code:
include 'autenticacion.php';
$conn = OpenCon();
$lista_paises = "";
$autor = "";
$lista_editoriales = "";
$lista_temas = "";
if(isset($_GET['enviar-filtros'])) {
if (!isset($_GET["listapaises"]) || empty($_GET["listapaises"])) {
echo "Ningun país...";
} else {
$lista_paises = $_GET["listapaises"];
}
if (!isset($_GET["autor"]) || empty($_GET["autor"])) {
echo "Ningún autor...";
} else {
$autor = $_GET["autor"];
}
if (!isset($_GET["listaeditoriales"]) || empty($_GET["listaeditoriales"])) {
echo "Ninguna editorial...";
} else {
$lista_editoriales = $_GET["listaeditoriales"];
}
if (!isset($_GET["listatemas"]) || empty($_GET["listatemas"])) {
echo "Ningún tema...";
} else {
$lista_temas = $_GET["listatemas"];
}
}
$sql_mostrar = sprintf("
SELECT `libro`.`TITULO`, `libro`.`ANNO_PUBLICACION`, `autor`.`NOMBRE` AS 'NOMBRE_AUTOR', `autor`.`APELLIDOS`, `tema`.`NOMBRE` AS 'TEMA', `editorial`.`NOMBRE` AS 'EDITORIAL'
FROM `libro`
JOIN `libro_autor` ON `libro_autor`.`CODIGO_LIBRO` = `libro`.`CODIGO_LIBRO`
JOIN `autor` ON `autor`.`CODIGO_AUTOR` = `libro_autor`.`CODIGO_AUTOR`
JOIN `autor_pais` ON `autor_pais`.`CODIGO_AUTOR` = `autor`.`CODIGO_AUTOR`
JOIN `pais` ON `autor_pais`.`CODIGO_PAIS` = `pais`.`CODIGO_PAIS`
JOIN `libro_tema` ON `libro_tema`.`CODIGO_LIBRO` = `libro`.`CODIGO_LIBRO`
JOIN `tema` ON `tema`.`CODIGO_TEMA` = `libro_tema`.`CODIGO_TEMA`
JOIN `editorial` ON `libro`.`CODIGO_EDITORIAL` = `editorial`.`CODIGO_EDITORIAL`
WHERE `pais`.`CODIGO_PAIS` = '%s'
AND `autor`.`NOMBRE` LIKE '%{%s}%' OR `autor`.`APELLIDOS` LIKE '%{%s}%'
AND `editorial`.`CODIGO_EDITORIAL` = '%s'
AND `tema`.`CODIGO_TEMA` = '%s'
ORDER BY `libro`.`TITULO` ASC;", $lista_paises, $autor, $autor, $lista_editoriales, $lista_temas);
Pd: Line 51 is where i have my ORDER BY sentence.
I tried to change the way the sql query takes the values but the error is still there...
Related
Fatal error: Uncaught Error: Cannot use object of type stdClass as array in C:\xampp\htdocs\Tugas Akhir\master-trade.php:114 Stack trace: #0 {main} thrown in C:\xampp\htdocs\Tugas Akhir\master-trade.php on line 114
<?php
function terlambat($tgl_dateline, $tgl_kembali){
$tgl_dateline_pecah = explode("-", $tgl_dateline);
$tgl_dateline_pecah = $tgl_dateline_pecah[2]."-".$tgl_dateline_pecah[1]."-".$tgl_dateline_pecah[0];
$tgl_kembali_pecah = explode("-", $tgl_kembali);
$tgl_kembali_pecah = $tgl_kembali_pecah[2]."-".$tgl_kembali_pecah[1]."-".$tgl_kembali_pecah[0];
$selisih = strtotime($tgl_kembali_pecah)-strtotime($tgl_dateline_pecah);
$selisih = $selisih/86400;
if ($selisih>=1){
$hasil_tgl = floor($selisih);
} else {
$hasil_tgl = 0;
}
return $hasil_tgl;
}
?>
<td>
<?php
$denda = 1000;
$tgl_dateline2 = $rs['tgl_kembali'];
$tgl_kembali - date('Y-m-d');
$lambat = terlambat($tgl_dateline2, $tgl_kembali);
$denda1 = $lambat*$denda;
if ($lambat>0) {
echo "
<font color='red'>$lambat hari<br>(Rp $denda1)</font>
";
}else{
echo $lambat ."Hari";
}
?>
</td>
Im trying to make a search filter for table products and im trying to have pagination and filter in the same sql query. Im using a MVC pattern.
This is the model:
<?php
namespace Dao\test;
use Dao\Table;
class Productos extends Table
{
public static function obtenerProductos($list, $search, $numPerPage)
{
$startFrom = (intval($list)-1)*$numPerPage;
$sqlStr = "SELECT * FROM productos WHERE name LIKE '%:search%' LIMIT :startFrom,:numPerPage;";
$parametros = array(
"search" => $search,
"startFrom" => $startFrom,
"numPerPage" => $numPerPage
);
return self::obtenerRegistros($sqlStr, $parametros);
}
public static function obtenerNumeroProductos()
{
$sqlStr = "SELECT * FROM productos;";
return self::obtenerRegistros($sqlStr, array());
}
}
?>
This is the controller:
<?php
namespace Controllers\test;
use Controllers\PublicController;
use Views\Renderer;
class Productoss extends PublicController
{
public function run() :void
{
\Utilities\Site::addLink("/public/css/test1.css");
if(isset($_GET["search"])){
$search = $_GET["search"];
}else{
$search="";
}
$numPerPage = 5;
if(isset($_GET["list"])){
$list=$_GET["list"];
}
else{
$list=1;
}
$viewData = array(
"totalProductos" => 0,
"totalList" => "",
);
$viewData["producto"] = \Dao\test\Productos::obtenerProductos($list, $search, $numPerPage);
$viewData["lista"] = \Dao\test\Productos::obtenerNumeroProductos();
foreach ($viewData["lista"] as $producto) {
$viewData["totalProductos"] = $viewData["totalProductos"] + 1;
}
$viewData["totalList"] = ceil($viewData["totalProductos"]/$numPerPage);
for ($i=1; $i <= $viewData["totalList"]; $i++) {
$viewData["nList"]["number"] = $i;
$viewData["nPages"][] = $viewData["nList"];
}
if($list<$viewData["totalList"]){
$viewData["next"] = true;
$viewData["nextBtn"] = $list+1;
}
if ($list>1) {
$viewData["previous"] = true;
$viewData["prevBtn"] = $list - 1;
}
Renderer::render("test/Productoss", $viewData);
}
}
?>
I get the error:
Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter
number: number of bound variables does not match number of tokens in
C:\xampp\htdocs\PHPmvc\SimplePHPMvcOPP\src\Dao\Table.php:70 Stack
trace: #0
C:\xampp\htdocs\PHPmvc\SimplePHPMvcOPP\src\Dao\Table.php(70):
PDOStatement->execute() #1
C:\xampp\htdocs\PHPmvc\SimplePHPMvcOPP\src\Dao\test\Productos.php(18):
Dao\Table::obtenerRegistros('SELECT * FROM p...', Array) #2
C:\xampp\htdocs\PHPmvc\SimplePHPMvcOPP\src\Controllers\test\Productoss.php(34):
Dao\test\Productos::obtenerProductos(1, 'a', 5) #3
C:\xampp\htdocs\PHPmvc\SimplePHPMvcOPP\index.php(27):
Controllers\test\Productoss->run() #4 {main} thrown in
C:\xampp\htdocs\PHPmvc\SimplePHPMvcOPP\src\Dao\Table.php on line 70
I finally found an answer, what i did was this:
public static function obtenerLaboratorios($list, $search, $numPerPage)
{
$startFrom = (intval($list)-1)*$numPerPage;
if(!empty($search)){
$sqlStr = "SELECT * FROM laboratorio WHERE `laboratorioNombre` LIKE :search LIMIT :startFrom,:numPerPage;";
$parametros = array(
"search" => "%$search%",
"startFrom" => $startFrom,
"numPerPage" => $numPerPage
);
}else{
$sqlStr = "SELECT * FROM laboratorio LIMIT :startFrom,:numPerPage;";
$parametros = array(
"startFrom" => $startFrom,
"numPerPage" => $numPerPage
);
}
return self::obtenerRegistros($sqlStr, $parametros);
}
This way the mvc doesn't take the error for the '' symbols, that was what cause me problems. Takes the value of the variable $search and just puts the "%" in the start/end of the variable.
I'm working on a system that has several server-side datatables but i facing issues with 2 joins when i try to order de columns.
I receive the following message when try to sort the columns:
Query error: Column 'notes' in order clause is ambiguous - Invalid query: SELECT *
FROM `tbl_project`
LEFT JOIN `tbl_client` ON `tbl_project`.`client_id`=`tbl_client`.`client_id`
LEFT JOIN `tbl_account_details` ON `tbl_project`.`created_by` = `tbl_account_details`.`user_id`
LEFT JOIN `tbl_notes` ON `tbl_project`.`notes` = `tbl_notes`.`notes_id`
WHERE `tbl_project`.`client_id` = '100'
ORDER BY `notes` DESC
LIMIT 10
This is the code with my query:
$id = $this->input->post("client_id");
$client_details = get_row('tbl_client', array('client_id' => $id));
$draw = intval($this->input->post("draw"));
$start = intval($this->input->post("start"));
$length = intval($this->input->post("length"));
$order = $this->input->post("order");
$search= $this->input->post("search");
$search = $search['value'];
$col = 0;
$dir = "";
if(!empty($order))
{
foreach($order as $o)
{
$col = $o['column'];
$dir= $o['dir'];
}
}
if($dir != "desc" && $dir != "desc")
{
$dir = "desc";
}
$valid_columns = array(
0=>'project_id',
1=>'client',
2=>'fullname',
3=>'notes',
4=>'origen',
5=>'end_date',
6=>'project_status',
7=>'action',
);
if(!isset($valid_columns[$col]))
{
$order = null;
}
else
{
$order = $valid_columns[$col];
}
if($order !=null)
{
$this->db->order_by($order, $dir);
}
$searchQuery = "";
if($search != ''){
$searchQuery = " (tbl_project.project_id like'%".$search."%' OR tbl_project.end_date like'%".$search."%' OR tbl_project.project_status like'%".$search."%' OR tbl_notes.notes like'%".$search."%' OR tbl_notes.eco like'%".$search."%' OR tbl_account_details.origen like'%".$search."%' OR tbl_client.name like'%".$search."%') ";
}
$this->db->select('*');
$this->db->from('tbl_project');
$this->db->join('tbl_client', 'tbl_project.client_id=tbl_client.client_id','left');
$this->db->join('tbl_account_details', 'tbl_project.created_by = tbl_account_details.user_id','left');
$this->db->join('tbl_notes', 'tbl_project.notes = tbl_notes.notes_id','left');
$this->db->where('tbl_project.client_id', $client_details->client_id);
if($searchQuery != '')
$this->db->where($searchQuery);
$this->db->limit($length,$start);
$cita = $this->db->get()->result();
For some reason the ORDER BY is not set as tbl_notes.notes
Any suggestion on how to fix this?
Thanks in advance
EDIT: i have added more code so there is more visibility of the process
The error occurs, because your column name is not unique, it exists in more than one table.
append the table name of the searched column to your query to make it unique:
for example in this line:
$this->db->order_by('my_table_name.'.$order, $dir);
that would generate something like
ORDER BY `my_table_name.notes` DESC
edit: or in case you have to address columns from several different tables you could change your $valid_columns array:
$valid_columns = array(
0=>'my_table_name1.project_id',
1=>'my_table_name2.client',
2=>'my_table_name2.fullname',
3=>'my_table_name3.notes',
// etc.
);
and maintain the remaining original code.
I'm very much a beginner at Drupal development, MySQL, and pretty much everything, so this may seem trivial, but I would really appreciate any help I can get here.
I'm getting this error, and I'm not really sure what's wrong, because everything was working fine before, and I didn't change anything around the area that it mentions since the last time it was working perfectly.
The exact error is:
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ASC' at line 3: SELECT n.nid AS nid FROM {node} n INNER JOIN {embryo_log} a ON n.nid = a.nid WHERE (n.type = :db_condition_placeholder_0) AND (a.expiration_date > :db_condition_placeholder_1_0) ORDER BY n.sticky DESC, n.changed DESC ASC; Array ( [:db_condition_placeholder_0] => embryo_log [:db_condition_placeholder_1_0] => -1 ) in embryo_log_all() (line 599 of /data/www/drupal-7.34/sites/all/modules/embryo_log/embryo_log.module)."
Here is the entire function that the error is referencing, because I don't know what might be relevant:
function embryo_log_all($option = NULL, $action = NULL) {
$nodes_per_page = variable_get('embryo_log_per_page', variable_get('default_nodes_main', 10));
$output = '<div class="embryo_log">';
// If the optional param is numeric, assume it is a node or term id.
if (is_numeric($option)) {
if ($action == 'group') {
// Get all embryo_log with this term.
// TODO Change fully to a dynamic query
$result = db_query("SELECT n.nid FROM {node} n LEFT JOIN {taxonomy_index} tn USING (nid) WHERE n.type = :n.type AND n.status = :n.status AND tn.tid = :tn.tid", array(':n.type' => 'embryo_log', ':n.status' => 1, ':tn.tid' => $option));
foreach ($result as $nid) {
$embryo_log = node_load($nid->nid);
$output .= '<h2>' . check_plain($embryo_log->title) . '</h2>';
$build = node_view($embryo_log);
$output .= drupal_render($build);
}
return $output . '</div>';
}
else {
$embryo_log = node_load($option);
// If it is an embryo_log, ok, else ignore it.
if ($embryo_log != NULL) {
if ($embryo_log->type == 'embryo_log') {
$build = node_view($embryo_log, 'full');
// Plain node title
$outp = '<h2>' . check_plain($embryo_log->title) . '</h2>';
$build['#node']->title = ''; // Don't render title
return $outp . drupal_render($build);
}
}
}
}
if (user_access('edit embryo_log')) {
$args = array(-1);
}
else {
$args = array(gmdate("U"));
}
// $query = "SELECT n.nid FROM {node} n INNER JOIN {embryo_log} a ON n.nid=a.nid
// WHERE n.type='embryo_log' AND a.expiration_date > %d
// ORDER BY " . variable_get('embryo_log_page_order', 'n.sticky DESC, n.changed DESC');
$query = db_select('node', 'n');
$query->extend('PagerDefault')
->limit($nodes_per_page);
$query->innerJoin('embryo_log', 'a', 'n.nid = a.nid');
$query->condition('n.type', 'embryo_log', '=')
->condition('a.expiration_date', $args, '>')
->fields('n', array('nid'))
->orderBy(variable_get('embryo_log_page_order', 'n.sticky, n.changed'), '');
// $query_result = pager_query(db_rewrite_sql($query, 'n', 'nid'), $nodes_per_page, 0, NULL, $args);
$query_result = $query->execute();
foreach ($query_result as $nid) {
$embryo_log = node_load($nid->nid);
$build = node_view($embryo_log, $option);
$output .= drupal_render($build);
}
$output .= '</div>';
$output .= theme('pager', array('tags' => NULL));
return $output;
}
And the line in there that is specifically being referenced in the error (line 599) is the one towards the bottom that says $query_result = $query->execute();
Any help would be greatly appreciated, because everything looks fine to me, and I'm at a loss.
Thanks!
First of thank you for your help.
The code piece "while (sqlite_has_more($dres))" is using sqlite2 and I need sqlite3. If there isn't a replacement for has_more is there another code I can use to still Find whether or not more rows are available?
F.Y.I. The server updated their stuff which included their sqlite and now I have to fix this last peice of code to get the schedule to populate and not give me this error.
Fatal error: Non-static method SQLite3::open() cannot be called statically in /home/server/public_html/current-list.php on line 57
$row_num = 0;
if ($dbh = SQLite3::open($sked_path))
{
$qsql = "SELECT rowid,* FROM sked ORDER BY sk_dow_num, sk_time_start, sk_time_end";
$dres = SQLite3::query($dbh, $qsql);
if (SQLite3::num_Rows($dres) > 0)
{
$last_dow = "";
$last_start = "0000";
$last_end = "0000";
while (sqlite_has_more($dres))
{
$ska = Sqlite3Result::fetchArray($dres, SQLITE3_ASSOC);
$rid = $ska['rowid'];
$dow = $ska['sk_dow_name'];
$start = $ska['sk_time_start'];
$end = $ska['sk_time_end'];
$title = preg_replace("/<br\s*\/*>/", " ", $ska['sk_show_title']);
$show_dow = strtoupper($dow);
$show_start = strtoupper(formatTimeAmPm($start));
$show_end = strtoupper(formatTimeAmPm($end));
$show_style = "";
if (stristr($title, "Encore Show"))
$show_style = " class=\"$text_style\"";
Something like ...
<?php
$dbh = new SQLite3;
if ( !$dbh->open($sked_path) ) {
trigger_error('...error handling...', E_USER_ERROR);
}
else {
$dres = $dbh->query('
SELECT
rowid,*
FROM
sked
ORDER BY
sk_dow_num, sk_time_start, sk_time_end
');
if ( !$dres ) {
trigger_error('...error handling...', E_USER_ERROR);
}
else {
$ska = $dres->fetchArray(SQLITE3_ASSOC);
if ( !$ska ) {
onNoRecords();
}
else {
do {
doSomethingWithRowData($ska);
}
while( false!=($ska=$dres->fetchArray(SQLITE3_ASSOC)) );
}
}
}
(completely untested)