I wonder how i unset a specified session.
$array = array(
'Name' => 'Jhon',
'Age' => '19',
'Remark' => 'Tests'
);
$this->session->set_userdata('registrasi',$array);
I know i can delete session with
$this->session->unset_userdata('registrasi');
How do i delete Remark ? so the last result will be like this.
'Name' => 'Jhon',
'Age' => '19'
You can use unset_userdata()
$this->session->unset_userdata()
In You case
$this->session->unset_userdata('Remark');
I tired this with an my own example. Check below
This is my session
$session = array(
'id' => $result[0]['id'],
'username' => $name,
'logged_in' => TRUE
);
$this->session->set_userdata($session);
Printing session
print_r($this->session->all_userdata());
Output
Array (
[session_id] => 4cc6794ab4d1ee062e377945c92148dc
[ip_address] => ::1
[user_agent] => Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
[last_activity] => 1464104585
[user_data] =>
[id] => 1
[username] => Admin
[logged_in] => 1
[flash:new:success] => Welcome Admin
)
And im going to remove username from the above session
$this->session->unset_userdata('username');
And printing back
print_r($this->session->all_userdata());
Output
Array (
[session_id] => 4cc6794ab4d1ee062e377945c92148dc
[ip_address] => ::1
[user_agent] => Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
[last_activity] => 1464104585
[user_data] =>
[id] => 1
[logged_in] => 1
[flash:new:success] => Welcome Admin
)
So this tested and works well
Maybe you can try it.
public function index()
{
$array = array(
'Name' => 'Jhon',
'Age' => '19',
'Remark' => 'Tests'
);
$this->session->set_userdata('registrasi',$array);
print_r($this->session->all_userdata());
}
public function delete()
{
$i = "Tests";
$del = $this->session->userdata('registrasi');
$index = array_search($i, $del);
unset($del[$index]);
$this->session->set_userdata('registrasi', $del);
print_r($this->session->all_userdata());
}
Related
$sql = DB::table('laravel_products')
->insert(array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
));
$lastInsertedID = $sql->lastInsertId();
When I try to insert its responses:
"Call to a member function lastInsertId() on bool"
I used insertGetId but its cant save multiple rows of pictures on mysql.
If you want to get the last inserted ID like that you can call that method on the PDO instance directly:
$id = DB::getPdo()->lastInsertId();
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
$id = DB::table('users')->insertGetId(
['email' => 'john#example.com', 'votes' => 0]
);
from : https://laravel.com/docs/5.8/queries#inserts
$data = new LaravelProducts(); //LaravelProducts is your Model Name
$data->name= $name; //here 'name' is your column name
$data->price= $price; //here 'price' is your column name
$data->qty= $qty; //here 'qty' is your column name
$data->description= $description; //here 'description' is your column name
..........
..........
$data->image= $image; //here 'image' is your column name
$data->save();
$lastInsertedId = $data->id;
You don't have to write a new query to collect last inserted id from database.
$laravel_product = DB::table('laravel_products')
->insertGetId( array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
)
);
foreach ($filenamesToSave as $filename) {
DB::insert('INSERT INTO laravel_products_images ( product_id, filename ) VALUES ( ?, ? )',[$laravel_product->id, $filename]);
return view('createproduct');
} // Foreach Closing
// Echo your inserted ID Like Below
echo $laravel_product->id;
It should be 100% working for you.
My situation is
using Laravel 7
want to use Shopee API
Sending a request in Laravel should be like this
$res = Http::withHeaders([
'Content-Type' => 'application/json',
'Authorization' => $secret_key
])->post($api_url, [
"ordersn_list" => [$order_no],
"shopid" => $shop_id,
"partner_id" => $partner_id,
"timestamp" => $timestamp
]);
But Shopee API needs no space in the body part (cannot send as JSON format). I have tried
$res = Http::withHeaders([
'Content-Type' => 'application/json',
'Authorization' => $secret_key
])->post($api_url, $body_string);
It does not work because it must be an array. return error Argument 2 passed to Illuminate\Http\Client\PendingRequest::post() must be of the type array, string given
.
Try this:
$data = [
"ordersn_list" => [$order_no],
"shopid" => $shop_id,
"partner_id" => $partner_id,
"timestamp" => $timestamp
];
$res = Http
::asJson()
->withHeaders([
'Authorization' => $secret_key
])
->post($api_url, $data);
Or:
$data = [
"ordersn_list" => [$order_no],
"shopid" => $shop_id,
"partner_id" => $partner_id,
"timestamp" => $timestamp
];
$res = Http
::withHeaders([
'Authorization' => $secret_key
])
->withBody(json_encode($data), 'application/json')
->post($api_url);
am using code as below but am not getting any value.i gave as print_r($this->title); what i have to do to get the value. thanks
if(isset($_POST['is_ajax']) && $_POST['is_ajax']) {
print_r($this->title);
$respondentArray = array(
'state' => $_POST['state'],
'name' => $_POST['name'],
'title' => $_POST['title'],
'dline' => $_POST['directline'],
'email' => $_POST['email'],
'organization' => $_POST['organization'],
'address' => $_POST['address'],
'city' => $_POST['city'],
'state1' => $_POST['state1'],
'zip' => $_POST['zip'],
'generalphone' => $_POST['generalphone'],
'fax' => $_POST['fax'],
);
$this->session->set_userdata($respondentArray);
i guess this is what you need
echo $this->input->post('title') ;
$this->input->post(postedValues) this gets all the input values that is posted...
Use var_dump($this->title); to test
My validation fails, so my test for this message throws an ValidationException every time.
"Not all fields are filled out correct". Why? Analoguosly, it works for users (another method).
MODEL:
public $validate = array(
'name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Name can not be empty',
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'This name is already used.',
),
),
'address' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Address can not be empty',
),
...
public function saveNewInstitution($institutionData, $userId) {
$institutionData[$this->alias]['is_active'] = 1;
$institutionData[$this->alias]['user_id'] = $userId;
$this->create();
$this->set($institutionData);
if ($this->validates()) {
return $this->save();
} else {
throw new ValidationException('Not all fields are filled out correct');
}
}
TESTclass:
public function testSaveNewInstitution() {
$data = array(
'Institution' => array(
'name' => 'Spitex Staufen',
'address' => 'Hauptweg 4',
'postcode' => '1234',
'city' => 'huuh',
'phone_number' => '123 456 78 90',
'email' => 'staufen#spitex.huuh',
'comment' => '',
'institution_type_id' => 5
));
$expected = array(
'Institution' => array(
'id' => 2,
'name' => 'Spitex Staufen',
'address' => 'Hauptweg 4',
'postcode' => '1234',
'city' => 'huuh',
'phone_number' => '123 456 78 90',
'email' => 'staufen#spitex.huuh',
'comment' => '',
'is_active' => TRUE,
'user_id' => 2,
'institution_type_id' => 5
));
$result = $this->Institution->saveNewInstitution($data, 2);
$this->assertEqual($result, $expected);
}
and all the Exceptionhandling methods like this:
public function testSaveNewInstitutionExceptionName() {
$this->setExpectedException('ValidationException');
$this->Institution->saveNewInstitution($this->__nameEmpty, 2);
}
I don't know if i got it really - is your Testclass failing or is the saveNewInstitution() function making you troubles? Did you try to check if the saveNewInstitution() is working correct by hand - put some data in a form an pass it to your function?
Maybe it's just a small thing and you have an entry with id=2 in your database an you got a duplicate key exception overwritten by your own exception method testSaveNewInstitutionExceptionName().
I'm using CakePHP 2.1.1 and whilst my methods which use the form helper, for example my add method in my Users Controller validates correctly, I can't get my mobile_register method in the controller to validate, it saves even when data is missing.
This is my mobile_register method:
public function mobile_register() {
if ($this->request->is('post')) {
$jsonData = file_get_contents("php://input");
if(isset($jsonData) && !empty($jsonData)){
$data = json_decode($jsonData,true);
$data = $this->User->configureUser($data);
$this->User->create();
if($this->User->save($data)){
$jsonResponse = array('status' => 'OK', 'token' => $data['User']['token'], 'message' =>'SUCCESS');
}else{
$errors = $this->User->validationErrors;
$this->log($errors,'errors');
$jsonResponse = array('status' => 'ERROR','message' => $errors);
}
}
}else{
$jsonResponse = array('status' => 'ERROR','message' => 'API method expects POST data');
}
$this->set('response' , $jsonResponse);
}
I've been using curl to test my method and it always saves despite post the following data:
[User] => Array
(
[firstname] => Andy
[token] => cc42030bbb49faf2cf0393418036e44f
[role] => user
)
curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"User":{"firstname":"Andy"}}' url/users/mobile_register
My validation rules in my model are:
public $validate = array(
'username' => array(
'username-1' => array(
'rule' => array('notempty'),
'message' => 'Username is required',
),
'username-2' => array(
'rule' => 'alphaNumeric',
'message' => 'Usernames must only contain letters and numbers.',
),
),
'password' => array(
'password-1' => array(
'rule' => array('notempty'),
'message' => 'Password is required',
),
'password-2' => array(
'rule' => array('between', 5, 15),
'message' => 'Passwords must be between 5 and 15 characters long.',
),
),
'firstname' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Forename is required'
),
),
'surname' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Surname is required',
),
),
'email' => array(
'email-1' => array(
'rule' => 'notempty',
'message' => 'Email is required',
),
'email-1' => array(
'rule' => 'email',
'message' => 'Please enter a valid email',
)
)
);
Am I missing something?
Perhaps a better approach to this solution would be to make a good use of the "required" and "allowEmpty" validation options:
CakePhp's data validation
This is what solved my problem, I thought it was related with the way I was requesting the action, but instead it was that I wasn't even setting the fields I wanted to validate.
I figured it out. Basically I learnt that if you don't pass the fields then they will not be validated.