Creating Tables with MYsql in yii 1.1 - php

Here is the scenario: I have been following the "yii" book by Larry Ullman in which he gave his MYsql for CMS but he didn't described any tool , how to create these tables of sql. The only way I know is through migrations but the sql written in the book is not working in migrations.
The sample sql is given for a table from the book :
CREATE TABLE IF NOT EXISTS yii_cms.user ( id INT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(45) NOT NULL,
email VARCHAR(60) NOT NULL,
pass CHAR(64) NOT NULL,
type ENUM('public','author','admin') NOT NULL,
date_entered TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE INDEX username_UNIQUE (username ASC),
UNIQUE INDEX email_UNIQUE (email ASC) )
ENGINE = InnoDB DEFAULT
CHARACTER SET = utf8

If you don't mind, you can use straight-forward way to execute sql so:
$sql = 'your sql here';
Yii::app()->db->createCommand($sql)->execute();
The other way is to use Yii QueryBuilder and the createTable() command. More information for QueryBuilder is here and for createTable() here.

Related

MariaDB create database relational tables

I created 2 tables as follows:
$sql = "CREATE TABLE users (
id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id VARCHAR(25) UNIQUE NOT NULL,
password VARCHAR(256) NOT NULL,
first_name varchar(25) NOT NULL,
last_name varchar(25) NOT NULL,
email varchar(50) UNIQUE NOT NULL
date_created VARCHAR(25) NOT NULL,
date_modified VARCHAR(25) NOT NULL
)";
This table was created successfully.
I tried to create a 2nd table as follows:
$sql = "CREATE TABLE users_performance (
id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id INT(11) REFERENCES users(id) UNIQUE NOT NULL,
performance text NOT NULL
)";
This failed with following error:
Error creating table: You have an error in your SQL syntax; check the
manual that corresponds to your MariaDB server version for the right
syntax to use near 'NOT NULL, performance text NOT NULL )' at line 3
Now the error line is:
user_id INT(11) REFERENCES users(id) UNIQUE NOT NULL
I have scratched through Maria DB manual but can't quickly get a solution.
I know this syntax works fine on postgresql. Why is it not working on mysqli
I prefer to create 2 separate tables for future changes, etc.
Thanks
First, check that you are using MariaDB 10.5 or later. Inline foreign keys are not implemented in older versions of MariaDB.
Then, move the UNIQUE NOT NULL before the foreign key option. The order of column options is important.
Also, make sure the data type of the foreign key column is the same as the column it references. In this case, you need to make it INT UNSIGNED. The "length" option (11) doesn't matter, and you can omit it.
user_id INT UNSIGNED UNIQUE NOT NULL REFERENCES users(id),
Demo: https://dbfiddle.uk/?rdbms=mariadb_10.5&fiddle=54964388cd0d880169c0332934c13b3d

MYSQL table and column naming convention

