mysql one translates table vs multiple translate table - php

I am trying to design a structure translate(en -> fr) for all system.
my database :
translates(id,table,key_for_search,column_to_translate,lang,translate)
id | table | key_for_search | column_to_translate | lang | translate
1 | posts | 2 | title | en | hello
2 | posts | 2 | title | sp | hola
add translate to new table or when exists is possible.
this way is good ?

thanks for reply.
sorry for my bad english.
I think I talked unclear.
my tables for example:
--
-- Table structure for table `posts`
--
CREATE TABLE IF NOT EXISTS `posts` (
`id` int(11) NOT NULL,
`title` varchar(100) NOT NULL,
`content` mediumtext
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `posts`
--
INSERT INTO `posts` (`id`, `title`, `content`) VALUES
(1, 'hello', 'hello how are you ?');
-- --------------------------------------------------------
--
-- Table structure for table `translates`
--
CREATE TABLE IF NOT EXISTS `translates` (
`id` int(11) NOT NULL,
`table` varchar(255) NOT NULL,
`key` int(11) NOT NULL,
`column` varchar(255) NOT NULL,
`lang` varchar(3) NOT NULL,
`translate` text NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `translates`
--
INSERT INTO `translates` (`id`, `table`, `key`, `column`, `lang`, `translate`) VALUES
(1, 'posts', 1, 'title', 'es', 'Hola'),
(2, 'posts', 1, 'content', 'es', 'Hola, cómo estás?');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `posts`
--
ALTER TABLE `posts`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `translates`
--
ALTER TABLE `translates`
ADD PRIMARY KEY (`id`), ADD KEY `table` (`table`,`key`,`column`,`lang`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `posts`
--
ALTER TABLE `posts`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `translates`
--
ALTER TABLE `translates`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=3;
and my query for get translate
select `column`,`translate` from `translates` where `table` = 'posts' && (`column` = 'title' || `column` = 'content') && `key` = 1 && `lang` = 'es' #Spanish translate
why me using this way ?
because i can in future add new table and I do not need for new design table or new programming
this is a good idea ?

Perhaps a simpler table:
xid -- code that is in the other table
lang -- language of 'xlation' column
xlation -- the translation in `lang` (use utf8 for this column)
xid could be an INT and you simply ask for another entry. Or it could be a short string. Or it could be the English version.
You would need
PRIMARY KEY(xid, lang)
and you might need this to avoid dups:
UNIQUE(lang, xlation)
Now... Think through the dataflow and what INSERTs and SELECTs you will need. You may have more questions.
(Update):
xid | lang | xlation
Hello | en | Hello
Hello | sp | hola
hello how are you ? | en | Hello. How are you?
hello how are you ? | sp | Hola. ¿Coma estas?

Related

Mysql queries works fine in local host but not in server

I am trying to upload some images to my database with some data, when I do this in localhost it's all work fine. But on the server, only some queries work fine. but others are not working.
This is my database pages table and papertag table
CREATE TABLE `pages`
(
`pageId` int(10) NOT NULL,
`paperId` varchar(255) NOT NULL,
`filePath` varchar(255) NOT NULL,
`fileType` varchar(20) NOT NULL,
`status` enum('0','1') NOT NULL,
`dateAndTime` datetime NOT NULL,
`description` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `pages`
--
ALTER TABLE `pages`
ADD PRIMARY KEY (`pageId`),
ADD KEY `paperId` (`paperId`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `pages`
--
ALTER TABLE `pages`
MODIFY `pageId` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=324;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `pages`
--
ALTER TABLE `pages`
ADD CONSTRAINT `pages_ibfk_1` FOREIGN KEY (`paperId`) REFERENCES `papers` (`paperId`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
-----paper tag------
CREATE TABLE `papertag`
(
`tagId` int(11) NOT NULL,
`paperId` varchar(255) NOT NULL,
`tagName` varchar(255) NOT NULL,
`des` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `papertag`
--
ALTER TABLE `papertag`
ADD PRIMARY KEY (`tagId`),
ADD KEY `paperId` (`paperId`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `papertag`
--
ALTER TABLE `papertag`
MODIFY `tagId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=460;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `papertag`
--
ALTER TABLE `papertag`
ADD CONSTRAINT `papertag_ibfk_1` FOREIGN KEY (`paperId`) REFERENCES `papers` (`paperId`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
and this is my SQL query code in PHP file
$up22 = mysqli_query($connection, "INSERT INTO papertag(`paperId`, `tagName`) VALUES ('{$paperId}', '{$nme}')");
$up = mysqli_query($connection, "INSERT INTO pages(`paperId`, `filePath`, `fileType`, `status`, `dateAndTime`) VALUES ('{$paperId}', '{$img_dir}', '{$type}',2 , '{$date}' )");
I think you have to insert all columns with not null Constraint. you did not insert des column for example.
you need this code :
$up22 = mysqli_query($connection, "INSERT INTO papertag(`paperId`, `tagName`,`des`) VALUES ('{$paperId}', '{$nme}'),'{$des}'");

Show all user posts in one page but query is too slow

I try to show the videos and pictures shared by the members in one page. The query I wrote works fine but is very slow. I don't know why this happened. That's why I need your help. You can also see the conditions I wrote in the following query.
Here is the sqlFiddle
$morequery="";
if($lastpostid) {
$morequery=" AND P.user_post_id<'".$lastpostid."' ";
}
$GetAllPostQuery = mysqli_query($this->db,"SELECT
P.user_post_id,
P.user_id_fk,P.post_type,
P.who_can_see_post,
P.post_image_id,P.post_video_id,
P.post_video_name,
U.user_name, U.user_fullname,U.influencer_status
FROM user_posts P
INNER JOIN users U
ON P.user_id_fk = U.user_id
WHERE
U.user_status='1' AND
U.influencer_status = '1' AND
(P.who_can_see_post IN('everyone','influencer','friends')) AND
(P.post_type IN('image','video')) $morequery
ORDER BY
P.user_post_id
DESC LIMIT " .$this->perpage) or die(mysqli_error($this->db));
//Store the result
while($row=mysqli_fetch_array($GetAllPostQuery)) {
// Store the result into array
$data[]=$row;
}
if(!empty($data)) {
// Store the result into array
return $data;
}
The Users Table Here:
-- phpMyAdmin SQL Dump
-- version 4.8.3
-- https://www.phpmyadmin.net/
--
-- Host: localhost:8889
-- Generation Time: Sep 10, 2019 at 11:56 AM
-- Server version: 5.7.23
-- PHP Version: 7.2.10
CREATE TABLE `users` (
`user_id` int(11) NOT NULL,
`user_name` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`user_status` enum('0','1','2','3') NOT NULL DEFAULT '0',
`user_fullname` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`influencer_status` enum('0','1') NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`user_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
And The User Posts Table Here:
CREATE TABLE `user_posts` (
`user_post_id` int(11) NOT NULL,
`user_id_fk` int(11) DEFAULT NULL,
`post_type` enum('text','image','link’,’video','audio','avatar','cover','gif','location','watermark','which','page','event','blog','group','product','bfaf','inf') NOT NULL DEFAULT 'text',
`post_created_time` int(11) NOT NULL DEFAULT '1524910573',
`who_can_see_post` enum('everyone','onlyme','friends','influencer') NOT NULL DEFAULT 'everyone',
`post_video_id` varchar(255) DEFAULT NULL,
`post_video_name` varchar(255) DEFAULT NULL,
`post_audio_id` varchar(255) DEFAULT NULL,
`post_image_id` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for table `user_posts`
--
ALTER TABLE `user_posts`
ADD PRIMARY KEY (`user_post_id`),
ADD KEY `ex_posts` (`user_id_fk`);
--
-- AUTO_INCREMENT for table `user_posts`
--
ALTER TABLE `user_posts`
MODIFY `user_post_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
--
-- Constraints for table `user_posts`
--
ALTER TABLE `user_posts`
ADD CONSTRAINT `ex_posts` FOREIGN KEY (`user_id_fk`) REFERENCES `users` (`user_id`);
What should I do to make the query work faster? Can you help me.
The fiddle contains too few rows to reproduce the problem but these 2 indexes might help.it really depends on your data distribution.
ALTER TABLE users ADD KEY(user_status,influencer_status);
ALTER TABLE user_posts ADD KEY(who_can_see_post,post_type);

one to many relation-displays first row only

after going through many attempts, i finally can display data from child table. I have 2 tables, user (parent) and useradvert(child).
user
-id (pk)
-name
-username
-telno
useradvert
-id(index)
etc.........
it's a 1 to many relation. from table users to table useradvert. table users suppose to pull many rows from table useradvert based on specific id which matches id in table users. But, instead it only display first row from useradvert. No matter how you login with different username, you will always see the first row from useradvert and not the rows that is supposed to display. For ur info, I'm a newbie. Any help is appreciated. tqs.
below is extract;
$query = "SELECT * FROM users,useradvert WHERE users.id=useradvert.id";
$stmt = $conn->prepare($query);
$stmt->execute();
$res = $stmt->get_result();
$row2 = $res->fetch_array();
$_SESSION['name2'] = $row2['name2'];
$_SESSION['color2'] = $row2['color2'];
$_SESSION['hobby2'] = $row2['hobby2'];
$_SESSION['radiobtn'] = $row2['radiobtn'];
$_SESSION['kupon'] = $row2['kupon'];
$_SESSION['image'] = $row2['image'];
$_SESSION['image2'] = $row2['image2'];
below is extract -continue on same page
<?php
//display record from table- useradveret -(child table)
// while($row = $res->fetch_array()){
echo $_SESSION['name2']."<br/>";
echo $_SESSION['color2']."<br/>";
echo $_SESSION['hobby2']."<br/>";
echo $_SESSION['radiobtn']."<br/>";
echo $_SESSION['kupon']."<br/>";
echo $_SESSION['image']."<br/>";
echo $_SESSION['image2']."<br/>";
// }
?>
table query for useradvert
-- Table structure for table useradvert
CREATE TABLE IF NOT EXISTS `useradvert` (
`id` int(10) unsigned NOT NULL,
`name2` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`color2` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`hobby2` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`radiobtn` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`kupon` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`image` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`image2` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `useradvert`
--
INSERT INTO `useradvert` (`id`, `name2`, `color2`, `hobby2`, `radiobtn`, `kupon`, `image`, `image2`) VALUES
(97, 'testthree nickname', 'colorthree', 'hobbythree', 'female', '', 'uploads/testpic1.jpg', 'uploads/testpic2.jpg'),
(99, 'testfivenamecick', 'testfivehcolor', 'testfivecolor', 'female', '', 'uploads/testpic3.jpg', 'uploads/testpic4.jpg'),
(97, 'lagitestthree', 'trheecolor', 'threehobby', 'female', '', 'uploads/testpic5.jpg', 'uploads/testpic6.jpg');
--
-- Constraints for dumped tables
--
--
-- Constraints for table `useradvert`
--
ALTER TABLE `useradvert`
ADD CONSTRAINT `useradvert_ibfk_1` FOREIGN KEY (`id`) REFERENCES `users` (`id`);
I guess your sql query is not correct. Yo use the id field of useradvert table, but that is the index field of that table. That looks wrong. You should have a foreign key userId in useradvert table for the join. Then you query should look something like this:
SELECT * FROM users u
INNER JOIN useradvert ua ON u.id = ua.userId
Then you should get all useradvert fields for the user.
The 2 tables should look something like this:
Table user:
id | name | ...
1 | Ben | ...
2 | Markus | ...
Table useradvert:
id | userid | ...
1 | 1 | ...
2 | 1 | ...
userid in useradvert is the foreign key to create the relationship between the 2 tables. Does that make sense?

MySQL for Test Website

I am making a website similar to Moodle. It basically holds tests for students. The confusion comes in when allowing multiple types of questions on the tests and how to create the tables to store the data.
The test_info table will contain the test ID and description.
The test table will contain Test ID and Question ID pairs.
To get the questions for a test this will require a "SELECT * FROM test WHERE testID=$tID" which will take a substantial amount of time to execute when the database gets large.
Originally the questions table contained the question, 4 possibilities and the answer.
How should I store the data for multiple questions and multiple types of questions in a database?
For Example:
Test 51 - "Intro Mathmatics"
Question 1: What is 2+2?
A: 4 B: 12
C: 7 D: 8
Question 2: (0,103) is the range for the equation y=2x/(100x)?
True False
This results in data with 2 different sizes
Questions:
| Question | A | B | C | D | Correct |
| Question | Correct |
If I store these in 1 table it will waste 4 50Char Var-Chars per question and if I store these in 2 separate tables, how will the SELECT know which table to select from?
Questions:
| TestID | TableID | QuestionID |
Questions1:
| Ques | A | B | C | D | Correct |
Questions2:
| Ques | A | B | C | D | Correct |
What a nightmare.
Put the answer in their own table:
answers (answer_id, question_id, description, sequence)
and put the correct answer_id in the question table.
An empty VARCHAR(50) only needs six bits, which means that it will (most likely) take up one byte only on the disk. The VAR in VARCHAR means that the space usage will adapt to the actual data. This means that using one table will "waste" only four bytes per question.
Since you have two types of questions that you handle in two different ways in the code, your two-table approach is viable as well.
The recommended approach is:
Note that four-answer questions and yes-no questions are both special cases of a multiple-choice question. Store these in the database. One possible schema:
question: question_id (PK), test_id (FK), text
answer: answer_id (PK), question_id (FK), text, is_correct
PK = primary key, FK = foreign key
I think you data structure will be like this:
Table1 :Test
id:
TestName:
Table2: Questions:
id:
test_id:
Question:
Answer: //say a,b,c,d
Table3:Answers
id:
question_id:
Anwser Option: //say a,b,c,d
Answer:
Sql For tables with data:
The data will help you in understanding the structure.
CREATE TABLE IF NOT EXISTS `Tests` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`Test` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `test2`
--
INSERT INTO `test2` (`id`, `Test`) VALUES
(1, 'Test1');
//////////////////////////////////////
CREATE TABLE IF NOT EXISTS `questions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`test_id` int(11) NOT NULL,
`Question` varchar(255) NOT NULL,
`Answer` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `questions`
--
INSERT INTO `questions` (`id`, `test_id`, `Question`, `Answer`) VALUES
(1, 1, 'question1', 'a'),
(2, 2, 'Question2', 'd');
////////////////////////////////////////////////////
CREATE TABLE IF NOT EXISTS `answers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`question_id` int(11) NOT NULL,
`answer_option` varchar(10) NOT NULL,
`Answer` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
--
-- Dumping data for table `answers`
--
INSERT INTO `answers` (`id`, `question_id`, `answer_option`, `Answer`) VALUES
(1, 1, 'a', 'True'),
(2, 1, 'b', 'False'),
(3, 2, 'a', 'Asnwer1'),
(4, 2, 'b', 'Answer2'),
(5, 2, 'c', 'Answer3'),
(6, 2, 'd', 'Answer4'),
(7, 2, 'e', 'Answer5');

How to store multiple dynamic values within one field in MySQL?

How can I go about storing multiple values (numbers and words) within one field of a MySQL database and then extracting them again as and when I need them using MySQL and PHP?
For example, I want to store the dynamic values a user will enter using a form for example 1, 2, foo, tree, and monkey all in the same field in a database.
Then I want to extract it and put them on separate lines for example:
1
2
foo
tree
monkey
Any ideas?
MySQL 5.7.8 has a new data type that is JSON. You can store a JSON string with all the user information in that column.
Example:
CREATE TABLE table1 (jsonString JSON);
INSERT INTO table1 VALUES('{"car": "bmw", "year": "2006", "key": "value" }');
MySQL Reference
You can put all the values into an array and then serialize it:
$string = serialize(array(1, 2, 'foo', 'tree', 'monkey');
This will give you a string which you store in your database. Later, you can recover your array with de-serializing it:
$array = unserialize($string);
If you're referring to a datatype which can handle a whole slew of stuff, you can use text otherwise this is a bad idea and this is not how you should be storing data in a normalized relational database. Can you please provide information on what you're storing?
I'm a SQL noob myself so if any guru has a better schema strategy, let me know.. this is what I came up with:
Dump:
/*
Navicat MySQL Data Transfer
Date: 2009-10-20 03:01:18
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `job_scores`
-- ----------------------------
DROP TABLE IF EXISTS `job_scores`;
CREATE TABLE `job_scores` (
`job_id` int(2) NOT NULL,
`user_id` int(2) NOT NULL,
`rating` tinyint(2) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- ----------------------------
-- Records of job_scores
-- ----------------------------
INSERT INTO `job_scores` VALUES ('1', '1', '10');
-- ----------------------------
-- Table structure for `jobs`
-- ----------------------------
DROP TABLE IF EXISTS `jobs`;
CREATE TABLE `jobs` (
`id` int(2) NOT NULL auto_increment,
`name` varchar(50) collate utf8_unicode_ci default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- ----------------------------
-- Records of jobs
-- ----------------------------
INSERT INTO `jobs` VALUES ('1', 'plumber');
-- ----------------------------
-- Table structure for `users`
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(2) NOT NULL auto_increment,
`name` varchar(50) collate utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('1', 'John');
Example query:
SELECT
jobs.name as job_name, users.name as user_name, job_scores.rating
FROM
job_scores
INNER JOIN jobs ON jobs.id = job_scores.job_id
INNER JOIN users on users.id = job_scores.user_id
WHERE
user_id = 1
Result:
plumber John 10

Categories