Message: mysql_real_escape_string() expects parameter 2 to be resource, boolean given Filename: mysql/mysql_driver.php Line Number: 346 - mysql-real-escape-string

I am using the following code to select from a MySQL database with a Code Igniter webapp:
My Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class m_login extends CI_Model{
function __construct(){
parent::__construct();
}
public function validate(){
// grab user input
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
$password = md5($password);
// Run the query
//$array = array('nip' => $this->db->escape_str($username), 'password' => $this->db->escape_str($password));
//$this->db->select('pegawai.NIP, akun.PASSWORD, akun.ROLE');
//$this->db->from('pegawai');
//$this->db->join('akun', 'akun.ID_PEGAWAI = pegawai.ID_PEGAWAI');
//$this->db->get_where('nip', $username);
//$this->db->where($array);
//$this->db->where('PASSWORD', 'd93591bdf7860e1e4ee2fca799911215');
//$query = $this->db->get();
$sql = "SELECT NIP, PASSWORD, ROLE FROM pegawai LEFT JOIN akun ON pegawai.ID_PEGAWAI=akun.ID_PEGAWAI WHERE pegawai.NIP=('".$this->db->escape_str($username)."') AND akun.PASSWORD=('".$this->db->escape_str($password)."')";
$this->db->query($sql);
//$query = $this->db->query("SELECT NIP, PASSWORD, ROLE FROM pegawai LEFT JOIN akun ON pegawai.ID_PEGAWAI=akun.ID_PEGAWAI WHERE pegawai.NIP='$username' AND akun.PASSWORD='$password'");
// Let's check if there are any results
//var_dump($this->db);
//var_dump($username);
if($query->num_rows == 1)
{
//If there is a user, then create session data
$row = $query->row();
$data = array(
'role' => $row->role,
'nip' => $row->nip,
'validated' => true
);
$this->session->set_userdata($data);
return true;
}
//If the previous process did not validate
//then return false.
return false;
}
}
?>
I have error like this
A PHP Error was encountered
Severity: Warning
Message: mysql_real_escape_string() expects parameter 2 to be resource, boolean given
Filename: mysql/mysql_driver.php
Line Number: 346
Backtrace:
File: C:\xampp\htdocs\simpeg\application\models\m_login.php
Line: 27
Function: escape_str
File: C:\xampp\htdocs\simpeg\application\controllers\login.php
Line: 26
Function: validate
File: C:\xampp\htdocs\simpeg\index.php
Line: 292
Function: require_once
Most likely, this is a syntax error, but I just can't figure out which part of my code is responsible.
I've also gone through the Queries section of the user guide of CodeIgniter, but it wasn't explained clearly there.
Can anyone please tell me where my mistake is, and what is the correct syntax for what I'm trying to do?

Related

Yii, already define index but `Undefined Index`

