i use following to statement to load data form SQL the SELECT query works well until php IF is executed.
i want to use 2 ORDER BY in single statement when if statement is executed i get
Fatal error : Uncaught exception 'PDOException' with message
'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 'AND sca IN (?)'
at line 1' in
C:\Users\Amin\Documents\NetBeansProjects\fetch.php:34 Stack trace:
0 C:\Users\Amin\Documents\NetBeansProjects\fetch.php(34): PDO->prepare('SELECT * FROM a...') #1 {main} thrown in
C:\Users\Amin\Documents\NetBeansProjects\fetch.php on line 34
How do i solve this problem
if (isset($_POST["action"])) {
$query = "SELECT * FROM allpostdata WHERE sts = '1' AND mca='Vehicle' ORDER BY pdt DESC";
if (!empty($_POST['cate'])) {
$query .= " AND sca IN (" . str_repeat("?,", count($_POST['cate']) - 1) . "?)";
} else {
$_POST['cate'] = []; // in case it is not set
}
if (!empty($_POST['brand'])) {
$query .= " AND product_brand IN (" . str_repeat("?,", count($_POST['brand']) - 1) . "?)";
} else {
$_POST['brand'] = []; // in case it is not set
}
if (!empty($_POST['model'])) {
$query .= " AND mdl IN (" . str_repeat("?,", count($_POST['model']) - 1) . "?)";
} else {
$_POST['model'] = []; // in case it is not set
}
if (!empty($_POST['sort'])) {
if ($_POST["sort"][0] == "ASC" || $_POST["sort"][0] == "DESC") { //simplistic whitelist
$query .= " ORDER BY prs " . $_POST['sort'][0];
}
}
$stmt = $conn->prepare($query);
$params = array_merge($_POST['cate'], $_POST['brand'], $_POST['model']);
$stmt->execute($params);
$result = $stmt->fetchAll();
$total_row = $stmt->rowCount();
$output = '';
As already mentioned by #aynber, the order by should be the last clause in your query. Thus, the correct form would be as below:
if (isset($_POST["action"])) {
$query = "SELECT * FROM allpostdata WHERE sts = '1' AND mca='Vehicle'";
if (!empty($_POST['cate'])) {
$query .= " AND sca IN (" . str_repeat("?,", count($_POST['cate']) - 1) . "?)";
} else {
$_POST['cate'] = []; // in case it is not set
}
if (!empty($_POST['brand'])) {
$query .= " AND product_brand IN (" . str_repeat("?,", count($_POST['brand']) - 1) . "?)";
} else {
$_POST['brand'] = []; // in case it is not set
}
if (!empty($_POST['model'])) {
$query .= " AND mdl IN (" . str_repeat("?,", count($_POST['model']) - 1) . "?)";
} else {
$_POST['model'] = []; // in case it is not set
}
$query .= " ORDER BY pdt DESC";
if (!empty($_POST['sort'])) {
if ($_POST["sort"][0] == "ASC" || $_POST["sort"][0] == "DESC") { //simplistic whitelist
$query .= ", prs " . $_POST['sort'][0];
}
}
Related
I converted a bootgrid plugin (code snippet) from mysqli to pdo. The records are retrieved but I can not perform a search. Surprisingly, the mysqli version of the code works just fine (both retrieval and search). Running the query in mysql works just fine so not sure what I am doing wrong.
The function [block] that is generating the errors:
function getRecords($params) {
$sql = $sqlRec = $sqlTot = $where = '';
$rp = isset($params['rowCount']) ? $params['rowCount'] : 10;
if (isset($params['current'])) {
$page = $params['current'];
} else {
$page = 1;
};
$start_from = ($page - 1) * $rp;
if (!empty($params['searchPhrase'])) {
$where .= "WHERE";
$where .= "name LIKE '" . $params['searchPhrase'] . "%' ";
}
if (!empty($params['sort'])) {
$where .= " ORDER By " . key($params['sort']) . ' ' . current($params['sort']) . " ";
}
// getting all records without any search
$sql = "select * from students";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if (isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
if ($rp != -1) {
$sqlRec .= " LIMIT " . $start_from . "," . $rp;
}
$qtot = $this->conn->prepare($sqlTot);
$qtot->execute();
$queryRecords = $this->conn->prepare($sqlRec);
$queryRecords->execute();
while ($row = $queryRecords->fetch(PDO::FETCH_ASSOC)) {
$this->data[] = $row;
}
$json_data = array(
"current" => intval($params['current']),
"rowCount" => 10,
"total" => intval($qtot->rowCount()),
"rows" => $this->data // total data array
);
return $json_data;
}
Error log from the console:
Uncaught 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 '' at line 1 in ..\inc\process.php:95
Stack trace:
#0 ..\process.php(95): PDOStatement->execute()
#1 ..\process.php(27): Candidate->getRecords(Array)
#2 {main}
thrown in <b>..\process.php</b> on line <b>95</b><br />```
I have the following code but i am not sure how to check if insert is success. execute returns resource id. I would like to check if success and return all errors on fail.
public function persist()
{
$update = FALSE;
if(!is_array($this->tablePrimaryKey)) {
if(!empty($this->fieldVals[$this->tablePrimaryKey])) {
$update = true;
}
}
if ($update) {
$sql = "UPDATE " . $this->tableName . " SET ";
$binds = [];
foreach ($this->fieldVals as $key=>$val) {
if ($key != $this->tablePrimaryKey) {
if(in_array($key, $this->DATE_IDS)) {
$sql .= '"' . strtoupper($key) . '" = sysdate,';
} else {
$bind = 't_' . $key;
$binds[$bind] = $val;
$sql .= '"' . strtoupper($key) . '" = :' . $bind . ',';
}
}
}
$sql = substr($sql,0,-1);
$sql .= " WHERE " . $this->tablePrimaryKey . " = '" . $this->fieldVals[$this->tablePrimaryKey] ."'";
} else {
$binds = $fields = $date_fields = [];
if(!empty($this->tablePrimaryKey) && !is_array($this->tablePrimaryKey)) {
$this->fieldVals[$this->tablePrimaryKey] = $this->generateNewPrimaryKey();
}
foreach ($this->fieldVals as $key=>$val) {
$bind = ':t_' . $key;
if (in_array($key, $this->DATE_IDS)) {
$date_fields[] = strtoupper($key);
} else {
$binds[$bind] = $val;
$fields[] = strtoupper($key);
}
}
$sql = 'INSERT INTO ' . $this->tableName . '("' . implode('","', $fields);
if(count($date_fields) >0) {
$sql .= '","';
$sql .= implode('","', $date_fields);
}
$sql.='") VALUES (' . implode(',', array_keys($binds));
if(count($date_fields) >0) {
$cnt=0;
foreach($date_fields as $date) {
$cnt++;
if(preg_match('/NULL/i', $this->fieldVals[strtolower($date)], $result)) {
$sql .= ",NULL";
} elseif(isset($this->fieldVals[strtolower($date)])) {
$sql .= ",TO_DATE('" . (new DateTime($this->fieldVals[strtolower($date)]))->format("Y-M-d H:i:s") . "', 'yyyy/mm/dd hh24:mi:ss')";
} else {
$sql .= ",sysdate";
}
}
}
$sql .= ')';
}
$this->oiDb->parse($sql, $binds);
return $this->oiDb->execute();
}
I run $result = $oiRequests->hydrate($reportingRequest)->persist();. $reportingRequest is key,value pair of columns/values. $result contains resource id. $oiRequests is my model.
I have tried
$num_rows = oci_fetch_assoc ($result);
print_r($num_rows);
returns
Warning: oci_fetch_assoc(): ORA-24374: define not done before fetch or execute and fetch in /var/SP/oiadm/docroot/dev/uddins/requestportal/requestportal_ajax.php on line 65
Most of the OCI functions return false on error. This means you can do a simple check on the return value and, if it's false, call oci_error().
For the specific case of checking if an INSERT statement worked you can reference the example code for oci_commit(). The relevant part of that example is duplicated here:
// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1. The two flags are equivalent
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
This code down here should search database. but I am getting error that my table doesnt exists. And also I want to ask why if I push second time submit button it just jumps to else so it echo choose at least.... and also all data from database. Thanks!
Here is php
if (isset($_POST['submit'])) {
$query = 'SELECT * FROM station_tab';
if (!empty($_POST['station_name']) && !empty($_POST['city']) && !empty($_POST['zone']))
{
$query .= 'WHERE station_name' .mysql_real_escape_string($_POST['station_name']) . 'AND city' . mysql_real_escape_string($_POST['city']) . 'AND zone' . mysql_real_escape_string($_POST['zone']);
} elseif (!empty($_POST['station_name'])) {
$query .= 'WHERE station_name' . mysql_real_escape_string($_POST['station_name']);
} elseif (!empty($_POST['city'])) {
$query .= 'WHERE city' . mysql_real_escape_string($_POST['city']);
} elseif (!empty($_POST['zone'])) {
$query .= 'WHERE zone' . mysql_real_escape_string($_POST['zone']);
} else {
echo "Choose at least one option for search";
}
$result = mysql_query($query, $db) or die(mysql_error($db));
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)){
echo '<br/><em>' .$row['station_name'] . '</em>';
echo '<br/>city: '. $row['city'];
echo '<br/> zone: ' .$row['zone'];
echo '<br/> Long: ' .$row['lon'];
echo '<br/> Lat: ' . $row['lat'];
}
}
}
here is error message when I add name of the city to city.
Table 'stanice_tab.station_tabwhere' doesn't exist
Here is your corrected code:
$query = 'SELECT * FROM station_tab '; // note the space at the end
if (!empty($_POST['station_name']) && !empty($_POST['city']) && !empty($_POST['zone'])) {
$query .= ' WHERE station_name = "' .mysql_real_escape_string($_POST['station_name']) . '" AND city = "' . mysql_real_escape_string($_POST['city']) . '" AND zone = "' . mysql_real_escape_string($_POST['zone']).'"'; // note the = signs and the space before each AND
} elseif (!empty($_POST['station_name'])) {
$query .= ' WHERE station_name = "' . mysql_real_escape_string($_POST['station_name']).'"'; // note the = sign and the space at the beginning
} elseif (!empty($_POST['city'])) {
$query .= ' WHERE city = "' . mysql_real_escape_string($_POST['city']).'"'; // note the = sign and the space at the beginning
} elseif (!empty($_POST['zone'])) {
$query .= ' WHERE zone = "' . mysql_real_escape_string($_POST['zone']).'"'; // note the = sign and the space at the beginning
} else {
echo "Choose at least one option for search";
}
Take the habit of echoing your $query variable so concatenation does not add any typo mistakes.
in phpmyadmin select the database and then select your table
and in menu above there is a sql menu. you can use this functionality to construct sql queries or debug when there are errors like this
I'm using SensioLabsInsight to profile any vulnerabilities in my code.
I've received several errors for possible sql injection, and it recommends using parameter binding with PDO. This is fine since I'm already using PDO for my db driver.
Right now my model is passed a $data array and then checks for specific values in the array in order to add to the sql query if present, like so:
public function getDownloads($data = array()) {
$sql = "
SELECT *
FROM {$this->db->prefix}download d
LEFT JOIN {$this->db->prefix}download_description dd
ON (d.download_id = dd.download_id)
WHERE dd.language_id = '" . (int)$this->config->get('config_language_id') . "'";
if (!empty($data['filter_name'])) {
$sql .= " AND dd.name LIKE '" . $this->db->escape($data['filter_name']) . "%'";
}
$sort_data = array(
'dd.name',
'd.remaining'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql .= " ORDER BY " . $data['sort'];
} else {
$sql .= " ORDER BY dd.name";
}
if (isset($data['order']) && ($data['order'] == 'DESC')) {
$sql .= " DESC";
} else {
$sql .= " ASC";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->rows;
}
The error referenced from the SensioLabsInsight analysis references only the $data['sort'] clause as being a possible injection point.
My question is, do I need to test for $data array presence when creating a prepare statement, or will it simply return null if the array value is empty.
My proposed new query with parameter binding would look like so:
public function getDownloads($data = array()) {
$sql = "
SELECT *
FROM {$this->db->prefix}download d
LEFT JOIN {$this->db->prefix}download_description dd
ON (d.download_id = dd.download_id)
WHERE dd.language_id = '" . (int)$this->config->get('config_language_id') . "'";
if (!empty($data['filter_name'])) {
$sql .= " AND dd.name LIKE :filter_name%";
}
$sort_data = array(
'dd.name',
'd.remaining'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql .= " ORDER BY :sort";
} else {
$sql .= " ORDER BY dd.name";
}
if (isset($data['order']) && ($data['order'] == 'DESC')) {
$sql .= " DESC";
} else {
$sql .= " ASC";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT :start, :limit";
}
$this->db->prepare($sql);
$this->db->bindParam(':filter_name', $data['filter_name']);
$this->db->bindParam(':sort', $data['sort']);
$this->db->bindParam(':start', $data['start'], PDO::PARAM_INT);
$this->db->bindParam(':limit', $data['limit'], PDO::PARAM_INT);
$query = $this->db->execute();
return $query->rows;
}
Will this work as is, or do the parameter bindings need to be moved within the if/else conditionals?
$db contains the connection to the database.
I am getting the Error in The foreach statement.
Error Message :
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number' in /home/a5057270/public_html/insert2.php:33 Stack trace: #0 /home/a5057270/public_html/insert2.php(33): unknown() #1 {main} thrown in /home/a5057270/public_html/insert2.php on line
Here's The PHP code :
$date = $_GET['date'];
$time = $_GET['time'];
$mode = $_GET['mode'];
$tfno = $_GET['tfno'];
$params = array(':date' => $date);
$query = "SELECT * FROM cabs WHERE DATE=':date' ";
if ($mode!=='' || $mode!=="") {
$query .="AND MODE=':mode' ";
$params[':mode'] = $mode;
}
if ($tfno!=='') {
$query .="AND TFNO=':tfno' ";
$params[':tfno'] = $tfno;
}
$query .="ORDER BY TIME";
$req = $db->prepare($query);
$req->execute($params);
//Build Result String
$display_string = "<article class='container box style3'><section><header><h3><u><b>Here Are The Results...!!</u></b></h3></header><div class='table-wrapper'><table class='default'><thead><tr><th>ID</th><th>Name</th><th>Description</th><th>Contact No.</th></tr></thead><tbody>";
// Getting Error in the line Below
foreach ($req as $row) {
$display_string .="<tr><td>" . $row[IDNO] . "</td><td>" . $row[NAME] . "</td><td><ul><li> Date : " . $row[DATE] . "</li><li> Time : " . $row[TIME] . "</li><li>
Train/Flight No. " . $row[TFNO] . "</li></ul></td><td>" . $row[CONTACT] . "</td></tr>";
}
$display_string .= "</table>";
that's because you are putting '' around your PDO vars...
remove them and all is good. example: make ':mode' => :mode with no '' and it will work.
$params = array(':date' => $date);
$query = "SELECT * FROM cabs WHERE DATE=:date "; //No '' here
if ($mode!=='' || $mode!=="") {
$query .="AND MODE=:mode "; //No '' here
$params[':mode'] = $mode;
}
if ($tfno!=='') {
$query .="AND TFNO=:tfno ";//No '' here
$params[':tfno'] = $tfno;
}