PHP Error Call to undefined function RecordCount() - prepared-statement

I'm fairly new to PHP and have been trying to make a simple login using PHP PDO. When I try and login it keeps throwing this error - Call to undefined function RecordCount(). My searching has provided no insight as to why this is happening. My code is below. Any insight into where to look or why this is happening would be appreciated. Thanks!
<?php
include_once '../utils/dbcon.php';
$stmt = $dbc->prepare("SELECT username,password FROM users where username = ? AND password = ?");
if ($stmt->execute(array($_GET['username'],$_GET['password'])))
{
if ($stmt.RecordCount())
{
echo "record found";
}
elseif(!$stmt.RecordCount())
{
echo "No records found";
}
}
?>

Your syntax is wrong:
$stmt.RecordCount()
should be
$stmt->RecordCount()

Related

I got a 500 error when I use guzzle but with curl I dont get one

I have an Openhab system on a PI and a REST API and I want to display information on a TV-Screen.
I have tried to do it with a curl and it worked. So now I want to do the same with Guzzle.
First I only installed composer and guzzle in the Project directory on my PC, Then I also installed them on the PI. Neither approach worked as I got a 500 error on both attempts.
function getCurrentTemp() {
echo "test1";
$client = new GuzzleHttp\Client([
'base_uri'=>'http://fernseher/'
]);
echo "test2";
$return = $client->request('GET','http://openhab.clubdrei.com/rest/items/ThermostateTemp/state', ['auth' => ['User','Password']]);
echo $return;
}
I think the creating Client break up the script
I need your help,
Thank you
500 basically means that there is a server error. Please attach the cURL command that is successful (as you mentioned in the question's title).
I also modified your code a bit, to be sure that you are are working with the body content of the response (->getBody()->getContents() part):
function getCurrentTemp()
{
// You don't need 'base_uri' here, because you use absolute URL below
$client = new GuzzleHttp\Client();
$response = $client->request(
'GET',
'http://openhab.clubdrei.com/rest/items/ThermostateTemp/state',
['auth' => ['User','Password']]
);
return $response->getBody()->getContents();
}

Cakephp 2.5.4: Database Error Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

I want to show error for database in cakephp. How can I display a message of "sql error" to the users. This is my code. In this code, I am getting Database Error. But I want to show proper message to the user instead of database error.
public function edit_mothertongue(){
$motherTongue=array();
if($this->request->is('post')){
foreach ($this->request->data as $key => $value) {
$motherTongue[$key]=$value;
}
if(!empty($motherTongue)){
App::import('Model','MotherTongue');
$this->MotherTongue=new MotherTongue();
try{
if($this->MotherTongue->save($motherTongue)){
echo "Record saved";
}else{
echo "Record not saved";
}
}
catch(Exception $e){
echo $e->getMessage(); // I want to display error message of sql.
}
}
}
}
When you want to display information, you need to use a view. To pass information from the controller to the view use the set method.
$this->set('errormsg', $e->getMessage());
Then use $errormsg in your view.
If you want to use AJAX you can set it like this:
$this->set('_serialize', array('errormsg'));
If you are looking for an output in JSON
However using AJAX is out of scope of this question.

Drupal: Running Feeds Importer Programatically - Where to Put Code

When running a feeds importer using Cron, the importer times out resulting in an incomplete import. I'm trying to use a script to execute the importer and I've come across this code a few times:
<?php
function MODULE_NAME_cron() {
$name = 'FEED_NAME';
$source = feeds_source($name);
$source->import();
}
?>
However, when executing this I get an error saying there's no feeds_source() function, which leads me to believe that I just don't know where to put this code (a separate php file just isn't working for me). Can anyone help me out here? Thanks in advance!
I think you need to call $source->startImport(); method instaed of $source->import();
I just posted an answer to a similar question over here: https://drupal.stackexchange.com/questions/90062/programmatically-execute-feed-import/153434#153434 , which might help. in short, in the a form submit hook if your using the batch api, or dont use the batch api if you're doing it non browser (install hook , install profile)
so in your case
function load_data(){
// Files to import in specific order.
$files = array(
'challenge_importer' => 'data/challenges.csv',
);
$file_location_base = drupal_get_path('module', 'challenge');
foreach ($files as $feed => $file) {
$feedSource = feeds_source($feed);
// Set the file name to import
$filename = $file_location_base.'/' . $file;
if (!file_destination($filename, FILE_EXISTS_ERROR)) {
$config = $feedSource->getConfig();
$config['FeedsFileFetcher']['source'] = $filename;
$feedSource->setConfig($config);
$feedSource->save();
while (FEEDS_BATCH_COMPLETE != $feedSource->import());
}
}
}
could be called from the cron , or use the scheduled execution from the feeds importer

Debugging SQL in controller

I am trying to debug my sql but I am having a hard time. I know I can use this:
<?php echo $this->element('sql_dump'); ?>
to dump the sql but this doesnt (or at least I dont know how to use it) work if I am doing an ajax call. Because the page is not reloaded, the dump does not get refreshed. How can I run my command and debug the sql? Here is the code I have in my controller:
public function saveNewPolicy(){
$this->autoRender = false;
$policyData = $this->request->data["policyData"];
$numRows=0;
$data = array(
'employee_id' => trim($policyData[0]["employeeId"]),
'insurancetype_id'=> $policyData[0]["insuranceTypeId"],
'company' => $policyData[0]["companyName"],
'policynumber' => $policyData[0]["policyNumber"],
'companyphone' => $policyData[0]["companyPhone"],
'startdate'=> $policyData[0]["startDate"],
'enddate'=> $policyData[0]["endDate"],
'note' => $policyData[0]["notes"]
);
try{
$this->Policy->save($data);
$numRows =$this->Policy->getAffectedRows();
if($numRows>0){
$dataId = $this->Policy->getInsertID();
$response =json_encode(array(
'success' => array(
'msg' =>"Successfully Added New Policy.",
'newId' => $dataId
),
));
return $response;
}else{
throw new Exception("Unspecified Error. Data Not Save! ");
}
}catch (Exception $e){
return $this->EncodeError($e);
}
}
The problem is that if the company field in my array is empty, empty, the insert will fail without any error. I know it has failed, though, because of the numrows variable I use. I know the field accepts nulls in the database. It seems like the only way for me to debug this is to look at what SQL is being sent to MySql. Anyone know how to debug it? I am using CakePhp 2.4
I use this approach. I added this method in my AppModel class:
public function getLastQuery() {
$dbo = $this->getDatasource();
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
and then in any controller you call this like:
debug($this->{your model here}->getLastQuery());
Rather than trying to hack around in CakePHP, perhaps it would be easier to just log the queries with MySQL and do a tail -f on the log file? Here's how you can turn that on:
In MySQL, run SHOW VARIABLES; and look for general_log and general_log_file entries
If general_log is OFF, run SET GLOBAL general_log = 'ON'; to turn it on
In a terminal, run a tail -f logfile.log (log file location is in the general_log_file entry) to get a streaming view of the log as it's written to
This is very helpful for these circumstances to see what's going on behind the scenes, or if you have debug off for some reason.

Data determined by URI

So at the moment, my CI website is formatted to take part of the URI, let's say an id, and find a result in the database from it to display on the page.
If I enter an id that is not in the database however, naturally I am going to get a database error. Is there a better way of protecting my URI's from direct db access, and, what would be the best method to tell the user that the URL they entered is invalid?
imo you should not only display a error, but also throw a 404 (or 301, depends on your application) for SEO reasons
a simple implementation:
MY_Controller.php
...
protected function error404()
{
set_status_header(404);
$data = array();
$this->load->view('error404_view', $data);
}
examplecontroller.php
...
$data = $this->Some_model->get_by_id($id);
if (empty($data))
{
$this->error404();
}
else
{
// your view here
}
...
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Suppose your id is stored in $id. Then you can do something like this.
if() // if $id not found - depends how you are doing check
{
$errorMsg = "Not found";
$this->session->set_flashdata('errorMsg', $errorMsg );
redirect('home'); //Redirect to the page which is always available and display flashdata with error message here
}

Resources