I have already properly defined the index to be POST-ed but still it says Undefined Index
Below is my code:
in the _form.php:
<?php echo $form->labelEx($model,'clientPackagedService_id'); ?>
<?php $client = Client::model()->findByPk(1);?>
<?php echo $form->dropDownList($model, 'clientPackagedService_id', CHtml::listData($client->clientPackagedservices(array('condition'=>'client_id='.$client->id.' AND booking_id IS NULL')),'id','packagedServiceInfo'),
array(
'disabled'=>'disabled',
'prompt'=>'Select Packaged Service...',
'ajax' => array( 'type'=>'POST', //request type
'url'=>CController::createUrl('updateMasseuseAndStationListPSID'), //url to call.
//This line-> 'data'=>array('clientPackagedService_id'=>'js:this.value', 'dt'=>'js:$("#Booking_date").val()', 'timeStart'=>'js:$("#Booking_timeStart").val()'),
'dataType'=>'json',
'success'=>'js:function(data) {
//alert(data.masseuse);
var mass="#'.CHtml::activeId($model, 'masseuse_id').'";
$(mass).html(data.masseuse);
$(mass).trigger("chosen:updated");
$(mass+"_chzn").css("width","300px");
$(mass+"_chzn > .chzn-drop").css("width","298px");
var station="#'.CHtml::activeId($model, 'station_id').'";
$(station).html(data.station);
$(station).trigger("chosen:updated");
$(station+"_chzn").css("width","300px");
$(station+"_chzn > .chzn-drop").css("width","298px");
//alert(data.timeEnd);
var timeEnd="#'.CHtml::activeId($model, 'timeEnd').'";
$(timeEnd).val(data.timeEnd);
}',
)
)
); ?>
in the controller.php:
public function actionUpdateMasseuseAndStationListPSID(){
$sid = Booking::getServices($_POST['clientPackagedService_id']);
....(codes to update Masseuse, Station, and TimeEnd.
}
in the model.php
public static function getServices($cpsID){
$psID = Yii::app()->db->createCommand('SELECT packagedService_id FROM client_packagedservice WHERE id='.$cpsID)->queryAll();
$sID = Yii::app()->db->createCommand('SELECT service_id FROM packaged_service WHERE id = '.$psID)->queryAll();
return $sID;
}
As you can see, I have already posted the appropriate name $_POST['clientPackagedService_id'] in the controller.php, but I still get the Error 500: Undefined index: clientPackagedService_id.
Did I do something wrong somewhere? Please advise. Thanks
I think problem is the data your are posting with ajax request. This is your data:
'data'=>array('clientPackagedService_id'=>'js:this.value', 'dt'=>'js:$("#Booking_date").val()', 'timeStart'=>'js:$("#Booking_timeStart").val()'),
Try to change it into this:
'data'=>array('clientPackagedService_id'=>'js:$(this).value', 'dt'=>'js:$("#Booking_date").val()', 'timeStart'=>'js:$("#Booking_timeStart").val()'),
Best way for debugging ajax request is to inspect browser's console. You can see ajax's posted data and realize your problem.

Can't get Task to Send Email in Symfony 1.4

I created a task to automate emailing a report in Symfony 1.4. Both this task and a related module for viewing in the web share a custom PHP class file. The task is able to pull in the data correctly, but I have not been able to get it to send out the email. I attempted to follow the official Symfony 1.4 documentation as well as a number of examples from a Google search, but none are solving my problem. The terminal isn't displaying any error either.
My Code:
<?php
require_once sfConfig::get('sf_lib_dir').'/vendor/sesame/reports/reports.class.php';
//use reports;
class reportsTask extends sfBaseTask
{
protected function configure()
{
// // add your own arguments here
// $this->addArguments(array(
// new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
// ));
$this->addOptions(array(
new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name'),
new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
new sfCommandOption('type', null, sfCommandOption::PARAMETER_OPTIONAL, 'The output type of the report', 'email')
// add your own options here
));
$this->namespace = '';
$this->name = 'reports';
$this->briefDescription = '';
$this->detailedDescription = <<<EOF
The [reports|INFO] task does things.
Call it with:
[php symfony reports|INFO]
EOF;
}
protected function execute($arguments = array(), $options = array())
{
$databaseManager = new sfDatabaseManager($this->configuration);
$databaseManager->loadConfiguration();
$reports = new reports();
$output = $reports->buildReport($options['type']);
switch($options['type']){
case 'csv':
echo $output;
break;
case 'email':
$message = $this->getMailer()->compose($output['from'], $output['to'], $output['subject']);
$message->setBody($output['body']['content'], $output['body']['type']);
$message->attach(Swift_Attachment::newInstance($output['attachment']['content'], $output['attachment']['name'], $output['attachment']['type']));
$this->getMailer()->sendNextImmediately()->send($message) or die('email failed to deliver');
$output = array('status'=>'success', 'to'=>$output['to']);
default:
$this->logSection('results', json_encode($output));
}
}
}
The terminal command being attempted from the project root:
php symfony reports
Any answers leading to the right path would be most helpful. Please keep in mind that I need to stay with version 1.4. The server is capable of sending off emails and my module version does just that when invoked by a URL. I need it to run on the command line though so I can set up a cron.

echo posted json data in server php

The json sent to server php file as post request from ibm worklight Http adapter not accessible even after decoding:
Here are the codes:
Http adapter:
function storeRegistrationData(emailVal, passVal, fname1, gender, phone, userType, vehType) {
var credentials = JSON.stringify({jemailVal: emailVal, jpassVal: passVal, jfname1: fname1, jgender: gender, jphone: phone, juserType : userType, jvehType : vehType});
var input = {
method : 'post',
returnedContentType : 'json',
path : "/carbikepooling/index.php",
parameters: {credentials: credentials}
};
return WL.Server.invokeHttp(input);
}
Server php code:
$jsonObj = (isset($_POST['credentials']) ? $_POST['credentials'] : null);
$credentials = json_decode($jsonObj);
$email = $credentials->jemailVal;
$pass = $credentials->jpassVal;
$uname = $credentials->jfname1;
$gender = $credentials->jgender;
$phone = $credentials->jphone;
$usertype = $credentials->juserType;
$vehtype = $credentials->jvehType;
$boolean = false;
$userId; $userTypeId;
// sanitation, database calls, etc
$connection = mysqli_connect("localhost","root","","carbikepooling");
if (mysqli_connect_errno($connection))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($connection,"insert into userInfo values(0,".$email.",'".$pass."','".$uname."','".$gender."','".$phone."')");
$result1 = mysqli_query($connection, "select u.userId from userInfo u order by u.userId desc limit 1");
if($result1){
$row1 = mysqli_fetch_row($result1);
$userId = $row1[0];
mysqli_query($connection,"insert into userType values(0,".$userId.",'".$usertype."')");
$result2 = mysqli_query($connection, "select t.userTypeId from userType t order by t.userTypeId desc limit 1");
if($result2){
$row2 = mysqli_fetch_row($result2);
$userTypeId = $row2[0];
mysqli_query($connection, "insert into vehicleType values(0,".$userTypeId.",'".$vehtype."')");
$boolean = true;
}
}
mysqli_close($connection);
$returnData[] = array(
'boolean' => "$boolean"
);
echo json_encode($returnData);
?>
Javascript code to show return result from server php:
function storeFormData(emailVal, passVal, fname1, gender, phone, userType, vehType){
var invocationData = {
adapter : 'registerUser',
procedure : 'storeRegistrationData',
parameters : [emailVal, passVal, fname1, gender, phone, userType, vehType]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : storeFormDataSuccess,
onFailure : storeFormDataFailure,
});
}
function storeFormDataSuccess(result){
WL.Logger.debug('Data stored Successfully');
alert(JSON.stringify(result.invocationResult));
}
function storeFormDataFailure(result){
WL.Logger.error('Error in storing Data');
}
What happens is that when I used decoded json data in server php file in the insert statements, nothing happens. I tried echoed values of email, gender, etc. but nothing prints as if they contain no values. However, if I sent the decoded json values of email, gender etc. in the returnData array as they are used in insert statements, values successfully received by the app which made the request, i.e: shown those values in the alert in the js code. Please solve this problem?
Hmm, that is strange. I copied and pasted your exact code and I was able to echo the variables that were passed from the Worklight adapter. Maybe the way you are trying to use the variables for your sql statements is wrong?
Can you change your mysql query to look something more like this?
mysqli_query($connection, "insert into vehicleType values(0, '$userTypeId','$vehtype')");
Notice how I've removed the concatenation '.' from the query and I now I just have the variables surrounded by single quotes.

