I try to make new datatables and following this tutorial.
But, I got an error message :
"Error occuered during query execution: (<small>SELECT a.idrec,a.date, a.model, a.serial, a.item,a.symptom, a.remark
FROM second_sampling AS a
WHERE 1=1 ORDER BY LIMIT , </small>): 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 'LIMIT ,' at line 3";
the syntax is :
$requestData= $_REQUEST;
$columns = array(
// datatable column index => database column name
0 => 'idrec',
1 => 'date',
2 => 'model',
3 => 'serial',
4 => 'item',
5 => 'symptom',
6 => 'remark'
);
$sql = "SELECT a.idrec,a.date, a.model, a.serial, a.item,a.symptom, a.remark
FROM second_sampling AS a
WHERE 1=1";
if( !empty($requestData['search']['value']) ) { // if there is a search parameter, $requestData['search']['value'] contains search parameter
$sql.=" AND ( a.date LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR a.model LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR a.serial LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR a.item LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR a.symptom LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR a.remark LIKE '".$requestData['search']['value']."%' )";
}
$query=mysql_query($sql) or _doError(_ERROR30 . ' (<small>' . htmlspecialchars($sql) . '</small>): ' . mysql_error() );
$totalFiltered = mysql_num_rows($query);
$sql. =" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
$query=mysql_query($sql) or _doError(_ERROR30 . ' (<small>' . htmlspecialchars($sql) . '</small>): ' . mysql_error() );
try to close the root cause and put:
<?php
echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
?>
then show :
{"draw":0,"recordsTotal":49,"recordsFiltered":49,"data":[]}
Array( [sEcho] => 1 [iColumns] => 7 [sColumns] => ,,,,,, [iDisplayStart] => 0 [iDisplayLength] => 10
Your vars
$columns[$requestData['order'][0]['column']]
$requestData['start']
$requestData['length']
so the
$sql. =" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".
$requestData['order'][0]['dir'].
" LIMIT ".$requestData['start']." ,".$requestData['length']." ";
produce wrong query clause
ORDER BY LIMIT ,
In the output SQL there should be a column name between the ORDER BY and the LIMIT, and then two numbers separated by a comma after the LIMIT.
The fact this is not happening seems to indicate that the variable $requestData is empty, or at least not filled with the values you were expecting.
I would try:
var_dump($requestData);
to find out what is really in the variable $requestData.
Your Statement is invalid
WHERE 1=1 ORDER BY LIMIT ,
This part is the problem:
$sql. =" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
The requestData $columns[$requestData['order'][0]['column']],
$requestData['order'][0]['dir'],
$requestData['start'],
and $requestData['length'] is empty.
Related
I am trying to pass table name and column name from String to the sql query, but for some reason it doesnt work.
This is an example of what am trying to do from symfony 4.4 documentation :
This is how I am trying to do it :
$sql = "SELECT
:col,
COUNT(*) AS `cnt`
FROM
:tab
GROUP BY
:col
";
$stmt = $conn->prepare($sql);
$stmt->execute([ 'col' => $col , 'tab' => $tab ]);
return $stmt->fetchAllAssociative();
output :
meanwhile, it works like this :
$sql = "SELECT
typeCl,
COUNT(*) AS `cnt`
FROM
client
GROUP BY
typeCl
";
$stmt = $conn->prepare($sql);
$stmt->execute([ 'col' => $col , 'tab' => $tab ]);
return $stmt->fetchAllAssociative();
And I still want to make my table and column parametrable .. is there anyway to do that ??
(It is not about my String values I used dump and die and make sure nothign wrong with that)
This is how i made it work :
$sql = "SELECT ".$col.",
COUNT(*) AS `cnt`
FROM
".$tab."
GROUP BY
".$col."
";
$stmt = $conn->prepare($sql);
$stmt->execute([ 'col' => $col , 'tab' => $tab ]);
return $stmt->fetchAllAssociative();
Please i need help to analyze this code . I am bit confuse to interpret what it means . This is not a code i write but some else .
All i need to do is to understand it and able to implement it
somewhere else . Thank you
$sql = "select t0.userid,concat(t3.firstname,',',t3.lastname) as name,count(*) as quizs,sum(if(t0.finalgrade > 0,1,0)) as quiz, sum(t0.finalgrade) as grade";
$sql .= " from mdl_grade_grades t0";
$sql .= " left join mdl_grade_items t1 on( t0.itemid= t1.id and t1.courseid = 37 and (t1.itemname like '%Daily Quiz%' or t1.itemname in ('Mid Term Exam','FINAL EXAM')))";
$sql .= " left join mdl_user t3 on(t3.id=t0.userid)";
$sql .= " where t0.userid >= 480";
$sql .= " group by t3.firstname,t3.lastname";
$res = mysql_query($sql);
$response->totalcount = mysql_num_rows($res);
$sql .= " Order by t3.firstname,t3.lastname";
$sql .= " Limit " .$start ."," .$limit ;
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)){
$attend = $row->gquiz / $row->quizs;
$grade = $row->grade / $row->gquiz;
$response->items[] = array('id' => $row->userid,'name' => $row->name,'attend' => $attend,'grade' => $grade);
}
//
echo json_encode($response);
The function sum(if(t0.finalgrade > 0,1,0)) actually counts the number of records having a finalgrade greater than 0.
The function sum(t0.finalgrade) simply sums the finalgrade of all records.
IF() is a builtin function and it's documented:
IF(expr1,expr2,expr3)
If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL), IF() returns expr2.
Otherwise, it returns expr3.
In your case:
if(t0.finalgrade > 0,1,0)
If final grade is greater than 0 then return 1, else return 0.
Finally, SUM() sums all these zeros and ones.
PHP code does not play any role in this MySQL logic.
this my model code:
function get_ads($page=0, $type, $limit=1, $order=' order by rand()') {
if ($page === 0) {
$page = $this->get_adpage();
$qry = "select * from tbl_ads ";
$qry .= " where status=1 and pages like '%".$page. "%'";
$qry .= " and type = ".intval($type);
$qry .= $order;
$qry .= intval($limit) > 1 ? " limit 0,".$limit : " limit 0,1";
$results = $this->db->query($qry)->result(); return $results;}
}
}
Query like this
SELECT * FROM tbl_ads WHERE STATUS=1 AND pages LIKE '%1%' AND TYPE = 1 ORDER BY RAND() LIMIT 0,1`
Controller code is
function get_ads(){
$this->main_model->get_ads(14,2,1);
}
Its working fine local when uploading to server showing fatal error some times but some times its working fine.
Thanks for your help
Here the solution
$this->db->query($qry)->result() in this instead of result() result_array() for multiple rows or row_array() for single row of result did the trick
I'm attempting to modify a mySQL query (that works) to return a more specific result. I've added a variable to the statement so that it looks for jobID AND UserName. Adding the $userName to the statement breaks it.
I've included the code below with the three variations of the SQL statement for comparison. I'm sure it's something obvious - to everyone but me...
Thanks in advance!
DB
// get all applicants from a User
public function GetAllMyApplications($from=false, $to=false, $user_name)
{
global $db;
$applicants = array();
if ($from >= 0 && $to > 0)
{
$sql_limit = ' LIMIT ' . $from .', ' . $to;
}
else
{
$sql_limit = '';
}
$user_name = "Bob Bobberton"; // reset this var for testing
$sql = 'SELECT * FROM '.DB_PREFIX.'job_applications WHERE job_id = '. $this->mJobId . ' ORDER BY name ASC ' . $sql_limit; // This was the original SQL that worked
$sql = 'SELECT * FROM '.DB_PREFIX.'job_applications WHERE job_id = '. $this->mJobId . ' AND name = ' . $user_name . ' ORDER BY name ASC ' . $sql_limit; // Added "and" $user_name - it breaks
$sql = 'SELECT * FROM '.DB_PREFIX.'job_applications WHERE job_id = '. $this->mJobId . ' AND name = "Bob Bobberton" ORDER BY name ASC ' . $sql_limit; // Replace var with value "Bob Bobberton" and it works
$result = $db->query($sql);
while ($row = $result->fetch_assoc())
{
$applicants[] = array('id' => $row['id'],
'job_id' => $row['job_id'],
'name' => $row['name'],
'email_address' => $row['email_address'],
'message' => str_replace(array("\r\n", "\r", "\n"), "<br />", $row['message']),
'resume_path' => base64_encode($row['resume_path']),
'created_on' => $row['created_on'],
'ip' => $row['ip']);
}
if (isset($applicants))
{
return $applicants;
}else{
return("");
}
}
change this
' AND name = ' . $user_name . ' ORDER BY name ASC '
to
" AND name = '" . $user_name . "' ORDER BY name ASC "
and it will work
The solution provided by Satya is not enough. You should escape your inputs properly.
Assume your $username contains a " character. That will break your SQL statement. So you should use prepared statements or, at least, use the function mysql_real_string_escape().
I am using a Joomla module (ArogaRousel) that was made to display images of another module (AdsManager), and the module displays the following error:
No valid database connection 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 ')) ORDER BY views DESC, id
LIMIT 0, 9' at line 1 SQL=SELECT
*,concat('/images/com_adsmanager/ads/',id,'a.jpg')
as imgUrl FROM root_adsmanager_ads ,
root_adsmanager_adcat as ac WHERE
published=1 AND (ac.adid=id and
ac.catid IN ()) ORDER BY views DESC,
id LIMIT 0, 9
I am not proficient in mysql, but I have found the file where the query is being made.
This is the code where the query is being made
$query = "SELECT *,concat('/images/com_adsmanager/ads/',id,'a.jpg') as imgUrl FROM #__adsmanager_ads "
. $table
. " WHERE published=1 "
. $where
. $ordering
. $limit;
Could any of you, oh knowledgeable humans, indicate the error and the solution?
In response to Bemace here I add the whole function
// Get list of banners
function getAds(&$paramslist){
$where = array();
if ($paramslist['ads'] != '') $where[] = 'id IN (' . modArogarouselAdsmanagerHelper::cleanIds($paramslist['ads']) . ')';
if ($paramslist['categories'] != '') {
$where[] = 'ac.adid=id and ac.catid IN (' . modArogarouselAdsmanagerHelper::cleanIds($paramslist['categories']) . ')';
$table = ' , #__adsmanager_adcat as ac';
}
$where = (count($where) > 0) ? ' AND (' . implode(' OR ', $where) . ')' : '';
if ($paramslist['ordering'] == 1) {
$ordering = ' ORDER BY views DESC, id';
} else if ($paramslist['ordering'] == 2) {
$ordering = ' ORDER BY views ASC';
} else if ($paramslist['ordering'] == 3) {
$ordering = ' ORDER BY id';
} else if ($paramslist['ordering'] == 4) {
$ordering = ' ORDER BY RAND()';
}
$limit = ($paramslist['limit'] != '') ? ' LIMIT 0, ' . ($paramslist['limit']) : '';
$query = "SELECT *,concat('/images/com_adsmanager/ads/',id,'a.jpg') as imgUrl FROM #__adsmanager_ads "
. $table
. " WHERE published=1 "
. $where
. $ordering
. $limit;
$db = &JFactory::getDBO();
$db->setQuery($query);
$adslist = $db->loadObjectList();
$adslist = ($paramslist['mode_dir'] == 'bottom') ? array_reverse($adslist, true) : $adslist;
//print_r($adslist);
return $adslist;
}
The empty IN () right before the ORDER BY is the problem. You'll need to check the code that is setting the $where variable. It appears to be expecting at least one category to be selected but none appear to have been.