This is my mysql query
$acountry = 1;
$this->db->where_in('varcountry', $acountry);
$val = $this->db->get('tblagencies')->result();
In database table the varcountry filed is stored like this 1,2,3,4 its type is varchar.Each row in table have multiple countries that is the reason to use varchar datatype.
Here i want to select table rows which have $acountry value in the filed varcountry.
How can i do that?The above code is it correct?
You have choosen a wrong data type for storing a comma separated value 1,2,3,4 into varchar,
you should chose a data-type of set, or normalize into a separate table, like :-
create table country (id, name ...);
create table agencies_country ( agency_id, country_id);
insert into agencies_country (agency_id, country_id)
values (x,1), (x,2), (x,3), (x,4);
// meaning 1,2,3,4 = 4 rows
// grabbing result using inner join
Using set is easier, but common practice is to normalize the data (which require some understanding).
I don't like the active record in codeigniter,
is easy to use (not doubt with this),
but it dis-allowed lost of flexibility
Personally I like the construct my own query,
provided you have the understanding of the table schema (which you have to anyway)
use this query..
$search_field = array('varcountry'=>$acountry)
$result = $this->db->get_where('tblagencies' , $search_field );
but in codeignator you can use your own queries like
$sql = "select * from tblagencies where varcountry like '%acountry%'";
$result = $this->db->query($sql);
Related
I have table with 10 columns and I want to check input value in where clause of the MySQL query.
I want to do something like this. But, when I use this query I am getting an error.
for example :
SELECT * FROM user_data
where poll_title='$poll_title'
and '$voter' IN (user_vote_1,user_vote_2,user_vote_3...user_vote_10)
order by idpoll ASC
user_vote_1 to 10 (value is null'ed in the database) and I want to retrieve only that rows from a column which have $voter value.
I think you need this comparison (Not Sure OfCourse) :-
SELECT * FROM user_data
where poll_title = "$poll_title"
and (user_vote_1 = "$voter"
OR user_vote_2 = "$voter"
OR user_vote_3 = "$voter"
OR user_vote_4 = "$voter"......OR user_vote_10 = "$voter")
order by idpoll ASC
If I've understood what you want to do - return only the column with the value - then would coalesce do the job? This assumes that the value in user_vote_n will either match the value you're looking for or be null, since coalesce returns the first non-null argument.
(untested)
select coalesce(user_vote_1, user_vote_2, user_vote_3, ) as UserVote from user_data
where coalesce(user_vote_1, user_vote_2, user_vote_3, ) = '$voter';
That aside, this looks like a structure that could do with normalising - a single 'user_vote' column and a single 'user_vote_number' column.
I have a table called tblActivities. There are two fields ID and Attendees.
ID Attendees
1 Jon Jhonson
2 Ive Iveson
Which PHP function or MySQL statement do I need to use to get to this result:
ID Attendees
1 Jon Jhonson, Ive Iveson, Adam Adamer
2 Ive Iveson
In other words, how can I add new data to existing data in my database?
You need something like:
UPDATE tblActivities
SET Attendees = CONCAT(Attendees, "Ive Iveson, Adam Adamer")
WHERE id = 1;
But maybe you should change the database layout. It is preferable to have only one value in one field. You could find more information under http://en.wikipedia.org/wiki/Database_normalization.
use mysql's update statement. If you want to exeute through php then
first get the existing value using select statement,
SELECT Attendees from <table-name> WHERE ID = 1
you will get attendees existing value, put it in a php variable, now concatenate your value..
and then update,
UPDATE <table_name>
SET Attendees=<new-value>
WHERE ID=1
you would have to use the php's mysql functions to run the above queries
I think you're better off restructuring. Make a table:
ID (primary key)
ACTIVITY_ID (foreign key to activity table)
ATTENDEE (foreign key to USERS table)
Then select everything from that event and concat in PHP.
$q = mysql_query( 'SELECT ATTENDEE FROM tblActivities '.
'WHERE ACTIVITY_ID = $activity_id' );
$attendees = array();
while( $row = mysql_fetch_assoc( $q ) )
{
$attendees[] = $row['attendee'];
}
$attendees =implode( ' ', $attendees );
I need to select category ids from my sql database.
I have a variable $product_id and for each product id there are three rows in a table that i need to select using PHP.
If I do "SELECT * FROM table_name WHERE product_id='$prodid'"; I only get the one on the top.
How can I select all three category_ids which contain the same product_id?
I suppose you are using PHP's mysql functions, is this correct? I am figuring that your query is actually returning all three rows but you aren't fetching all of them.
$sql = "SELECT * FROM table_name WHERE product_id='$prodid'";
$r = mysql_query($sql, $conn); //where $conn is your connection
$x = mysql_fetch_SOMETHING($r); //where something is array, assoc, object, etc.
The fetch function gives only one row at a time. You say you need three so it needs to be executed three times.
$x[0] = mysql_fetch_assoc($r);
$x[1] = mysql_fetch_assoc($r);
$x[2] = mysql_fetch_assoc($r);
OR this would be better
while($curRow = mysql_fetch_assoc($r)) //this returns false when its out of rows, returns false
{
$categoryIds[] = $curRow['category_id'];
}
If this doesn't do it then your query is actually returning only one row and we need to see your tables/fields and maybe sample data.
SQL seems to be correct, but Why do you store product_id in categories table? if it's one-to-many relation it would be better to store only category_id in products table.
The SQL query is correct for what you want to do. It will select all the records in table_name with the field product_id = $prodid (not only 1 or 3 but any that matches the variable)
To select a few records you should use the LIMIT keyword
You should look inside your table structure and the variable $prodid to find problems.
i have retrieved mysql data from one table in json using the following script
$table_first = 'abc';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);
$set = array();
$total_records = mysql_numrows($resouter);
if($total_records >= 1){
while ($link = mysql_fetch_array($resouter, MYSQL_ASSOC)){
$set[] = $link;
}
}
echo json_encode($set);
how can i retrieved data from two other tables in which there is a foreign key of this table in both of those tables. OR simply how can i retrieved data from 3 mysql tables in php.
I believe the best way to go here is using a JOIN or just something like this:
$sql = "SELECT
tabl1.*, table2.*, tabl3.* FROM table1, table2, table3
WHERE
table1.fk1 = table2.id AND
table1.fk2 = table2.id";
//Do the whole selection process...
If you make the queries separately, you'll be forcing 3 queries onto your database and will end in a performance hit that you dont need. So, the idea is load all the data from the DB using joins or similar that and then encode the results. Is faster and you'll leave the merging work to MySQL
Hope I can help
You can get all data firstly.
Then merge the data array.
Finally use json_encode to change the data format.
There is a foreign key of this table in both so you can use "join" to retrieve values from other tables.
Suppose that there are two tables as State(st_id,st_name) and City(ct_id,ct_name,state_id). Now, primary key are st_id & ct_id respectively of tables State & City.
Connection between this two table can be establish by joining State.st_id and City.state_id.
Now, coming to your problem to retrieve data from two table State & City, we can make sql query like following,
$sql="select s.*, c.* from State s, City c
where s.st_id=c.state_id ";
Using above query you can fetch data from database and convert into json format and can send it to android system. here is a good article http://blog.sptechnolab.com/2011/02/10/android/android-connecting-to-mysql-using-php/. i hope you like it.
I believe your code roughly will look like this:
$query = "SELECT
A.column1 AS First_1
A.column2 AS First_2
B.column2 AS Second
C.column3 AS Third
FROM table1 A, table2 B, table3 C
WHERE
A.fk1 = B.id AND
B.fk2 = C.id";
where a column is a relevant record you want to show. Meanwhile,
AS will act as a key name in JSON.
I have 31 separate tables (actually I have 365, but lets keep this simple) in a MySQL database, each containing data for a given day. The tables are (badly) named based on the day.
Example:
island01Aug07
island02Aug07
island03Aug07
island04Aug07
...
island31Aug07
I would like to combine all the tables into one master table:
island_08
It would be simple to use INSERT INTO but my problem is that the tables do not have a column to denote the day. It would have to be added into the destination table, and then I would need to populate that when moving/copying the tables over.
Suggestions, advice and solutions welcome.
CREATE TABLE island_08 (mydate DATE NOT NULL, field1 …)
INSERT
INTO island_08 (mydate, field1, field2)
SELECT '2007-07-01', field1, field2
FROM island01Aug07
UNION ALL
SELECT '2007-07-02', field1, field2
FROM island02Aug07
UNION ALL
…
As alternative option you can list all tables in to array like table_name=>mysql_date,
after that loop through and copy data from one table and insert in to another. After data was transferred successfully you can remove the table.
Here is example of getting list of tables and extracting date from it:
$prefix = 'island';
$lenght = strlen($prefix);
$result = $this->query("SHOW TABLES LIKE '{$prefix}%'");
$arrayDates = array();
if($db->num_rows($result))
{
while($v = $db->fetch_array($result))
{
$mysql_table = current($v);
$arrayDates[$mysql_table] = date('d-m-Y',strtotime(substr($mysql_table,0,$lenght)));
}
}
//Now you can walk through your array and copy data from one table tyo another and append you mysql value