Why i don't see my #replies in conversation view in twitter?

I need to reply to one particular twitter status. I'm using following functions. And I've used Abraham's twitteroauth library in php.
public function replyToTwitterStatus($user_id,$status_id,$twitt_reply,$account_name)
{
$connection= $this->getTwitterConnection($user_id,$account_name);
try{
$responce = $this->postApiData('statuses/update', array('status' => $twitt_reply,'in_reply_to_status_id '=> $status_id),$connection);
}
catch(Exception $e){
echo $message = $e->getMessage();
exit;
}
}
// this function will handle all post requests
// To post/update twitter data
// To post/update twitter data
public function postApiData($request,$params = array(),$connection)
{
if($params == null)
{
$data = $connection->post($request);
}
else
{
$data = $connection->post($request,$params);
}
// Need to check the error code for post method
if($data->errors['0']->code == '88' || $data->errors['0']->message == 'Rate limit exceeded')
{
throw new Exception( 'Sorry for the inconvenience,Please wait for minimum 15 mins. You exceeded the rate limit');
}
else
{
return $data;
}
}
But the issue is that it is not maintaining the conversation view and it is update like normal status for e.g #abraham hello how are you. but that "View conversation" is not coming. Like expanding menu is not coming.
Please do needful
Thanks
You've got an unwanted space in your in_reply_to_status_id key which causes that parameter to be ignored.
This call:
$responce = $this->postApiData('statuses/update', array(
'status' => $twitt_reply,
'in_reply_to_status_id ' => $status_id
), $connection);
should look like this:
$responce = $this->postApiData('statuses/update', array(
'status' => $twitt_reply,
'in_reply_to_status_id' => $status_id
), $connection);
Also, make sure that the $status_id variable is being handled as a string. Although they look like numbers, most ids will be too big to be represented as integers in php, so they'll end up being converted to floating point which isn't going to work.
Lastly, make sure you have include the username of the person you are replying to in the status text. Quoting from the documentation for the in_reply_to_status_id parameter:
Note:: This parameter will be ignored unless the author of the tweet this parameter references is mentioned within the status text. Therefore, you must include #username, where username is the author of the referenced tweet, within the update.

