I am using
$row = mysqli_fetch_row(mysqli_query($conx, "SHOW CREATE TABLE $table"));
in a loop to grab my schema data, that works fine.
I also need put the column names in an array.
Is there a way to pull them from that $row array?
Or do I need to run a separate SHOW COLUMNS to do that?
If you take the create table result whic will look like this:
CREATE TABLE `TableName` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`message` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
You could create a regex that looks for "`[a-zA-Z0-9_-]*`" and besides the first match, they will be column names.
Why not use the information_schema?
"SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = '$table'"
Related
I have two tables as below
table halte :
CREATE TABLE `halte` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nama` varchar(255) NOT NULL,
`lat` float(10,6) DEFAULT NULL,
`lng` float(10,6) DEFAULT NULL,
PRIMARY KEY (`id`)
)
table stops :
CREATE TABLE `stops` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_halte` int(11) DEFAULT NULL,
`sequence` int(2) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `id_halte` (`id_halte`)
)
I also have some other tables which don't cause any problems.
Halte table has many to one relation to stop. The problem is when i try to get rows from halte table using right join to table stops, Yii only returns unique rows. Yii won't return same halte's row more once even stop table has more than one record related to same row in halte table.
Here's my code
$haltes = $modelHalte->find()
->rightJoin('stops', 'halte.id = stops.id_halte')
->where(['stops.id_rute'=>Yii::$app->request->get('rute')])
->orderBy('sequence')
->all();
I have tried distinct(false) but no result.
I've also check debugger and it run right query i want :
SELECT `halte`.* FROM `halte` RIGHT JOIN `stops` ON halte.id = stops.id_halte WHERE `stops`.`id_rute`='1' ORDER BY `sequence`
I tried to run that query manually and it returned 29 rows which is what what i want. But in Yii, it only returned 27 rows because 2 rows is same record in halte table.
I know i can achieve this using yii\db\Query, but i want to use ActiveRecord.
Are there any way to work around this?
I would really appreciate your opinion/help.
Thanks.
Check the sql command generated by you active query
$haltes = $modelHalte->find()
->rightJoin('stops', 'halte.id = stops.id_halte')
->where(['stops.id_rute'=>Yii::$app->request->get('rute')])
->orderBy('sequence')
->all();
echo $haltes->createCommand()->sql;
or to get the SQL with all parameters included try:
$haltes->createCommand()->getRawSql();
And compare the code generated by ActiveQuery with your created manually ..
I try to insert Data in the temporary Table, but when i call select last_insert_id() it return allways the same number. I have set the autoincement setting.
In the normal Table works, but when i Copy the normal Table to a temporary Table, then i have the problem with the select last_insert_id().
This is my code:
CREATE TEMPORARY TABLE IF NOT EXISTS suchergebnisse_temp (SELECT * from suchergebnisse);
INSERT INTO suchergebnisse_temp SET datensatzid='2865', datum='2015-05-13 00:00:00', tabelle='task', sortierung1='1';
SELECT LAST_INSERT_ID();
The Normal Table:
CREATE TABLE IF NOT EXISTS `suchergebnisse` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`tabelle` varchar(100) NOT NULL DEFAULT '0',
`datensatzid` bigint(20) NOT NULL DEFAULT '0',
`datum` datetime NOT NULL,
`sortierung1` int(11) NOT NULL COMMENT 'Priorität',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Temporäre Tabelle.';
Can you help me? Thanks :)
I forgot to add the key explicit to the temporary Table. It needs to execute the following code:
ALTER TABLE `suchergebnisse_temp`
CHANGE COLUMN `id` `id` BIGINT(20) NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`id`);
Because with:
CREATE TEMPORARY TABLE IF NOT EXISTS suchergebnisse_temp (SELECT * from suchergebnisse);
copys only the Field Data but not the Key Data. The Key Data must be declared separately.
I'm working on a web site where users can post articles with this table structure :
CREATE TABLE IF NOT EXISTS `articles` (
`id_articles` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_users` int(10) unsigned NOT NULL,
`articles` text NOT NULL,
PRIMARY KEY (`id_articles`),
UNIQUE KEY `id_articles` (`id_articles`),
KEY `id_users` (`id_users`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Each user can 'like' the articles.
Is that the right way below to create a 'like table' :
CREATE TABLE IF NOT EXISTS `articles_likes` (
`id_articles` int(10) unsigned NOT NULL,
`id_users` int(10) unsigned NOT NULL,
KEY `id_articles` (`id_articles`,`id_users`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
It is correct but you will want to add separte indexes on id_articles and id_users (also you might want to name the columns 'id_article' and 'id_user' for sanity).
CREATE TABLE IF NOT EXISTS `article_likes` (
`id_article` int(10) unsigned NOT NULL,
`id_user` int(10) unsigned NOT NULL,
KEY `id_article` (`id_article`),
KEY `id_user` (`id_user`)
) ENGINE=InnoDB;
The reason you want separate indexes is because in mysql if you create an index on columns (A, B) that index will be used in queries having in the where clause column A, or columns A and B.
In your case for example if you made a query "SELECT * FROM article_likes WHERE id_user=X" this query would not use an index.
An ever better option would be to add a combined index and a separate index on the second column from the combined index. Like this:
CREATE TABLE IF NOT EXISTS `article_likes` (
`id_article` int(10) unsigned NOT NULL,
`id_user` int(10) unsigned NOT NULL,
KEY `id_article_user` (`id_article`, `id_user`),
KEY `id_user` (`id_user`)
) ENGINE=InnoDB;
This way you would have optimal performance on queries like 'WHERE id_user=X', "WHERE id_article=X', "WHERE id_article=X AND id_user=Y"
This is a valid way Chris. You can use COUNT() to match the id_articles in the articles_likes table against the current article you are viewing in articles.
$articles_id = 23;
mysql_query("SELECT COUNT(*) FROM articles_likes
WHERE id_articles = ".$articles_id);
You can also just leave COUNT() (MySQL) out and instantly know which users are the "likers" of the articles and use count() (PHP) on the returned Array to duplicate the effect of COUNT() in MySQL.
i would have a total of 3 tables. an articles table, and the user id could be a column in that for users who submit articles , but you need a separate user table since not all users will submit articles (i am assuming), and then a 3rd table for likes, that takes the primary key from users and the primary key from articles and uses them as foreign keys. so each time an article is liked, an entry is made in the 3rd table
I'm making a simple PHP Forum, whereby tags are created alongside the main topic.
The table looks like this:
CREATE TABLE IF NOT EXISTS `topic` (
`topic_id ` int(100) NOT NULL AUTO_INCREMENT,
`topic_head` varchar(5) NOT NULL,
`topic_body` varchar(20) NOT NULL,
`topic_tag` varchar(20) NOT NULL,
`topic_date` varchar(20) NOT NULL,
`topic_owner` varchar(20) NOT NULL,
PRIMARY KEY (`topic_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
Specifically for the tags, I'll be performing a select query in the form of:
$tags = mysql_query("SELECT DISTINCT topic_tags
FROM forum_topics")
while($tags = mysql_fetch_assoc($tags){
$split_tags = "$tags";
$pieces = explode(",", $split_tags);
Currently, topic_tags are in the format tag1,tag2,tag3,tag4
How can I have it in such a way that each topic tag will be associated with each topic?
If I've understood correctly, what you want is another table for tags and then a third table to store the relationships. So:
CREATE TABLE `tags` (
`t_id` int(11) NOT NULL AUTO_INCREMENT,
`t_text` varchar(150) NOT NULL,
`t_datetime` datetime NOT NULL,
PRIMARY KEY (`t_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE `tag_pairs` (
`tp_id` int(11) NOT NULL AUTO_INCREMENT,
`tp_topic_id` int(11) NOT NULL,
`tp_tag_id` int(11) NOT NULL,
`tp_datetime` datetime NOT NULL,
PRIMARY KEY (`tp_id`),
FOREIGN KEY (`tp_topic_id`) REFERENCES topic('topic_id'),
FOREIGN KEY (`tp_tag_id`) REFERENCES tags('t_id')
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Then, to get tags for a topic based on its ID ($THIS_ID):
$query = mysql_query("
SELECT tags.t_text
FROM tags, tag_pairs, topic
WHERE topic.topic_id = '$THIS_ID'
AND tag_pairs.tp_topic_id = topic.topic_id
AND tag_pairs.tp_tag_id = tags.t_id
");
Call the columns just: id, head, body, tag_id (FK), date and user_id (FK)
This is much more understandable and also easier to use. Let me explain:
Right now you are using the columns as: topic_id, but it should be: topic.id. How do you get this? By simply using the tablename + column. So when the table is called topics and you have a column called id, you can use it by saying: topics.id. In the answer above from da5id, I can see that he is using topics.topic_id, a bit overkill isn't it? ;)
Also, read this article about database normal form 3 and google a bit yourself with database+3nf
I've googled my question and read through a bunch of forum posts but I've yet to find the answer I'm looking for hopefully someone here can help me out.
For a project I'm building I've set up the following 3 tables; users, projects and projectUsers.
I've set up a form where I can add users to projects by saving the userID and the projectID in the projectUsers table nothing special so far. The form contains a select element with userIDs that can be connected to a projectID (hidden field).
This form element is filled with a query set up with Zend_Db_Select it selects all the users from the users table and adds it to the select. However I want to filter that result so it excludes all of the users already added to that specific project.
Short version: I have a select element with users filled with a resultset from a (Zend_db_select) database query I want that resultset to be stripped from certain userIDs.
For extra reference the table scheme below:
CREATE TABLE IF NOT EXISTS `projects` (
`projectID` int(11) NOT NULL AUTO_INCREMENT,
`projectName` varchar(255) NOT NULL
PRIMARY KEY (`projectID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `projectUsers` (
`projectUserID` int(11) NOT NULL AUTO_INCREMENT,
`projectID` int(11) NOT NULL,
`userID` int(11) NOT NULL
PRIMARY KEY (`projectUserID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `users` (
`userID` int(11) NOT NULL AUTO_INCREMENT,
`userFirstName` varchar(255) DEFAULT NULL,
`userLastName` varchar(255) DEFAULT NULL
PRIMARY KEY (`userID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Thanks in advance!
addint to Soica Micea ans
$blackList = array(1,3,5,6); //user id which you want to exclude
$db->select()->from('users', '*')
->joinLeft('projectUsers', 'projectUsers.projectUserID = users.userID', null)
->where('projectUsers.projectID = ?', someProjectID)
->where('projectUserID is null')
->where('users.userID not in (?)', implode(',',$blackList))
->query()->fetchAll();
This will select all users that have not been added to a project and ignore users from arrayOfUserIds
select()->from('users', '*')
->joinLeft('projectUsers', 'projectUsers.projectUserID = users.userID', null)
->where('projectUsers.projectID = ?', someProjectID)
->where('projectUserID is null')
->where('users.userID not in (?)', arrayOfUserIds)
->query()->fetchAll();