I am curious to know what is best naming convention in terms of performance for mysql table names and column names. I am designing a new database for my project.
What I have used so far is use descriptive table/column names which sometimes seems long but I think it helps in easily understanding the use/function of a table.
For example see below DDL:
CREATE TABLE `product_configuration` (
`product_configuration_id` int(11) NOT NULL AUTO_INCREMENT,
`product_id` int(20) NOT NULL,
`product_size_id` int(20) NOT NULL,
`product_color_id` int(20) NOT NULL,
`price` float NOT NULL,
`image` varchar(255) DEFAULT NULL,
`locked` tinyint(1) DEFAULT '0' COMMENT '1=locked, 0 =unlocked. if locked then this row can''t be deleted/updated',
`active` tinyint(1) DEFAULT '1' COMMENT '1=active, 0=inactive and wont display on frontend',
PRIMARY KEY (`product_configuration_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2342 DEFAULT CHARSET=latin1
And another DDL in which I use the primary key from above DDL as foreign key :
CREATE TABLE `product` (
`product_id` int(11) NOT NULL AUTO_INCREMENT,
`product_name` varchar(255) NOT NULL,
`product_description` varchar(255) NOT NULL,
`product_image` varchar(255) NOT NULL,
`price` float NOT NULL,
`active` tinyint(1) NOT NULL COMMENT '1=active, 0=inactive',
`date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`product_type_id` int(11) DEFAULT NULL,
`date_modified` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`product_id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=latin1
Basically I use singular table names with table name as prefix in most of the column names inside that table and I keep the same name and datatype for primary and foreign keys so that I can easily know which foreign key relates to which primary key/tables.
But I wonder, do using long table/column names have performance impact when database size grows. Like instead of just using "id" as primary key I am using long "product_configuration_id".
Also if I name tables/columns in uppercase and lowercase mixed like
"ProductConfiguration"
for table name and
"ProductConfigurationId"
for column name will that have any performance impact or linux/windows environment compatibility issue.
Long table and column names do not have (any significant) performance impact. All tables and column references are turned into internal locators during the compilation phase of the query. So pretty much the only impact is having to query a longer query string. The parsing part of query compilation is usually ignored from a performance perspective.
The following is opinion-based. As a general rule, I follow these conventions for naming:
Table names are in the plural, because they contain multiple entities.
Each table (almost always) has an auto-incremented numeric primary key, which is the singular form of the table followed by Id.
This column is the first column defined, so I can use order by 1 desc to get the most recent rows added to the table.
The table name is not (generally) part of the column name. I always (try to) use table aliases, so including the table name would be redundant.
Foreign key references use the same column name as the primary key they are referring to, when possible, so I can use using for joins.
I admit that these are "opinion-based", so the real answer to your question is in the first paragraph.

Error #1064 while executing sql query in phpmyadmin (wamp server)

m trying to make simple login registration app in android having php mysql db at the back end.. when i try to execute following query, i get error in phpmyadmin
Code:
create database android_api /** Creating Database **/
use android_api /** Selecting Database **/
create table users(
id int(11) primary key auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
); /** Creating Users Table **/
Error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'use android_api /** Selecting Database **/
create table users(
id int(11' at line 3
also i'd like to know.. the tutorial m following says i need two machines on same wifi network to run php n android.. cant they be run on same machine?? how about after deployment??
try the following. Creates a db to keep it out of yours for a test.
create schema abc123; -- create a db
use abc123; -- use it
create table users(
id int(11) primary key auto_increment,
unique_id varchar(23) not null,
name varchar(50) not null,
email varchar(100) not null,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime null,
updated_at datetime null,
unique key(unique_id),
unique key(email)
); /** Creating Users Table **/
drop schema abc123; -- clean up drop schema
Run this:
create database android_api;
use android_api;
create table users(
id int(11) primary key auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
);

Define relationships in database for CakePHP

Im trying out a sample project in CakePHP. It is taken from the cakePHP documentation. It has a total of 4 tables and two of the are listed here.
CREATE TABLE users (
id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL UNIQUE,
password CHAR(40) NOT NULL,
group_id INT(11) NOT NULL,
created DATETIME,
modified DATETIME
);
CREATE TABLE posts (
id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
user_id INT(11) NOT NULL,
title VARCHAR(255) NOT NULL,
body TEXT,
created DATETIME,
modified DATETIME
);
As you can see the id from the users table is added to the posts table as a foreign key in the form of user_id. But in the sample there are no relationships defined. I mean normally we would explicitly define user_id as a foreign key by adding the constraints (in my case using the Relation View of phpMyAdmin). But it is not done here or we are not instructed to do so. When using Cake Bake console to bake our Models do we need this foreign key constraints in place or does cakephp figure them out automatically?
Convention over configuration
Cakephp figures them out automatically for you but you have to follow the naming conventions

MySQL INSERT SELECT and get primary key values

I want to know if it's possible to INSERT records from a SELECT statement from a source table into a destination table, get the INSERT ID's and UPDATE a field on all the corresponding records from source table.
Take for example, the destination table 'payments':
CREATE TABLE `payments` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`txid` TEXT NULL,
`amount` DECIMAL(16,8) NOT NULL DEFAULT '0.00000000',
`worker` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
)
The source table 'log':
CREATE TABLE `log` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`solution` VARCHAR(80) NOT NULL,
`worker` INT(11) NOT NULL,
`amount` DECIMAL(16,8) NOT NULL DEFAULT '0.00000000',
`pstatus` VARCHAR(50) NOT NULL DEFAULT 'pending',
`payment_id` INT(10) UNSIGNED NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
The "log" table contains multiple "micro-payments" for a completed task. The purpose of the "payments" table is to consolidate the micro-payments into one larger payment:
INSERT INTO payments p (amount, worker)
SELECT SUM(l.amount) AS total, l.worker FROM log l
WHERE l.pstatus = "ready"
AND l.payment_id IS NULL
AND l.amount > 0
GROUP BY l.worker
I'm not sure if clear from the code above, but I would like the field "payment_id" to be given the value of the insert id so that it's possible to trace back the micro-payment to the larger consolidated payment.
I could do it all client side (PHP), but I was wondering if there was some magical SQL query that would do it for me? Or maybe I am going about it all wrong.
You can use mysql_insert_id() to get the id the inserted record.
See mysql_insert_id()
But the above function is deprecated.
If you're using PDO, use PDO::lastInsertId.
If you're using Mysqli, use mysqli::$insert_id.
Well, the linking column between the tables is the column worker. After you inserted your values, just do
UPDATE log l
INNER JOIN payments p ON l.worker = p.worker
SET l.payment_id = p.id;
and that's it. Or did I get the question wrong? Note, that the columns differ in the attribute signed/unsigned. You might want to change that.
I think you should use ORM in php as follows:
Look into Doctrine.
Doctrine 1.2 implements Active Record. Doctrine 2+ is a DataMapper ORM.
Also, check out Xyster. It's based on the Data Mapper pattern.
Also, take a look at DataMapper vs. Active Record.

Categories