I have a method like this:
public function query ($sql) {
$this->result = $this->db->query($sql);
}
Binds the query statement to the result variable. This is really handy because I have several methods that output something and another method that then handles the $result variable for other tasks.
However I wanted to use the same kind of method, but on prepared statements(to escape data that gets inserted) and I ran into a problem:
public function prepare ($sql) {
$this->result = $this->db->prepare($sql);
}
I tried to use it like this:
public function insert ($this, $that) {
// Then I tried to use my prepare method
$var = $this->prepare(INSERT INTO Table (Row1, Row2) VALUES (:Val1, :Val2));
$var->bindValue(":Val1", $this, PDO::PARAM_INT);
//... and so on
}
The problem shows up on the $var->bindValue() "Call to a member function bindvalue() on a non-object". What is exactly happening here because I don't really understand the error message? If I query my db using the query method it works just fine, but how can I bind values using the prepare method?
In:
public function ($sql) {
$this->result = $this->db->prepare($sql);
}
You forget to return the result. (You also forgot the name of the function in the snippet.)
The error message is quite clear, you're calling a method on something that's not an object. In this case you're calling it on NULL because your own prepare-method doesn't return anything.
first off i noticed your methods don't have a name.
public function ($sql) {
$this->result = $this->db->query($sql);
}
shouldn't it be something like
public function doSomething($sql) {
$this->result = $this->db->query($sql);
}
secondly, it seems you are calling an instance of another class in your method.
$this->db->query($sql)
if am not wrong the 'db' should be anothe class that you are trying to access its query method...Look at your code again.
Lastly i you are missing a return statement.
Related
I have following two classes called One and Two respectively. Class One has database stuff in it. Where method connect() returns a variable (a property) that is the database handler ($dbh). I have used connect() literally hundreds of times and it works as anticipated. Here too, (in method query()) it should work correctly. Now the work the method query() has to do is to prepare a statement ($query in this case) and execute it, after which it fetches data as an associative array and returns the data. I call this method in multiple methods, and works fine in all except in the method some_method() in class Two.
class One {
protected function query($sql, $params=[]){
$query = $this->connect()->prepare($sql); // Method connect() returns database handler ($dbh)
$query->execute($params);
$storage = $query->fetch(); // Fetch as an associative array
return $storage;
}
}
Now here in some_method() in class Two, method query()(from class One), is called where a variable $sql and also an associative array $params are declared as shown in the code below. All this method has to do is to call the method query(), with the parameters $sql and $params, and store the result in $storage. If $storage==false, return false and if $storage has some value other than false, return true. And this result (i.e., true or false) depends on if the database has an entry in the column class_date as specified in $params['date']. Now here comes the problem, irrespective of if the database has that value in that column, the method some_method(), always returns false. I don't know what mistake I'm doing here. Can someone point it out please.
class Two extends class One{
public function some_method($date){
$sql = 'SELECT class_date FROM table_name WHERE id=:id AND class_date=:date';
$params = [
'id' => $this->user_id,
'date' => $date
];
$array = $this->query($sql, $params);
return ($array==false) ? false : true;
}
}
so i'd like to get the response from my model:
function get_list_sales_kit(){
$brispot = $this->load->database('brispot',TRUE);
$brispot->select('id,title,imgurl,description');
$qrydata = $brispot->get('saleskit');
$brispot->close();
return $qrydata->result();
}
and this is the function to call that model:
function salesKit2($request){
$result = new stdClass;
$user='';
$CI =& get_instance();
$CI->load->library('libs_bearer');
$CI->load->library('libs_brispot');
$CI->load->model('service_model');
$datapost = json_decode($request);
if(isset($datapost->user)){
$user = substr('00000000'.$CI->security->xss_clean(trim($datapost->user)),-8);
if($CI->libs_bearer->cekToken($user)==true){
$getdata = $CI->service_model->get_list_sales_kit();
if($getdata->num_rows()>0){
$result->responseCode='00';
$result->responseDesc='Inquiry berhasil.';
$result->responseData=$getdata->result();
}
}
but i got eror result like fatal eror Call to a member function num_rows() on a non-object.
i confused how to call non object on num_row, or is there anything to replace num_row to get the response?
If you really want to return the result from your get_list_sales_kit() function the only way to get the number of rows is to count($getdata) as Lawrence said in the comments.
With that being said, I sometimes return the database object itself like so:
function get_list_sales_kit(){
$brispot = $this->load->database('brispot',TRUE);
$brispot->select('id,title,imgurl,description');
$qrydata = $brispot->get('saleskit');
$brispot->close();
return $qrydata; // this line changed
}
as such you can run any CI database functions on it like row() result() num_rows() and so on. Nothing has to be changed in the second code snippet as for some reason you are already accessing the result() object even though you are returning it in the first function.
Note: I'm not sure if close() will affect the objects being called after the fact. Why are you closing the database after doing one thing?
I am attempting to make multiple queries in a scope function in laravel. my code is as follows. the first query executes normally but the second seems to be ignored. what is the correct way to do this?
public function scopeUpdateStatus($query,$oldUser, $newUser, $alias, $env) {
$query->where('db_conn_app_alias_user', $newUser)->where('db_conn_app_alias', $alias)->where('app_instance_environment', $env)->update(array('user_status' => 'active'));
$query->where('db_conn_app_alias_user', $oldUser)->where('db_conn_app_alias', $alias)->where('app_instance_environment', $env)->update(array('user_status' => 'passive'));
return "success";
}
The trick here is to use with (a Laravel helper function) and clone.
function scopeSomeName($query) {
with(clone $query)->whereStuff;
with(clone $query)->whereOtherStuff;
}
This happens because you use the same $query variable in the two updates. You add where()s to the $query in the first update query and then run it, but when you add your where()s in the second update query the where()s from the first query are still there. Because of this your query will return zero result so there is nothing to update. Copy the $query first to a new variable then run the second query in the copied one:
public function scopeUpdateStatus($query, $oldUser, $newUser, $alias, $env) {
$queryTemp = $query;
$query->where('db_conn_app_alias_user', $newUser)
->where('db_conn_app_alias', $alias)
->where('app_instance_environment', $env)
->update(array('user_status' => 'active'));
$queryTemp->where('db_conn_app_alias_user', $oldUser)
->where('db_conn_app_alias', $alias)
->where('app_instance_environment', $env)
->update(array('user_status' => 'passive'));
return "success";
}
A minor edit (reduces overhead) to #merlinpatt answer. You don't need to clone the $query twice. Just once, as you already have the existing/original variable
function scopeSomeName($query) {
$query_cloned = clone $query;
$query->whereStuff;
$query_cloned->whereOtherStuff;
}
Also, there's no need for the with() helper function.
Tested it and works as expected.
i have one php class
class veh extends dbClass
{
function smo($id)
{
$query="select moname from mod where id=".$id;
$data=$this->query($query,1);
return $data[0];
}
}
i am calling that function like this
$objCms=new veh();
<?=$objCms->smo(1);?>
the value i got from this is showing array, but i need to get value of moname
Thanks
Your method don't returns anything, you should use return $this->lastQuery; or something like that
You are selecting, but ot fetching results. Try using MySQL Fetch Array or MySQL Fetch Row.
Example code:
class veh extends dbClass
{
function smo($id)
{
$query="select moname from mod where id=".$id;
$this->query($query,1);
return $this->fetchArray();
}
}
Where:
$this->fetchArray returns result of mysql_fetch_xxx of last query result.
May be the method query return an array as a result, can you give a link to veh class or put query method implementation from veh class.
You would use something like this, depending on how the ->query() method returns it's results. We really need to see ->query()'s body.
function smo($id)
{
$query = "select moname from mod where id=" . $id;
$data = $this->query($query,1);
return $data[0]['moname'];
}
The return statement could be 1 of the following 3 things: $data[0][0], $data[0]['moname'] or $data[0]->moname. You can find out by using var_dump to see how you're able to access the moname column's value.
I've been using this solution to get a superglobal mysqli connection:
class blst_db {
private static $mysqli;
private function __construct(){} //no instantiation
static function cxn() {
if( !self::$mysqli ) {
self::$mysqli = new mysqli(...);
}
return self::$mysqli;
}
//use
blst_db::cxn()->prepare(....
I found it here and it was working fine but when I try to get two connections at the same time I get an error. For example, I've a class that runs a query like this one:
$query_points = blst_db::cnx()->prepare('SELECT point_id FROM points WHERE id=?');
$query_points->bind_param('i', $this->id);
$query_points->bind_result($point_id);
$query_points->execute();
while ($query_points->fetch()) {
$point = new blst_point ($point_id);
$points[] = $point; }
I'm creating various objects inside the while statement and that objects constructor runs another query each time (another $query=blst_db::cnx->prepare(...)) and that's the one that is not working and I can't find the problem. If I change the code and create an array inside the while statement and then, after closing that query, I create all the objects inside a foreach I get no problem but I don't like that solution.
Thank you!
I found the problem. I have to store the results from the first query so I can run the rest inside it. I just added:
$query_points->store_result();
after the execute() call and then I made a free_result() before closing the $query_points and it's working perfectly.
I've found the solution here.