I have this save method in my model:
public function save($data = null, $whiteList = null){
$res = false;
$sql = '';
$di = \Phalcon\DI::getDefault();
try {
$param = array("[fecha] = to_date('" . $this->fecha . "', 'YYYY-MM-DD HH24:MI:SS') and [parametro_id] = :parametro_id:",
"bind" => array("parametro_id" => $this->parametro_id) );
$primero = Instantaneos::findFirst($param);
if ($primero){
$this->instantaneo_id = $primero->instantaneo_id;
} else {
$sql = "select AZUL_S_INSTANTANEOS.nextval from dual";
$result = $di->getShared('db')->query($sql);
while($row = $result->fetchArray()){
$this->instantaneo_id = $row['NEXTVAL'];
}
}
$this->fecha = date('d/M/y', strtotime($this->fecha));
$res = parent::save($data, $whiteList);
$res = true;
} catch (Exception $ex) {
$res = false;
$this->appendMessage(new Message($ex->getMessage()));
}
return $res;
}
And it works, but, when I modify this line:
$this->fecha = date('d/M/y', strtotime($this->fecha));
With this one:
$this->fecha = date('d/M/y H:i:s', strtotime($this->fecha));
I get this error:
SQLSTATE[HY000]: General error: 1830 OCIStmtExecute: ORA-01830: date format picture ends before converting entire input string
(ext\pdo_oci\oci_statement.c:148)
And I need to save the time information, I try to make my own save method, with no parent::save, writing my own sql when insert or update:
$sql_i = "insert into AZUL_INSTANTANEOS values(%d,%d,to_date('%s', 'YYYY-MM-DD HH24:MI:SS'),%f,'%s')";
$sql_u = "update AZUL_INSTANTANEOS set val = %f, valf = '%s' where instantaneo_id = %d";
And using:
$db->execute($sql);
But I get another error:
Maximum execution time of 30 seconds exceeded in <b>\app\config\services.php</b> on line <b>172</b><br />
I'm using:
XAMPP 1.8.2 (PHP Version 5.4.31, Apache/2.4.10 (Win32))
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
Phalcon 2.1.0b
¿Any advice?, thx.
Oracle is not fully supported in Phalcon. There is a driver in the incubator located here that you can utilize.
Oracle also has a different syntax that Phalcon's PHQL potentially cannot recognize.
I would suggest you start by adding SQL statement logging to your application, so that you can see what is being sent to the database and then figure out how to correct it.
Have a look at this page and scroll down to where it says Logging SQL Statements
Add that and have a look at what is going on with your query.
Related
I'm getting this error when I'm trying to edit data using CodeIgniter.
My controller:
public function edit_data($kode_part)
{
$tabel_part = $this->model_tabel_part->get_tabel_part("where kode_part ='$kode_part'");
foreach($tabel_part->result_array()as $row){
$kode_part = $row['kode_part'];
$nama_part = $row['nama_part'];
$warna_part = $row['warna_part'];
$cavity = $row['cavity'];
$gross = $row['gross'];
}
$data['kode_part'] = $kode_part;
$data['nama_part'] = $nama_part;
$data['warna_part'] = $warna_part;
$data['cavity'] = $cavity;
$data['gross'] = $gross;
$this->load->view('datamaster/tabel_part/v_edit_part', $data);
}
My Model:
public function get_tabel_part($where = ""){
$data_tabel_part = $this->db->query("select * from tabel_part".$where);
return $data_tabel_part;
}
And I'm getting this error:
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '='34232-C0100'' at line 1
select * from tabel_partwhere kode_part ='34232-C0100'
Filename: C:/xampp/htdocs/tpidbv1.1/system/database/DB_driver.php
Line Number: 691
Can you find any thing wrong here?
Your Error message is this...
select * from tabel_partwhere kode_part ='34232-C0100'
There is No Space between the table name and your "where" statement.
So in your model you need to add in a space in your SQL...
So this...
$data_tabel_part = $this->db->query("select * from tabel_part".$where);
Becomes this...
$data_tabel_part = $this->db->query("select * from tabel_part ".$where); // Added Space
Please add a space between the table name and the where clause.
public function get_tabel_part($where = ""){
$data_tabel_part = $this->db->query("select * from tabel_part ".$where);
return $data_tabel_part;
}
I have spent nearly two days going in circles on this one.
I seem to have difficulty using $_SESSION or $_POST as strings in any query or converting them to strings to use.
I am using a simple hash approach to login to a site.
Extract from script is
<?php
session_start();
echo "******Running Authenticate<br>";
echo "data submitted<br>".$_POST['site_login']."<br>".$_POST['site_password']."<br><br>";
$SiteLogin = $_POST['site_login']
$_SESSION['site_login'] = $_POST['site_login'];
$_SESSION['site_password'] = $_POST['site_password'];
$_SESSION['session_id'] = session_id();
$_SESSION['Now_val'] = date('Y-m-d H:i:s');
//include 'showallvars.php';
include 'dbconfig.php';
// Prepare our SQL
if ($stmt = $con->prepare('SELECT site_index, site_password FROM web_sites WHERE site_login = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['site_login']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the account exists in the database.
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
echo "account exists";
}
else
{
header('Location: badindex.php');
}
if (password_verify($_POST['site_password'], $password)) {
// Verification success! User has loggedin!
echo "password good";
}
else
{
header('Location: badindex.php');
}
}
$_SESSION['loggedin'] = TRUE;
?>
that works fine
BUT there is another field ( 'site_name') in the record which i want to carry forward.
This should be easy !!
and there is a dozen ways of doing it
for example the "standard" example is something like
$name = $mysqli->query("SELECT site_name FROM web_sites WHERE site_login = 'fred'")->fetch_object()->site_name;
That works fine
but no matter how i try - concatenating or or ... I cannot get $_SESSION['site_login'] or $_POST['site_login'] to replace 'fred'.
There seems to be white space added in.
Assistance or guidance ?
It should be possible to as easy as doing the following:
So:
if ($stmt = $con->prepare('SELECT site_index, site_password
FROM web_sites WHERE site_login = ?')) {
becomes:
if ($stmt = $con->prepare('SELECT site_index, site_password, site_login
FROM web_sites WHERE site_login = ' . $SiteLogin)) {
Do note, it is bad practice to do directly parse $SiteLogin to a query, because now someone can SQL Inject this and hack your website. All they need to do is use your form and figure out that which field is responsible for $SiteLogin. You would need to escape your $SiteLogin. Assuming Mysqli, it would become:
if ($stmt = $con->prepare('SELECT site_index, site_password, site_login
FROM web_sites WHERE site_login = ' . $con->real_escape_string($SiteLogin))) {
Thank you for that BUT the instant I saw the curly brackets in your answer - it all came flooding back to me. I had forgotten that PHP has problems with the square brackets
$sql = ("SELECT site_name FROM web_sites WHERE site_login = '". $_SESSION{'site_login'} ."' LIMIT 1");
I KNEW it was easy !
Your comments on injection are of course correct but this was an edited code excerpt and $SiteLogin was just added in as a "temporary working variable if needed"
I have javascript function that populates datatable using Ajax. My javascript code looks like :
$('#results').dataTable({
// Ajax load data
"ajax": {
"url": "get_intl_tickets",
"type": "POST",
"data": {
"user_id": 451,
"csrfmiddlewaretoken" : csrftoken,
}
}
})
My server side script in django has a function that loads around 500 data rows. Now the problem is that I don't want to load whole data at a time. Instead I want to have first 10 data rows. Then with pagination, another 10 rows like that.
I read the page server side processing documentation of datatables. I tried with "serverSide": true option as well. I am not understanding server side script. There is given an example of PHP. It seems that they are not using any parameters like draw, recordsFiltered, recordsTotal there. There they have used php SSP class. And it is unknown what does it do. I am trying to implement it in django.
But I am not finding proper good documentation to implement. Any help will be appreciated.
Old question but one I also had a surprisingly difficult time finding an answer to, so in case anyone else ends up here... :P
I found this 2020 article very helpful, specifically part 6 showing the "complete code" that includes getting the correct variables, building the SQL query, and how to build/structure the data object that it responds with:
https://makitweb.com/datatables-ajax-pagination-with-search-and-sort-php/
Their example posted below:
<?php
## Database configuration
include 'config.php';
## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = mysqli_real_escape_string($con,$_POST['search']['value']); // Search value
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " and (emp_name like '%".$searchValue."%' or
email like '%".$searchValue."%' or
city like'%".$searchValue."%' ) ";
}
## Total number of records without filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee");
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];
## Total number of record with filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];
## Fetch records
$empQuery = "select * from employee WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = mysqli_query($con, $empQuery);
$data = array();
while ($row = mysqli_fetch_assoc($empRecords)) {
$data[] = array(
"emp_name"=>$row['emp_name'],
"email"=>$row['email'],
"gender"=>$row['gender'],
"salary"=>$row['salary'],
"city"=>$row['city']
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
echo json_encode($response);
Nice exemple:
https://datatables.net/examples/server_side/defer_loading.html
But you need edit server side.
Response demo
{
draw:2,
recordsFiltered:57,
recordsTotal:57
}
After upgrade from 2.4.6 to 2.5 users get logged out every hour or two, though ttl is not that small. Switching back fixes the problem.
framework:
session:
name: SESSID
handler_id: session.handler.pdo
cookie_lifetime: 259200
Login is done with ajax.
$token = new UsernamePasswordToken($user, $user->getPassword()/* null */,
'main', $user->getRoles());
$this->get('security.context')->setToken($token);
$event = new InteractiveLoginEvent($this->getRequest(), $token);
$this->get('event_dispatcher')->dispatch(SecurityEvents::INTERACTIVE_LOGIN, $event);
Does anyone know about changes to symfony which could cause this? Or better and still simple way to log in?
I encountered this problem and I solved it by setting a value to gc_maxlifetime in config.yml. For that, I had a look to PdoSessionHandler.php and in the read method:
public function read($sessionId)
{
$this->beginTransaction();
try {
$this->lockSession($sessionId);
// We need to make sure we do not return session data that is already considered garbage according
// to the session.gc_maxlifetime setting because gc() is called after read() and only sometimes.
$maxlifetime = (int) ini_get('session.gc_maxlifetime');
$sql = "SELECT $this->dataCol FROM $this->table WHERE $this->idCol = :id AND $this->timeCol > :time";
$stmt = $this->pdo->prepare($sql);
$stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
$stmt->bindValue(':time', time() - $maxlifetime, \PDO::PARAM_INT);
$stmt->execute();
// We use fetchAll instead of fetchColumn to make sure the DB cursor gets closed
$sessionRows = $stmt->fetchAll(\PDO::FETCH_NUM);
if ($sessionRows) {
return base64_decode($sessionRows[0][0]);
}
return '';
} catch (\PDOException $e) {
$this->rollback();
throw $e;
}
}
I looked especially these two lines:
$maxlifetime = (int) ini_get('session.gc_maxlifetime');
and
$stmt->bindValue(':time', time() - $maxlifetime, \PDO::PARAM_INT);
So, I have defined in config.yml:
session:
handler_id: session.handler.pdo
cookie_lifetime: 259200
gc_maxlifetime: 259200
I think that default php.ini value is taken for gc_maxlifetime if it is not defined (here $maxlifetime). So when user is inactive more than gc_maxlifetime, he is disconnected. cookie_lifetime will force user to be disconected after cookie_lifetime seconds.
PS: In Symfony 2.4 there was this code where gc_maxlifetime was not used:
public function read($sessionId)
{
$sql = "SELECT $this->dataCol FROM $this->table WHERE $this->idCol = :id";
try {
$stmt = $this->pdo->prepare($sql);
$stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
$stmt->execute();
// We use fetchAll instead of fetchColumn to make sure the DB cursor gets closed
$sessionRows = $stmt->fetchAll(\PDO::FETCH_NUM);
if ($sessionRows) {
return base64_decode($sessionRows[0][0]);
}
return '';
} catch (\PDOException $e) {
throw new \RuntimeException(sprintf('PDOException was thrown when trying to read the session data: %s', $e->getMessage()), 0, $e);
}
}
I've created a J2.5 component with some config fields using config.xml in the admin folder of the component.
How can I set parameters in the config programatically?
I've tried the code bellow, but it obviously doesn't save the result to the DB:
$params = & JComponentHelper::getParams('com_mycomponent');
$params->set('myvar', $the_value);
Could anyone please show some examples of how to achieve this?
The safest way to do this would be to include com_config/models/component.php and use it to validate and save the params. However, if you can somehow validate the data params yourself I would stick with the following (much more simple solution):
// Get the params and set the new values
$params = JComponentHelper::getParams('com_mycomponent');
$params->set('myvar', $the_value);
// Get a new database query instance
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Build the query
$query->update('#__extensions AS a');
$query->set('a.params = ' . $db->quote((string)$params));
$query->where('a.element = "com_mycomponent"');
// Execute the query
$db->setQuery($query);
$db->query();
Notice how I cast the params to a string (when building the query), it will convert the JRegistry object to a JSON formatted string.
If you get any caching problems, you might want to run the following after editing the params:
From a model:
$this->cleanCache('_system');
Or, else where:
$conf = JFactory::getConfig();
$options = array(
'defaultgroup' => '_system',
'cachebase' => $conf->get('cache_path', JPATH_SITE . '/cache')
);
$cache = JCache::getInstance('callback', $options);
$cache->clean();
The solution is here...
http://www.webtechriser.com/tutorials/82-joomla-3-0/86-how-to-save-component-parameters-to-database-programmatically
You can replace in Joomla 2.5+ the
// check for error
if (!$table->check()) {
$this->setError('lastcreatedate: check: ' . $table->getError());
return false;
}
if (!$table->store()) {
$this->setError('lastcreatedate: store: ' . $table->getError());
return false;
}
with
if (!$table->save()) {
$this->setError('Save Error: ' . $table->getError());
return false;
}