I can't use my query in php when i use codeigniter.
I think that it's all ok but my code doesn't work.
What is it wrong ?
I need to cofront two parametres.
I have a table and i need colonn3
Models:
function get_colonn3($data){
$this->db->select("table.colonn3");
$this->db->where("table.colonn3",$data);
return $this->db->get("table.colonn3")->result_array();
Controller:
$colonn3_exsist = $this->my_model->get_colonn3($data)
if($colonn3_exsist):
echo "ok";
endif;
Remove table.colon3 from get(), maybe it will work
return $this->db->get()->result_array();
I believe is because you're passing the table name to the where statement and it expects a column.
CodeIgniter where documentation
function get_colonn3($data) {
$this->db->select("table.colonn3");
$this->db->where("colonn3", $data);
return $this->db->get("table")->result_array();
}
They also allow you to pass an array to the where parameters too:
function get_colonn3($data) {
$this->db->select("table.colonn3");
$this->db->where([
"colonn3" => $data
]);
return $this->db->get("table")->result_array();
}
CI also allows you to chain DB functions like so:
function get_colonn3($data) {
$this->db->select("table.colonn3")
->where([
"colonn3" => $data
]);
return $this->db->get("table")->result_array();
}
try this:
//model
function get_colonn3($data){
$this->db->select("colonn3");
$this->db->where("colonn3",$data);
return $this->db->get("table")->result_array();
//controller
$colonn3_exsist = $this->my_model->get_colonn3($data)
if($colonn3_exsist>0){
echo"ok";
}
You are passing the value to WHERE in a wrong way. You have to pass the values in an array without passing the table name.
You have to pass the array in WHERE clause like this if you have more than one parameter to compare from Database:
function get_colonn3($para1,$para2){
$this->db->select("table.colonn3");
$this->db->where(['columnname1' => $para1, 'columnname2' => $para2]);
return $this->db->get("table.colonn3")->result_array();
}
If you have only one parameter to compare then you can use this:
function get_colonn3($para1){
$this->db->select("table.colonn3");
$this->db->where('columnname1',$para1);
return $this->db->get("table.colonn3")->result_array();
}
Model
function get_colonn3($data){
return $this->db->select("table.colonn3 as col3")->from('table')->where(['table.colonn3' => $data])->get()->row()->col3;
}
Controller
$colonn3 = $this->my_model->get_colonn3($data)
if(!empty($colonn3)):
echo "ok";
endif;
Related
controller code
if($this->input->post('update'))
{
$n=$this->input->post('pps_pin');
$e=$this->input->post('pps_address');
$m=$this->input->post('stm_shipping_type');
$a=$this->input->post('tsm_time_slot');
$b=$this->input->post('pps_price');
$id=$this->input->post('pps_slid');
$this->Config_model->updaterecords($n,$e,$m,$id,$a,$b);
redirect('Admin_ctrl/config/view_pincode_price');
}
}
model code
function updaterecords($n,$e,$m,$id,$a,$b)
{
$id;
$qr=$this->db->query("UPDATE pincode_price_setup,shipping_type_mst,time_slot_mst SET pps_pin='$n',pps_address='$e',stm_shipping_type='$m',tsm_time_slot='$a',pps_price='$b' WHERE pps_slid='$id'");
return $qr;
}
Delivery Method and Delivery Time Slot data are same
You should modify your code to use codeigniters prepared statements. If I correctly understood relations in your DB, your update records method should looks something like this:
function updaterecords($n, $e, $m, $id, $a, $b)
{
$this->db->set('pps_pin', $n);
$this->db->set('pps_address', $e);
$this->db->set('stm_shipping_type', $m);
$this->db->set('tsm_time_slot', $a);
$this->db->set('pps_price', $b);
$this->db->join('shipping_type_mst', 'pincode_price_setup.pps_shipping_type = shipping_type_mst.stm_sqlid');
$this->db->join('time_slot_mst', 'pincode_price_setup.pps_time_slot = time_slot_mst.tsm_sqlid');
$this->db->where('pps_slid', $id);
$this->db->update('pincode_price_setup');
}
Friendly tip: give your variables some more meaningful names, it would be much easier to work with variable named $pin than $n.
Please try like this
//Controller Code
function update_record($id){
$update_array = array(
'pps_pin' => $this->input->post('pps_pin') ///add fields in array which updated
);
$this->modal_name->update($id,update_array);//pass id & array which want to be update
}
//Modal code
function update($id,$array){
return $this->db->where('id',$id)->update('TABLE_NAME',array);
}
Try This code
function updaterecords($n, $e, $m, $id, $a, $b) {
$this->db->set('pps_pin', $n);
$this->db->set('pps_address', $e);
$this->db->set('stm_shipping_type', $m);
$this->db->set('tsm_time_slot', $a);
$this->db->set('pps_price', $b);
$this->db->where('pps_slid', $id);
$this->db->update('pincode_price_setup');
return ($this->db->affected_rows() != 1) ? false : true;
}
Once codeigniter model is loaded then its default update function works
if($this->input->post('update'))
{
$data = [
'pps_pin' => $this->input->post('pps_pin'),
'pps_address' => $this->input->post('pps_address'),
'stm_shipping_type' => $this->input->post('stm_shipping_type'),
'tsm_time_slot' => $this->input->post('tsm_time_slot'),
'pps_price' => $this->input->post('pps_price'),
'pps_slid' => $this->input->post('pps_slid'),
];
$this->Config_model->id = $id;
$this->Config_model->update($data);
redirect('Admin_ctrl/config/view_pincode_price');
}
}
So I am sure we don't need to define a separate function in model for same purpose.
So as I understand it, you want to update records in your database. I will not write it for you. I will show you an example.
This code may not be perfect but it works for my localhost project.
Create a function to update records in your controller.
Example:
public function update($id){
$id = $this->input->post('id');
//create $data array and add your data to array
$data = array(
'nazov_divizia' => $this->input->post('nazov')
);
//send this $data array with $id to your update function in model
$this->Divizia_model->updateData($id, $data);
//you can create flash message if you want
$this->session->set_flashdata('message', 'Údaje upravené');
//redirect to your controller index function
redirect(base_url().'divizia');
}
Create a function to update the record in your model.
Example:
public function updateData($id, $data)
{
$this->db->where('id_divizia', $id);
$this->db->update('divizia', $data);
}
This is code here:
protected function credentials(Request $request)
{
$admin=admin::where('email',$request->email)->first();
if(count($admin))
{
if($admin->status==0){
return ['email'=>'inactive','password'=>'You are not an active person, Please contact to admin'];
}
else{
return ['email'=>$request->email,'password'=>$request->password,'status'=>1];
}
}
return $request->only($this->username(), 'password');
}
When i run the code this error become:
"count(): Parameter must be an array or an object that implements Countable"
It happens because of in PHP 7.2 NULL in count() return Warning.
You can try to change
count($admin)
to
count((is_countable($admin)?$admin:[]))
This is my solution:
count(array($variable));
Note that here, When you use the count() method, there should be countable element, like an array or object that implement ArrayAccess.
Admin::where('email',$request->email)->first();
But the first() method give you single element, not a collection or array. The get() method returns you countable a collection with found elements
Instead of using count you can directly check variable itself is it defined or null
if($admin){
// do something here
}
or you can use is_null() method
if(!is_null($admin)){
// do something here
}
$admin variable is neither array nor object that implements countable. When you use first() the result will be a model object if record is found else it will be null. For this condition you can use:
if (!empty($admin)) {
//
}
Just replace if (count($admin)) with if (!empty($admin)).
And when you use get() method to get multiple records you can check by:
if ($admins->count() > 0) {
//
}
You should check if it is null instead of count, because you ask for one result with first()
just this
if($admin)
will do it.
if you use return a collection using ->get() then you can check $admin->count().
You can cast the variable to an array:
count((array)$variable);
If it's null then it will become an empty array.
Well,
$admin=Admin::where('email',$request->email)->first();
//It will always return an **object**.
And make sure you included Admin model in your controller like as.
Use App\Admin;
at the same time check that you will have to mention which field of table needs to be fillable like in your model such as
protected $fillable = [
'first_name',
'last_name'
];
whatever data you will going to save in your database.
and then check object is null or not
I mean is.
if($admin && $admin!==null){
//do whatver you want to do.
}
$admin = null;
var_dump(count($admin));
output: Warning: count(): Parameter must be an array or an object that implements Countable in … on line 12 // as of PHP 7.2
if condition should be like:
if(isset($admin) && count($admin))
Use isset($admin->id) instead of count($admin)
Try this :
protected function credentials(Request $request)
{
$admin=admin::where('email',$request->email)->first();
if(isset($admin->id)))
{
if($admin->status==0){
return ['email'=>'inactive','password'=>'You are not an active person, Please contact to admin'];
}
else{
return ['email'=>$request->email,'password'=>$request->password,'status'=>1];
}
}
return $request->only($this->username(), 'password');
}
In my case count was 1 even when I got [] from api
so I had to put it in try catch
try{
$propertyId = arr[0].propertyId;
}catch(\Exception $e) {
return response()->json(['success' => 'false']);
}
add this your controler this code:
$user = User::where('email',$request->email)->first();
if ($user){
return redirect()->back()->with('errors','We cant find a user with that e-mail address.');
}else{
$user->password = bcrypt($request->new_password);
$user->update();
return redirect()->back()->with('success','Success');
}
Edit
Thanks for all the input on this, I did find error in my question so modifying now. Sorry for that.
I am trying to figure out how to return the last object in the JSON string I have rendered. The two functions I am working with:
public function revision($return = false)
{
$id = $this->input->post('galleryID');
$data = array('revision_count' => $this->revision->count_revision($id) );
if($return){
return json_encode($data);
}
else {
echo json_encode($data);
}
}
public function last_revision()
{
$allRevisions = json_decode($this->revision(),true);
return end($allRevisions);
}
The issue is that end() returns error stating that 1st parameter should be array.
Thanks for any help on this.
It is important to note here that json_decode returns an instance of stdClass by default. Try using json_decode($jsonstring, true) to return the JSON as a PHP associative array.
However, You haven't included what the $this->revision() method does. Could you possibly show that portion of the code, since that is the function you are getting a return value from?
Edit:
Alright, after we saw the right function in your code, here are a couple of things I would like to say:
You have added a $return parameter to your revision method, but you aren't using it when you need to. You should change $this->revision() to $this->revision(true) in your last_revision method.
If you're going to return data from the revision() method, there's not much of a point in json_encodeing it, just to json_decode the result. Just pass back the raw data array.
Once you have changed both of these things, this should work:
$allRevisions = $this->revision(true); return end($allRevisions['revision_count']);
You can change the edit_function() to:
public function edit_revision($return = false)
{
$galleryID = $this->input->post('galleryID');
$revisionID = $this->input->post('revisionID');
$data = array('revision_images' => $this->revision->get($galleryID, $revisionID) );
if($return)
return json_encode($data);
else
echo json_encode($data);
}
and then:
public function last_revision(true)
{
$allRevisions = json_decode($this->revision());
return end($allRevisions);
}
Maybe you need convert that json output to an php array (json_decode() function), then you could get the last item with array_pop() function:
https://php.net/array_pop
I have a function variable like this...
$aName = "My Name";
The function need to pass in like this:
$sayHelloFunction = function sayHello($aName){
echo($aName);
}
Than, I have a method that responsible for execute the sayHelloFunction:
runningFunction($sayHelloFunction($aName));
in the runningFunction, it will have some condition to execute the function, but when I pass the "$sayHelloFunction($aName)" to runningFunction, it execute automatically, but I would like to pass the variable $aName as well, how can I achieve it? Thank you.
runningFunction($sayHelloFunction, $aName);
Simples.
You will have to pass the arguments separately. However, you could wrap them in an array so that you can pass them to runningFunction as a single argument, like this:
$printFunction = function($args) {
print $args['lastname'].', '.$args['firstname'];
};
function runningFunction($f, $a) {
$f($a);
}
$firstname = 'Bob';
$lastname = 'Smith';
$functionArguments = array(
'firstname' => $firstname,
'lastname' => $lastname
);
runningFunction($printFunction, $functionArguments);
If you want your dynamic functions to get "proper" arguments, then I see no way around something like this:
function runningFunction($f, $a) {
switch(count($a)) {
0: $f(); break;
1: $f($a[0]); break;
2: $f($a[0], $a[1]); break;
3: $f($a[0], $a[1], $a[2]); break;
// and so on
}
}
Pass the parameters as an array, and then use call_user_func_array() to call your function.
This way your runningFunction() will be absolutely abstract (as you requested), it can call any type of function, it's your responsibility to pass the right number of parameters.
function runningFunction ($callback, $parameters=array()) {
call_user_func_array($callback, $parameters);
}
runningFunction($sayHelloFunction, array($aName));
call_user_func_array()
as xconspirisist suggested pass $aName as a seperate parameter to the function.
Details on Variable Functions can be found on the PHP site.
Use an anonymous function when calling runningFunction
function runningFunction($func) {
$func();
}
runningFunction(function() {
$sayHelloFunction($aName));
// You can do more function calls here...
});
I have a function to send mail to users and I want to pass one of its parameter as an array of ids.
Is this possible to do? If yes, how can it be done?
Suppose we have a function as:
function sendemail($id, $userid) {
}
In the example, $id should be an array.
You can pass an array as an argument. It is copied by value (or COW'd, which essentially means the same to you), so you can array_pop() (and similar) all you like on it and won't affect anything outside.
function sendemail($id, $userid){
// ...
}
sendemail(array('a', 'b', 'c'), 10);
You can in fact only accept an array there by placing its type in the function's argument signature...
function sendemail(array $id, $userid){
// ...
}
You can also call the function with its arguments as an array...
call_user_func_array('sendemail', array('argument1', 'argument2'));
even more cool, you can pass a variable count of parameters to a function like this:
function sendmail(...$users){
foreach($users as $user){
}
}
sendmail('user1','user2','user3');
Yes, you can safely pass an array as a parameter.
Yes, you can do that.
function sendemail($id_list,$userid){
foreach($id_list as $id) {
printf("$id\n"); // Will run twice, once outputting id1, then id2
}
}
$idl = Array("id1", "id2");
$uid = "userID";
sendemail($idl, $uid);
What should be clarified here.
Just pass the array when you call this function.
function sendemail($id,$userid){
Some Process....
}
$id=array(1,2);
sendmail($id,$userid);
function sendemail(Array $id,$userid){ // forces $id must be an array
Some Process....
}
$ids = array(121,122,123);
sendmail($ids, $userId);
Its no different to any other variable, e.g.
function sendemail($id,$userid){
echo $arr["foo"];
}
$arr = array("foo" => "bar");
sendemail($arr, $userid);
I composed this code as an example. Hope the idea works!
<?php
$friends = array('Robert', 'Louis', 'Ferdinand');
function greetings($friends){
echo "Greetings, $friends <br>";
}
foreach ($friends as $friend) {
greetings($friend);
}
?>
I found Delcon answer helpful but I was looking for this
function sendmail($user1, $user2, $user3){
echo $user1;
echo $user2;
echo $user3;
}
$users = array('user1','user2','user3');
sendmail(...$users);
In php 5, you can also hint the type of the passed variable:
function sendemail(array $id, $userid){
//function body
}
See type hinting.
Since PHP is dynamically weakly typed, you can pass any variable to the function and the function will try to do its best with it.
Therefore, you can indeed pass arrays as parameters.
Yes, we can pass arrays to a function.
$arr = array(“a” => “first”, “b” => “second”, “c” => “third”);
function user_defined($item, $key)
{
echo $key.”-”.$item.”<br/>”;
}
array_walk($arr, ‘user_defined’);
We can find more array functions here
http://skillrow.com/array-functions-in-php-part1/
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>