How to post to user wall only 1 time when a user allows my app?

Currently my app posts to the users wall every time they access the app. I only want it to post to the wall one time when they first authorize the app. Then every time they access it afterward it only updates the news feed status.
here is my current code:
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$access_token = $facebook->getAccessToken();
$vars = array(
'message' => "Message goes here",
'picture' => "image",
'link' => "link here",
'name' => "Name here",
'caption' => "Caption here"
);
$result = $facebook->api('/me/feed', 'post', $vars);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=> $app_url));
echo "<script type='text/javascript'>";
echo "top.location.href = '{$loginUrl}';";
echo "</script>";
}
What do I need to change in order to make that happen?
You have 2 choices of methods to achieve this behavior.
Utilize the Feed Dialog on the landing page for your users. This will popup a Facebook window prompting your users to share something on their wall. This method requires that you implement the JavaScript SDK as well.
Utilize the PHP SDK and programatically posting a feed story to the /me/feed endpoint. (As you have done in the try-catch block of your code sample).
With regard to only posting on the users first visit you should store in your database a boolean value. When you create a new record for the new user in your database you should include a field called something like first_visit and populate it with a "true" value.
Then when you detect a returning user (that means he is already in your database) you can check to see that the first_visit field is set to "false". Then your post via the PHP SDK can be the result of a conditional expression to test the first_visit value :
...
...
if ($first_visit == 'true'){
$result = $facebook->api('/me/feed', 'post', $vars);
}
An additional solution (not requiring a database) could be something similar to this :
When you so cunningly generate the login URL with the $facebook->getLoginUrl() method for your un-authorized users, you can add a temporary GET parameter to the redirect_uri parameter. Something like :
$redirect_uri = 'https://apps.facebook.com/waffle-ville?new_user=true';
Then your conditional expression for posting to the users wall would look something like this :
...
...
if ($_GET['new_user'] == 'true'){
$result = $facebook->api('/me/feed', 'post', $vars);
}
Don't forget to redirect the user back to the original URL after you have made the post :
var app_url = "https://apps.facebook.com/waffle-ville";
echo "<script type='text/javascript'>";
echo "top.location.href = app_url;";
echo "</script>";
The redirect is also possible with PHP :
$app_url = "https://apps.facebook.com/waffle-ville";
header("Location: {$app_url}");
IMO - Posting to a users wall automagically is a little bit annoying. There is a parameter in your application settings that is called Social Discovery. When this is set to "enabled" a story is automagically created as soon as a user installs your application. I recommend leaving posting to a users wall as an optional user initiated action.
I've figured it out. I created a database to store info and it checks to see if the User ID already exists or not. If it doesn't, then they are placed in the database and a post is made to their wall. If they are in the database, then nothing happens.
<?php
require 'facebook.php';
require 'dbconnect.php';
// Create our application instance
// (replace this with your appId and secret).
$app_id = "APP_ID";
$secret = "APP_SECRET";
$app_url = "APP_URL";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
'cookie' => true,
));
// Get User ID
$user = $facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
$access_token = $facebook->getAccessToken();
$name = $user_profile['name'];
$birthday = $user_profile['birthday'];
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=> $app_url));
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
}
//DO NOT EDIT BELOW
$db=mysql_connect($hostname, $dbuser, $pass);
mysql_select_db($database, $db);
//check if user has already signed up before
$insert = true;
$result = mysql_query("SELECT * FROM table_name") or die(mysql_error());
while($row = mysql_fetch_array($result)){
//if user id exists, do not insert
if(( $row['UID'] == $user)){
$insert = false;
}
}
// if new user, insert user details in your mysql table
if($insert){
mysql_query("INSERT INTO table_name (UID, username, userbirthday) VALUES ('$user','$name','$birthday') ") or die(mysql_error());
$access_token = $facebook->getAccessToken();
$vars = array(
'message' => "message goes here",
'picture' => "image",
'link' => "Link here",
'name' => "Name here",
'caption' => "Caption here",
);
$result = $facebook->api('/me/feed', 'post', $vars);
}
?>

Resources