I have this code on my controller:
$sql = "SELECT * FROM user WHERE id = " . $this->input->get('foo');
$foo = $this->db->query($sql);
echo '<pre>';
print_r($foo->result());
echo '</pre>';
die();
I've noticed that if I use this URL:
www.site.com?foo=1 OR 1 = 1
all data of the user table is shown:
Array
(
[0] => stdClass Object
(
[id] => 1
[email] => aaa#gmail.com
[password] => aaa
)
[1] => stdClass Object
(
[id] => 1
[email] => bbb#gmail.com
[password] => bbb
)
[2] => stdClass Object
(
[id] => 1
[email] => ccc#gmail.com
[password] => ccc
)
)
Is it possible to run another query that returns the data from the user_phone table?
Tables:
CREATE TABLE `user` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`email` VARCHAR(100) NOT NULL,
`password` VARCHAR(255) NOT NULL
PRIMARY KEY (`id`),
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
CREATE TABLE `user_phone` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`id_user` INT(11) UNSIGNED NOT NULL,
`number` INT(11) UNSIGNED NOT NULL
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
Data:
INSERT INTO `user`(`email`,`password`) VALUES ('aaa#gmail.com','aaa');
INSERT INTO `user`(`email`,`password`) VALUES ('bbb#gmail.com','bbb');
INSERT INTO `user`(`email`,`password`) VALUES ('ccc#gmail.com','ccc');
INSERT INTO `user_phone`(`id_user`,`number`) VALUES ('1','911911911');
INSERT INTO `user_phone`(`id_user`,`number`) VALUES ('1','922922922');
INSERT INTO `user_phone`(`id_user`,`number`) VALUES ('2','955955955');
INSERT INTO `user_phone`(`id_user`,`number`) VALUES ('3','711711711');
Thks
EDIT:
I'm aware of the existing mechanisms to prevent this from happening.
My question is if it's possible, and how, can I get data from other tables.
I think it's going to be like this.
www.site.com?foo=1 OR 1 = 1 union select * from user_phone where user_phone.id_user = user.id
CI comes with functions to escape variables for exactly this reason.
$foo = $this->input->get('foo');
$foo = $this->db->escape($foo);
$sql = "SELECT * FROM user WHERE id = {$foo}";
$foo = $this->db->query($sql);
echo '<pre>';
print_r($foo->result());
echo '</pre>';
die();
You should be able to bind your query using something like this:
$sql = "SELECT * FROM user WHERE id = ? AND name = ?";
$foo = $this->db->query($sql, array('foo', 'bar'));
As for getting data from other tables, you'd just need to construct a more elaborate sql query
You asked about querying data from 2 tables, to query 2 related tables you can use join. In your example user and user_phone are related. You perform sql queries with join like demo below. The user primary_key is the glue in user_phone table.
1 - select *
2 - pass the id we want to retrieve
3 - from which table
4 - perform a join or multiple joins
5 - get the result
try this
$this -> db -> select('*');
$this -> db -> where('id' => '1');
$this -> db -> from('user');
$this -> db -> join('user_phone', 'user_phone.id_user = user.id');
$query = $this -> db -> get();
Related
I have two tables, one with all the user data and one with some orders.
the order is always for one user, but made from another user (user can't order for his self)
in the order table the editor and the user are only stored with their id corresponding to the user table.
here the shortened tables:
`orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(10) NOT NULL,
`editor_id` int(10) NOT NULL,
`reason` char(200) COLLATE utf8_unicode_ci NOT NULL,
`amount` decimal(10,2) NOT NULL
)
`users` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` char(250) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`password` varchar(32) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`email` varchar(250) COLLATE utf8_unicode_ci NOT NULL DEFAULT ''
)
i want to query one of the orders, and get the user_id replaced with user_name and editor_id also replaced with the correct name from the users table.
this is what a normal orders query result looks like:
[0] => Array
(
[id] => 714
[user_id] => 97
[editor_id] => 45
[reason] => Ausgaben Regale 28.09.13
[amount] => 150.00
)
and this is what i want:
[0] => Array
(
[id] => 714
[user_id] => 97
[editor_id] => 45
[user_name] => the user name
[editor_name] => the editor name
[reason] => Ausgaben Regale 28.09.13
[amount] => 150.00
)
I tried so many different joins, but all without success, would love to get the hint pointing me to the right direction.
This?
SELECT o.id, o.user_id, o.editor_id, u1.name as user_name, u2.name as editor_name,
o.reason, o.amount
FROM orders o
INNER JOIN users u1 ON o.user_id = u1.id
INNER JOIN users u2 ON o.editor_id = u2.id
WHERE o.id = "requested order id"
SELECT orders.*,user.name as user_name,editor.name as editor_name FROM orders
inner join users user on orders.user_id=user.id
inner join users editor on orders.editor_id=editor.id where orders.id="requested id"
Im going to try my best to explain myself. Not 100% sure how to word this. I have data in multiple tables something like
tbl_rooms
tbl_tables
tbl_people_sitting_at_table
All these tables have there linking id's and what I want to do is build a "room" object and not query the db in the loops. Right now what i have is something like this
Pseudocode
foreach ($rooms as $room) {
$room->tables = get_all_the_table_by_room_id($room->room_id);
.....
foreach ($room->tables as $table) {
$table->people_sitting_at_table = get_all_the_people_by_table_id($table->table_id);
What I have work but I don't like the amount of queries required to build the object. Heres is an example what I am looking to send back
stdClass Object
(
[id] => 15
[room_name] => room_name
[tables] => Array
(
[0] => stdClass Object
(
[id] => 34
[table_name] => table_name
[people_sitting_at_table] => Array
(
[0] => stdClass Object
(
[id] => 45
[name] => name
What im having a hard time with is knowing how to organize all that if i was to get all the data up front.. If I get all the tables in the room and then all the people at all the tables how do i get the people nested under the right table efficiently
Not sure if this enough info to get my point across, if not let me know
Here is some SQL for the exaple
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
CREATE TABLE `tbl_people_sitting_at_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`table_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `tbl_people_sitting_at_table` (`id`, `name`, `table_id`) VALUES
(1, 'jim', 1),
(2, 'bob', 1);
CREATE TABLE `tbl_rooms` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `tbl_rooms` (`id`, `name`) VALUES
(1, 'room one'),
(2, 'room two');
CREATE TABLE `tbl_tables` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`room_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `tbl_tables` (`id`, `name`, `room_id`) VALUES
(1, 'table one', 1),
(2, 'table two', 1);
I think you are looking for something called the model-mapper design pattern.
Your model is a simple class that stores the columns in the database. You create one model instance per row. The mapper does your actual sql queries, then loads each row into a new model instance. So for instance, you would have a Room model and a Room Mapper. Then you have a PersonRoom model and a PersonRoom mapper. The PersonRoom mapper would let you select all PersonRooms that have a given room ID.
One thing you can look at that does this for you is Doctrine. Alternatively, you can just write it yourself. I wrote a code generator so that I can just point the code generator at the table and it will write the model/mapper code for me. I can then just use the models and mappers.
How would I get the banner name? If you look at the DB below you will see that this bring back everything apart from the actual banner.name?
Also I presume that it should check that the banner status to check it is enabled.
BEFORE:
SELECT *
FROM banner_image bi
LEFT JOIN banner_image_description bid ON (bi.banner_image_id = bid.banner_image_id)
WHERE
bi.banner_id = '".$banner_id."'
AND bid.language_id = '".$this->config->get('config_language_id')."'
Array (
[0] => Array (
[banner_image_id] => 1
[banner_id] => 1
[link] =>
[image] => data/banners/test.jpg
[language_id] => 1
[title] => Test banner
)
)
AFTER:
SELECT
bi.*,
b.name
FROM
banner b,
banner_image bi
LEFT JOIN banner_image_description bid ON (bi.banner_image_id = bid.banner_image_id)
WHERE
b.banner_id = '".$banner_id."'
AND bi.banner_id = '".$banner_id."'
AND bid.language_id = '".$this->config->get('config_language_id')."'
Array (
[0] => Array (
[banner_image_id] => 1
[banner_id] => 1
[link] =>
[image] => data/banners/test.jpg
[name] => Banner heading
)
)
DB Structure:
CREATE TABLE IF NOT EXISTS `banner` (
`banner_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) COLLATE utf8_bin NOT NULL,
`status` tinyint(1) NOT NULL,
PRIMARY KEY (`banner_id`)
);
CREATE TABLE IF NOT EXISTS `banner_image` (
`banner_image_id` int(11) NOT NULL AUTO_INCREMENT,
`banner_id` int(11) NOT NULL,
`link` varchar(255) COLLATE utf8_bin NOT NULL,
`image` varchar(255) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`banner_image_id`)
);
CREATE TABLE IF NOT EXISTS `banner_image_description` (
`banner_image_id` int(11) NOT NULL,
`language_id` int(11) NOT NULL,
`banner_id` int(11) NOT NULL,
`title` varchar(64) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`banner_image_id`,`language_id`)
);
I think this will do what you want:
SELECT *
FROM
banner b
INNER JOIN banner_image bi ON b.banner_id = bi.banner_id
INNER JOIN banner_image_description bid ON bi.banner_image_id = bid.banner_image_id
WHERE
b.banner_id = '". $banner_id ."'
AND b.status = TRUE
AND bid.language_id = '". $this->config->get('config_language_id') ."'
I would avoid using SELECT * and instead, explicitly list out each column you actually want to fetch.
One reason I think you were having trouble is that you used a comma (implicit join) to join in the banner table, but you didn't specify a join condition. You would have needed a condition in your WHERE clause like b.banner_id = bi.banner_id. But it would be better to use explicit INNER JOIN syntax.
I don't see a reason for using a LEFT JOIN instead of an INNER JOIN in this query. In the WHERE clause, you specify a condition that must be met in the banner_image_description table in order for a row to be returned. If there is no corresponding row in that table (which is the purpose of a LEFT JOIN), then there will be no row returned. So I switched them to INNER JOIN.
I have the following SQL Query:
SELECT
upd.*,
usr.username AS `username`,
usr.profile_picture AS `profile_picture`
FROM
updates AS upd
LEFT JOIN
subscribers AS sub ON upd.uid=sub.suid
LEFT JOIN
users AS usr ON upd.uid=usr.uid
WHERE
upd.deleted='0' && (upd.uid='118697835834' || sub.uid='118697835834')
GROUP BY upd.id
ORDER BY upd.date DESC
LIMIT 0, 15
where i get all user(118697835834) updates, his profile picture from another table using left join and also all his subscription users updates so can i show them in his newsfeed.
However as the updates get more and more so the query takes more time to load... right now using Codeigniter's Profiler i can see that the query takes 1.3793...
Right now i have created around 18k dummy accounts and subscribed from to me and vice versa so i can test the execution time... the times that i get are tragic considering that i am in localhost...
I also have some indexes where i suppose need more in the users table(username and uid as unique), updates table(update_id as unique and uid as index)
I suppose i am doing something wrong to get so bad results...
EDIT:
Running EXPLAIN EXTENDED result:
Array
(
[0] => stdClass Object
(
[id] => 1
[select_type] => SIMPLE
[table] => upd
[type] => ALL
[possible_keys] => i2
[key] =>
[key_len] =>
[ref] =>
[rows] => 22
[filtered] => 100.00
[Extra] => Using where; Using temporary; Using filesort
)
[1] => stdClass Object
(
[id] => 1
[select_type] => SIMPLE
[table] => sub
[type] => ALL
[possible_keys] =>
[key] =>
[key_len] =>
[ref] =>
[rows] => 18244
[filtered] => 100.00
[Extra] => Using where
)
[2] => stdClass Object
(
[id] => 1
[select_type] => SIMPLE
[table] => usr
[type] => eq_ref
[possible_keys] => uid
[key] => uid
[key_len] => 8
[ref] => site.upd.uid
[rows] => 1
[filtered] => 100.00
[Extra] =>
)
)
EDIT2: SHOW CREATE of Tables
Users table:
CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`uid` bigint(20) NOT NULL,
`username` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`email` text CHARACTER SET latin1 NOT NULL,
`password` text CHARACTER SET latin1 NOT NULL,
`profile_picture_full` text COLLATE utf8_unicode_ci NOT NULL,
`profile_picture` text COLLATE utf8_unicode_ci NOT NULL,
`date_registered` datetime NOT NULL,
`activated` tinyint(1) NOT NULL,
`closed` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uid` (`uid`),
UNIQUE KEY `username` (`username`)
) ENGINE=MyISAM AUTO_INCREMENT=23521 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Subscribers table:
CREATE TABLE `subscribers` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`sid` bigint(20) NOT NULL,
`uid` bigint(20) NOT NULL,
`suid` bigint(20) NOT NULL,
`date` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=18255 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Updates table:
CREATE TABLE `updates` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`update_id` bigint(19) NOT NULL,
`uid` bigint(20) NOT NULL,
`type` text COLLATE utf8_unicode_ci NOT NULL,
`update` text COLLATE utf8_unicode_ci NOT NULL,
`date` datetime NOT NULL,
`total_likes` int(11) NOT NULL,
`total_comments` int(11) NOT NULL,
`total_favorites` int(11) NOT NULL,
`category` bigint(20) NOT NULL,
`deleted` tinyint(1) NOT NULL,
`deleted_date` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `i1` (`update_id`),
KEY `i2` (`uid`),
KEY `deleted_index` (`deleted`)
) ENGINE=MyISAM AUTO_INCREMENT=23 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Try this one (without the GROUP BY):
SELECT
upd.*,
usr.username AS `username`,
usr.profile_picture AS `profile_picture`
FROM
updates AS upd
LEFT JOIN
users AS usr
ON upd.uid = usr.uid
WHERE
upd.deleted='0'
AND
( upd.uid='118697835834'
OR EXISTS
( SELECT *
FROM subscribers AS sub
WHERE upd.uid = sub.suid
AND sub.uid = '118697835834'
)
)
ORDER BY upd.date DESC
LIMIT 0, 15
At least the columns that are used in Joins should be indexed: updates.uid, users.uid and subscribers.suid.
I would also add an index on subscribers.uid.
Try:
SELECT
upd.*,
usr.username AS `username`,
usr.profile_picture AS `profile_picture`
FROM
updates AS upd
LEFT JOIN
subscribers AS sub ON upd.uid=sub.suid
LEFT JOIN
users AS usr ON upd.uid=usr.uid
WHERE
upd.deleted=0 and upd.uid in (118697835834,118697835834)
GROUP BY upd.id
ORDER BY upd.date DESC
LIMIT 0, 15
Note that ' has been removed from numeric values and bitwise operators changed to conventional operators.
don't use joins, try this one:
select *,
(select username from users where uid = upd.uid) as username,
(select profile_picture from users where uid = upd.uid) as profile_picture,
from updates as upd
WHERE
upd.deleted='0' && upd.uid='118697835834'
(not tested!)
maybe you have to check if there exists a subscriber in the where-clause with another sub-select.
Another way would be to make a join on sub-selects and not on the whole table. This may increase your performance also.
Shouldn't take too long to run; do you have an index on 'deleted'? What is the 'GROUP BY id' doing? Should it be UID? Can it come out, if ID is in fact just an auto increment, unique ID? (which would be expensive as well as pointless)
I think you'll be best separating this query into a select on the user table and then union those results with the select on the subscribers table.
I have following query:
CREATE TABLE `test` (
`col1` INT( 10 ) NOT NULL ,
`col2` VARCHAR( 50 ) NOT NULL ,
`col3` DATE NOT NULL
) ENGINE = MYISAM ;
I want to write a general php script that get table name(test) from above query.
If you can access the string which gets queried before you run the query, you can do this:
preg_match("/^create table `(?P<tablename>)`/i", $query, $matches);
print_r($matches);
/*
Output:
Array
(
[0] => CREATE TABLE `test` (`col1` INT( 10 ) NOT NULL ,`col2` VARCHAR( 50 ) NOT NULL , `col3` DATE NOT NULL ) ENGINE = MYISAM ;
[tablename] => test
[1] => test
)
*/
If you can't access the string for some reason, but you know that nothing is created in the database between the query and your code then you can use this query to retrieve the last created table:
SELECT
*
FROM
information_schema.TABLES
ORDER BY
CREATE_TIME DESC
LIMIT
1;