I am trying to retrieve the config_value on the basis of config_name from the table as shown in image in codeigniter project. Even i am not able to understand where to start.I find something like this on internet (for Sample).
$this->db->select('age');
$this->db->where('id', '3');
$q = $this->db->get('my_users_table');
$data = $q->result_array();
echo($data[0]['age']);
Do something like this :
$this->db->where('config_name', 'Account_activation');
$q = $this->db->get('my_users_table');
/* if u r fetching one row use row_array instead of result_array*/
$row = $q->row_array();
echo $row['config_value'];
For more : https://www.codeigniter.com/user_guide/database/index.html
If you want to retrieve config value on the basis of config name you can simply add an where condition in select query just like I am giving here, put whatever config_name you want to retrieve the query and it will print the config value which is there in the same row.
$this->db->select('config_value');
$q = $this->db->get_where('my_users_table',array('config_name'=>'home_page'));
$row = $q->row_array();
echo $row['config_name']; // this will print index.php
Little different than the other answers although functionally the same. You could make a helper and include this function. Really only useful if you only want to get one config item at a time.
function config_item_db($key) {
$CI = & get_instance();
$query = $CI->db->get_where('my_users_table', array('config_name' => $key));
if ($query->num_rows() == 1) {
return $query->row()->{$key};
} else {
return false;
}
}
Use codeignitor's get_where() method and pass the select condtions in an array. Example:
$this->load->database();
$this->db->get_where('table_name', array('database_column_title' => $value1,
'database_column_title' => $value2));
Related
I've got a table in which a field contains pattern Like this [{"vendor":"10","status":"paid"}] :
table
I want to make a query 'like' in codeigniter , but I got an error:
model :
function get_total_order($id_vendor){
$this->db->like('payment_status', 'vendor":"'.$id_vendor.'","status":"due');
$this->db->from('sale');
return $this->db->count_all_results();
}
view :
<?php
$new_order = $this->crud_model->get_total_order($this->session->userdata('vendor_id'));
echo "<h1>".$new_order."</h1>";
?>
when i run this, i got blank page, how i fix this?
thanks.
Since you use "Like" query type, you should add '%' in the query argument or send a complete argument:
function get_total_order($id_vendor)
{
$this->db->like('payment_status', '%vendor":"'.$id_vendor.'","status":"due%');
$this->db->from('sale');
return $this->db->count_all_results();
}
Try this:
function get_total_order($id_vendor){
$this->db->like('vendor',$id_vendor);
$this->db->like('status',"due");
$this->db->from('sale');
return $this->db->count_all_results();
}
if your searching json data so you have pass the data in like query and like query data should be look like data inside the table how it looks .
your query should be something like this
<?php
$id_vendor =123;
$ss= '%"vendor":"'.$id_vendor.'","status":"due"%';
$sssss ="select * from sale where payment_status like '$ss' ";
echo $sssss;
query look like this
select * from sale where payment_status like '%"vendor":"123","status":"due"%'
?>
and also you can use wildcard (%) more place with your wish.
You can customize where as per your requirement with and condition or another condition.
$where = "payment_status like '%$id_vendor%' OR status like '%$status%'";
$this->db->where($where);
try this one:
Because 'like is time consuming.
function get_total_order($id,$vendor)
{
$this->db->where('vender', $id);
$this->db->where('status',$vendor);
$this->db->get('sale');
$result=$res->result_array();
return $result;
}
You can use $this->db->where_in() like below:-
$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')
For more details, please check below link:-
https://www.codeigniter.com/userguide2/database/active_record.html
So let me explain my problem, lets assume that I run query like so:
$myquery = sql_query("SELECT name FROM table WHERE name='example' LIMIT 0,1");
Now.. I want to store the retrieved name into a variable so I would do something like this:
while ($myrow = sql_fetch_assoc($myquery)) {
transfer_row($myrow);
print"Name: $row_name";
}
$stored_name = $row_name;
NOTE: transfer_row() is just a function I wrote that takes $myrow['name'] and stores it in $row_name, for easier reference
Now, all is fine at this stage, here is where it gets interesting. Note that at this stage I still have a name assigned to $row_name. Further down the page I run another query to retrieve some other information from the table, and one of the things I need to retrieve is a list of names again, so I would simply run this query:
$myquery = sql_query("SELECT name, year FROM table WHERE DESC LIMIT 0,10");
while ($myrow = sql_fetch_assoc($myquery)) {
transfer_row($myrow);
$year = $row_year;
$link = "/$year";
print "<li style=\"margin-bottom: 6px;\">$row_name\n";
}
Now, I want to write an if statement that executes something if the $row_name from this query matches the $row_name from the old query, this is why we stored the first $row_name inside the variable.
if ($row_name == $stored_name){
// execute code
}
However as most of you know, this WONT work, the reason is, it simply takes $stored_name again and puts the new $row_name into $stored_name, so therefore the value of the first $row_name is lost, now it is crucial for my application that I access the first $row_name and compare it AFTER the second query has been run, what can I do here people? if nothing can be done what is an alternative to achieving something like this.
Thanks.
EDIT, MY transfer_row() function:
function transfer_row($myrow) {
global $GLOBALS;
if(is_array($myrow)) {
foreach ($myrow as $key=>$value) {
$key=str_replace(":","",$key);
$GLOBALS["row_$key"] = $value;
}
}
}
Without you posting the code for the function transfer_row, we won't be able to give you an answer that exactly matches what you request, but I can give you an answer that will solve the problem at hand.
When matching to check if the names are the same, you can modify the if statement to the following.
if ($row_name == $myrow['name']){
// execute code
}
What I suggest you do though, but since I don't have the code to the transfer_row function, is to pass a second variable to that function. The second variable will be a prefix for the variable name, so you can have unique values stored and saved.
Refrain from using the transfor_row function in the second call so your comparison becomes:
if ($myrow['name'] == $row_name)
If you need to use this function, you could do an assignment before the second database call:
$stored_name = $row_name;
...
transfer_row($myrow);
In your first query you are selecting the name field WHERE name='example' , Why are you quering then? You already have what you want.
Your are querying like:
Hey? roll no 21 what is your roll no?
So perform the second query only and use the if condition as :
if ($row_name == 'example'){
// execute code
}
Does it make sense?
Update
//How about using prefix while storing the values in `$GLOBAL` ??
transfer_row($myrow, 'old_'); //for the first query
transfer_row($myrow, 'new_'); //for the second query
function transfer_row($myrow, $prefix) {
global $GLOBALS;
if(is_array($myrow)) {
foreach ($myrow as $key=>$value) {
$key=str_replace(":","",$key);
$GLOBALS["$prefix"."row_$key"] = $value;
}
}
}
//Now compare as
if ($new_row_name == $old_row_name){
// execute code
}
//You'll not need `$stored_name = $row_name;` any more
hello i want to create function with returning data, for example when i have the function advert i want to make it every time show what i need, i have the table id, sub_id, name, date, and i want to create the function that i can print every time what i need advert(id), advert(name), i want to make it to show every time what i need exactly and i want to save all my result in array, and every time grab the exactly row that i want
<?php
function advert($data){
$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
$data = array(
'id' => $row['id']
);
}
return $data;
}
echo advert($data['id']);
?>
but my result every time is empty, can you help me please?
There are so many flaws in this short piece of code that the only good advice would be to get some beginners tutorial. But i'll put some effort into explaining a few things. Hopefully it will help.
First step would be the line function advert($data), you are passing a parameter $data to the method. Now later on you are using the same variable $data in the return field. I guess that you attempted to let the function know what variable you wanted to fill, but that is not needed.
If I understand correctly what you are trying to do, I would pass in the $id parameter. Then you can use this function to get the array based on the ID you supplied and it doesnt always have to come from the querystring (although it could).
function advert($id) {
}
Now we have the basics setup, we want to get the information from the database. Your code would work, but it is also vulnerable for SQL injection. Since thats a topic on its own, I suggest you use google to find information on the subject. For now I'll just say that you need to verify user input. In this case you want an ID, which I assume is numeric, so make sure its numeric. I'll also asume you have an integer ID, so that would make.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
}
Then I'll make another assumption, and that is that the ID is unique and that you only expect 1 result to be returned. Because there is only one result, we can use the LIMIT option in the query and dont need the while loop.
Also keep in mind that mysql_ functions are deprecated and should no longer be used. Try to switch to mysqli or PDO. But for now, i'll just use your code.
Adding just the ID to the $data array seems useless, but I guess you understand how to add the other columns from the SQL table.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
$query = mysql_query("SELECT * FROM advertisement WHERE id = $id LIMIT 1");
$row = mysql_fetch_assoc($query);
$data = array(
'id' => $row['id']
);
return $data;
}
Not to call this method we can use the GET parameter like so. Please be advised that echoing an array will most likely not give you the desired result. I would store the result in a variable and then continue using it.
$ad = advert($_GET['id']);
if (!is_array($ad)) {
echo $ad; //for sql injection message
} else {
print_r($ad) //to show array content
}
Do you want to show the specific column value in the return result , like if you pass as as Id , you want to return only Id column data.
Loop through all the key of the row array and on matching with the incoming Column name you can get the value and break the loop.
Check this link : php & mysql - loop through columns of a single row and passing values into array
You are already passing ID as function argument. Also put space between * and FROM.
So use it as below.
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$data."'");
OR
function advert($id)
{
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$id."'");
$data = array();
while($row = mysql_fetch_assoc($query))
{
$data[] = $row;
}
return $data;
}
Do not use mysql_* as that is deprecated instead use PDO or MYSQLI_*
try this:
<?php
function advert($id){
$data= array();
//$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
array_push($data,$row['id']);
}
return $data;
}
var_dump($data);
//echo advert($data['id']);
?>
I just started to using the Kohana framework and I'm trying to execute a few queries, but after spending a couple hours in documentation and running some tests all I have is this:
class Controller_Test extends Controller {
public function action_index()
{
$query = DB::select()->from('test')->where('test', '=', '1');
echo $query
}
}
Now, if try to run this all it does is echo my SQL.
How do I get the actual data from my database? I know that I could do something like:
$row = mysql_fetch_row(mysql_query($query));
echo $row[0];
and it would work; but I guess that's just completely stupid, since I'm using a framework and there has to be built-in method(s) for this.
You should be aware that you're actually building the Database_Query object, so there has to be something to execute it in the end, right?
$results = DB::select('*')->from('table')->execute();
and then you can normally loop through these:
foreach ($results as $result) { echo $result->id; }
After you've built up the query you'll then need to turn that into a Database_Query object using the execute() method so you can get values to run through.
If you want to deal with the results of the query as an array, you can add the as_array() method after the execute like so:
$query = DB::select()->from('test')->where('test', '=', '1')
->execute()->as_array();
If you're only dealing with a single row, and you know you only need a single row, you can change that to current():
$query = DB::select()->from('test')->where('test', '=', '1')
->execute()->current();
Then you can extract as needed when you loop through the array:
foreach ($query as $row)
{
echo $row['title'];
}
To get row:
$query = DB::select('p.id')
->select_array(array('p.title', array('p.title', 'pocket') ))
->from(array($this->_table_name, 'p'))
->limit(1);
echo $query->execute()->get('id');
To show query:
echo $query->compile();
In the Model class I use return $query->row(); to return single rows and return $query->result(); when returning multiple rows.
On a single page I have to return single rows and multiple rows from 2 separate tables.
Table users contains general information like the user name, full name, and email address.
Table user_links contains links submitted by the respective user and has multiple rows for each user.
My query
$this->db->select('*');
$this->db->from('users');
$this->db->join('user_links', "user_links.user_id = users.user_id");
$this->db->where('users.user_id', $user_id);
$this->db->where('user_links.user_id', $user_id);
$query = $this->db->get();
return $query->row();
In my controller I load the query in my view by
$data['row'] = $this->User_model->user_read($user_id);,
$user_id being the 3rd URL segment containing the unique user id.
Finally, in my view I retrieve rows by echo $row->first_name;
This works for single rows but how can I create a foreach loop for user links? The goal is to avoid loops for single rows and use them just for retrieving multiple rows.
This is psuedo code but you can probobly do something like this
$this->db->select('*');
$this->db->from('users');
$this->db->join('user_links', "user_links.user_id = users.user_id");
$this->db->where('users.user_id', $user_id);
$this->db->where('user_links.user_id', $user_id);
$query = $this->db->get();
if ($query->num_rows() == 1)
{
return $query->row();
}
elseif ($query->num_rows() > 1)
{
return $query->result_array(); //This returns an array of results which you can whatever you need with it
}
else
{
//Add some logic to handle if there are zero results
}
If I understand your question correctly, you want to get both the user data as well as user_links data with a single query while avoiding iterating through it to get the user's data. While this may be possible using result_array, I would advise against it since you will get 0 results when there are no entries in user_links for that particular user.
My suggestion is that you use two queries, one to get the user from the user table, another to get user's links from user_links table. This will also help you avoid joins.
Hard to tell what you want.
You want a function that checks if you're passing a row() or a result() and treat them accordingly.
In my opinion your code would be easier to read (and maintain) if you just passed everything as a result(). And do check if the set is empty to show a nice message to the user.
Sounds like you're looking for some of the other features already provided by CI's Active Record: http://codeigniter.com/user_guide/database/results.html
For what you are doing it sounds like using the built in function result_array would work. You use it like so:
TAKEN FROM LINK ABOVE
$query = $this->db->query("YOUR QUERY");
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
You can just replace this line:
$this->db->join('user_links', "user_links.user_id = users.user_id");
With this one:
$this->db->join('user_links', "user_links.user_id = users.user_id", 'left outer');
Join in codeigniter uses INNER JOIN by default but in some cases if there is no data in user_links it returns nothing so u can use LEFT JOIN in your frame work CI it used like i mentioned above.