inserting php + mysql - php

Its my first time using php and mysql together. Here's my database's script:
CREATE SCHEMA IF NOT EXISTS `Alinfo_Express` ;
USE `Alinfo_Express` ;
CREATE TABLE IF NOT EXISTS `Alinfo_Express`.`Categorias` (
`idCategoria` INT(11) NOT NULL,
`titulo` VARCHAR(128) NOT NULL,
`descricao` TEXT NOT NULL,
PRIMARY KEY (`idCategoria`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
CREATE TABLE IF NOT EXISTS `Alinfo_Express`.`Produtos` (
`idProduto` INT(11) NOT NULL,
`nome` VARCHAR(256) NOT NULL,
`descricao` TEXT NOT NULL,
`precoUnidade` FLOAT NOT NULL,
`qtdEstocada` INT(11) NOT NULL,
`emDestaque` BIT(1) NOT NULL,
`idCategoria` INT(11) NOT NULL,
PRIMARY KEY (`idProduto`),
INDEX `fk_Produtos_Categorias1_idx` (`idCategoria` ASC),
CONSTRAINT `fk_Produtos_Categorias1`
FOREIGN KEY (`idCategoria`)
REFERENCES `Alinfo_Express`.`Categorias` (`idCategoria`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
CREATE TABLE IF NOT EXISTS `Alinfo_Express`.`Usuarios` (
`idUsuario` INT(11) NOT NULL,
`nome` VARCHAR(256) NOT NULL,
`sexo` CHAR(1) NOT NULL,
`cpf` VARCHAR(256) NOT NULL,
`rg` VARCHAR(256) NOT NULL,
`email` VARCHAR(256) NOT NULL,
`endereco` VARCHAR(256) NOT NULL,
`CEP` VARCHAR(256) NOT NULL,
`bairro` VARCHAR(256) NOT NULL,
`cidade` VARCHAR(256) NOT NULL,
`estado` VARCHAR(256) NOT NULL,
`senha` VARCHAR(256) NOT NULL,
`tipo` CHAR(1) NOT NULL,
PRIMARY KEY (`idUsuario`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
CREATE TABLE IF NOT EXISTS `Alinfo_Express`.`Compra` (
`idCompra` INT NOT NULL,
`valor` DECIMAL NOT NULL,
`tipoPagamento` VARCHAR(45) NOT NULL,
`dataCompra` DATETIME NOT NULL,
`idUsuario` INT(11) NOT NULL,
`idProduto` INT(11) NOT NULL,
PRIMARY KEY (`idCompra`),
INDEX `fk_Compra_Usuarios_idx` (`idUsuario` ASC),
INDEX `fk_Compra_Produtos1_idx` (`idProduto` ASC),
CONSTRAINT `fk_Compra_Usuarios`
FOREIGN KEY (`idUsuario`)
REFERENCES `Alinfo_Express`.`Usuarios` (`idUsuario`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Compra_Produtos1`
FOREIGN KEY (`idProduto`)
REFERENCES `Alinfo_Express`.`Produtos` (`idProduto`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Here's my code:
$MySQLi->query("INSERT INTO Produtos (idProduto, nome, descricao, precoUnidade,qtdEstocada, emDestaque, idCategoria) VALUES ($cod, '$nome', '$desc', $preco,$qtd, $dest, '$url', $cat);");
I don't know why it isn't working out. There's a long time I don't work with databases, that maybe be my problem.

You have couple of mistakes in your query. Try to execute in phpmyadmin. Try this one
$MySQLi->query("INSERT INTO Produtos (idProduto, nome, descricao, precoUnidade,qtdEstocada, emDestaque, idCategoria) VALUES ($cod, '$nome', '$desc', $preco, $qtd, $dest, '$url', $cat)");
It should work. In phpmyadmin, it will tell you error. Share it with us.

Here you can try with this i hope it will work
$MySQLi->query("INSERT INTO Produtos (idProduto, nome, descricao, precoUnidade,qtdEstocada, emDestaque, idCategoria) VALUES ('".$cod."', '".$nome."', '".$desc.'", '".$preco."','".$qtd."', '".$dest."', '".$url."', '".$cat."')");

Related

Records are not being written or being deleted in a parent table and I don't know why with MariaDB/MySQL and PHP. Ideas?

Here is the structure of the database tables in quesiton.
Officials:
CREATE TABLE IF NOT EXISTS `officials` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`last` varchar(250) NOT NULL DEFAULT '',
`first` varchar(250) NOT NULL DEFAULT '',
`middle` varchar(250) NOT NULL DEFAULT '',
`address` varchar(250) NOT NULL DEFAULT '',
`city` varchar(250) NOT NULL DEFAULT '',
`state` varchar(250) NOT NULL DEFAULT '',
`zip` varchar(250) NOT NULL DEFAULT '',
`homeph` varchar(250) NOT NULL DEFAULT '',
`workph` varchar(250) NOT NULL DEFAULT '',
`cellph` varchar(250) NOT NULL DEFAULT '',
`main_phone` varchar(10) DEFAULT NULL,
`email` varchar(250) NOT NULL DEFAULT '',
`notes` text NOT NULL,
`blockreg` varchar(10) NOT NULL,
`inactive` varchar(10) NOT NULL,
`gender` varchar(100) NOT NULL,
`minority` varchar(100) NOT NULL,
`affiliate` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Is affiliate official? 0 = no. 1 = yes.',
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=14506 DEFAULT CHARSET=latin1;
Transactions (edited from original post to show foreign key constraints):
CREATE TABLE IF NOT EXISTS `transactions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`offid` int(11) NOT NULL,
`txn_id` varchar(64) NOT NULL,
`txn_time` varchar(24) NOT NULL,
`approval_code` varchar(24) DEFAULT NULL,
`amount` varchar(8) NOT NULL,
`result_message` varchar(100) NOT NULL,
`ch_phone` varchar(10) NOT NULL COMMENT,
`ch_card_type` varchar(4) NOT NULL,
`ch_address` varchar(50) NOT NULL,
`ch_state` varchar(15) NOT NULL,
`ch_last_name` varchar(50) NOT NULL,
`ch_email` varchar(100) NOT NULL,
`ch_zip` varchar(10) NOT NULL,
`ch_exp_date` varchar(4) NOT NULL,
`ch_city` varchar(50) NOT NULL,
`ch_first_name` varchar(30) NOT NULL,
`ch_transaction_type` varchar(15) NOT NULL,
`ch_card_number` varchar(18) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `txn_id` (`txn_id`) USING BTREE,
KEY `offid` (`offid`)
) ENGINE=InnoDB AUTO_INCREMENT=72 DEFAULT CHARSET=utf8mb4;
ALTER TABLE `transactions`
ADD CONSTRAINT `transactions_ibfk_1` FOREIGN KEY (`offid`) REFERENCES `officials` (`id`);
Transaction details (edited from original post to show foreign key constraints):
CREATE TABLE IF NOT EXISTS `transaction_details` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`xact_id` varchar(64) NOT NULL,
`detail_amount` float(5,2) NOT NULL,
`sport` varchar(10) NOT NULL,
`regyr` varchar(250) NOT NULL,
PRIMARY KEY (`id`),
KEY `xact_id` (`xact_id`)
) ENGINE=InnoDB AUTO_INCREMENT=63 DEFAULT CHARSET=utf8mb4;
ALTER TABLE `transaction_details`
ADD CONSTRAINT `transaction_details_ibfk_1` FOREIGN KEY (`xact_id`) REFERENCES `transactions` (`txn_id`) ON DELETE CASCADE ON UPDATE CASCADE;
Code that executes upon receiving the data from the credit card company where rows are inserted into the table:
// this creates the main transaction
$sql = "INSERT INTO transactions (offid, txn_id, txn_time, approval_code, amount, result_message, ch_phone,
ch_card_type, ch_address, ch_state, ch_last_name, ch_email, ch_zip, ch_exp_date, ch_city, ch_first_name,
ch_transaction_type, ch_card_number) VALUES ('$offid', '$txn_id', '$txn_time', '$approval_code', '$amount', '$result_message',
'$ch_phone', '$ch_card_type', '$ch_address', '$ch_state', '$ch_last_name', '$ch_email',
'$ch_zip', '$ch_exp_date', '$ch_city', '$ch_first_name', '$ch_transaction_type', '$ch_card_number')";
$result = mysqli_query($conn, $sql);
// this creates the detail transactions
if ($ssl_result == 0) {
$detail_sports = array('fb', 'vb', 'sb', 'bb', 'wr', 'sw', 'so', 'ba', 'tr');
foreach ($detail_sports as $sport) {
$var = $sport . 'total';
// cookie is set for fbtotal, vbtotal, etc. with an amount for that line item
if (isset($_COOKIE[$var])) {
$detail_amount = $_COOKIE[$var];
$sql = "INSERT INTO transaction_details (xact_id, detail_amount, sport, regyr) VALUES ('$txn_id', '$detail_amount', '$sport', '$regyear')";
$result = mysql_query($sql);
}
}
}
The transaction table has id numbers 1, 2, 3, 5, 6, 8, 9, 11, 12, 13, 15, 16, 17, etc. These should be consecutively numbered, but they aren't. It's almost as if they were written to the transaction (parent) table and then deleted. But the code doesn't delete a record.
The transaction detail table has a many-to-one relationship with transaction and all of its records contain consecutive ids.
Any idea what's going on?

One Table is not being created other is being created

I am working on creating table in to my database with mysql and here is my code:
mysqli_query($link, "CREATE TABLE IF NOT EXISTS `review` (
`clients_id` int(15) NOT NULL AUTO_INCREMENT,
`client_id` varchar(150) NOT NULL DEFAULT '',
`rating` tinyint(2) NOT NULL DEFAULT '0',
`proj_date` date NOT NULL DEFAULT '0000-00-00',
`proj_desc` text NOT NULL DEFAULT '',
`photoname` text NOT NULL,
`companyname` text NOT NULL,
`feedback` text NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '0',
`emailid` varchar(100) NOT NULL DEFAULT '',
`customratings` varchar(100) NOT NULL DEFAULT '',
`photo_option` varchar(100) NOT NULL DEFAULT '',
`title` varchar(100) NOT NULL DEFAULT '',
`citation` varchar(100) NOT NULL DEFAULT '',
`date_option` varchar(100) NOT NULL DEFAULT '',
`rating_option` varchar(100) NOT NULL DEFAULT '',
PRIMARY KEY (`clients_id`),
FULLTEXT KEY `feedback` (`feedback`)
) ENGINE=MyISAM AUTO_INCREMENT=1") or mysqli_error($link);
But this is not reflecting into my database ? Why were I may be going wrong ?
but I tried creating other table with the following code
mysqli_query($link, "CREATE TABLE IF NOT EXISTS `setting` (
`id` int(11) NOT NULL auto_increment,
`script_url` text NOT NULL,
`date` varchar(4) NOT NULL,
`rateing` varchar(4) NOT NULL,
`photo` varchar(4) NOT NULL,
`dateformat` varchar(4) NOT NULL,
`page_limit` int(4) NOT NULL,
`proj_desc` varchar(4) NOT NULL,
`companyname` varchar(4) NOT NULL,
`text_color` varchar(255) NOT NULL,
`citation_color` varchar(255) NOT NULL,
`bg_color` varchar(255) NOT NULL,
`border_color` varchar(255) NOT NULL,
`ratingsformat` varchar(250) NOT NULL,
`rating` varchar(250) NOT NULL,
`customratings` varchar(250) NOT NULL,
`speed` varchar(250) NOT NULL,
`pagination` varchar(250) NOT NULL,
`version` varchar(250) NOT NULL,
`global_option` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=0;
") or mysqli_error($link);
it is being created correctly and both the tables are in the same file
No you cannot create table using an insert statement.
There are four types of SQL statements:
DML (DATA MANIPULATION LANGUAGE)
DDL (DATA DEFINITION LANGUAGE)
DCL (DATA CONTROL LANGUAGE)
TCL (TRANSACTION CONTROL LANGUAGE)
DML is your SELECT, INSERT, UPDATE and DELETE statements...
DDL is you your CREATE, ALTER and DROP statements.
See more info about types of SQL statements
In order to insert data in your table, first you need to create it.
How to create sql table from php
No. "INSERT INTO" used to insert the data to existing table only.You should create the table with respective column before try to insert the values.
Or you can check the table exist or not before going insert."If exists" u can insert the value else just create and insert the values.
This worked for me but I don't know how?
I just removed DEFAULT '' present while creating review table and table just got created
Here is edited code
mysqli_query($link, "CREATE TABLE IF NOT EXISTS `review` (
`clients_id` int(15) NOT NULL AUTO_INCREMENT,
`client_id` varchar(150) NOT NULL,
`rating` tinyint(2) NOT NULL,
`proj_date` date NOT NULL,
`proj_desc` text NOT NULL,
`photoname` text NOT NULL,
`companyname` text NOT NULL,
`feedback` text NOT NULL,
`status` tinyint(1) NOT NULL,
`emailid` varchar(100) NOT NULL,
`customratings` varchar(100) NOT NULL,
`photo_option` varchar(100) NOT NULL,
`title` varchar(100) NOT NULL,
`citation` varchar(100) NOT NULL,
`date_option` varchar(100) NOT NULL,
`rating_option` varchar(100) NOT NULL,
PRIMARY KEY (`clients_id`),
FULLTEXT KEY `feedback` (`feedback`)
) ENGINE=MyISAM AUTO_INCREMENT=1") or mysqli_error($link);

Not able to assign On Delete Set null and on updated set Null in mysql

bank_api_uat_user Table
CREATE TABLE IF NOT EXISTS `bank_api_uat_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`bank_name` varchar(255) DEFAULT NULL,
`role` varchar(10) NOT NULL,
`bank_code` char(10) NOT NULL,
`user_name` varchar(255) NOT NULL,
`password` varchar(20) NOT NULL,
`api_key` varchar(255) NOT NULL,
`Client_Secret` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_name` (`user_name`),
KEY `user_name_2` (`user_name`),
KEY `id` (`id`,`user_name`),
KEY `role` (`role`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=36 ;
create_role Table
CREATE TABLE IF NOT EXISTS `create_role` (
`date` datetime NOT NULL,
`Role_name` varchar(50) NOT NULL,
`Role_code` varchar(5) NOT NULL,
PRIMARY KEY (`Role_code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I want to assign referential integrity to bank_api_uat_user table each time i add constraint it gives below error
MySQL said: Documentation
1215 - Cannot add foreign key constraint
Below query used to create foreign key.
ALTER TABLE `bank_api_uat_user` ADD CONSTRAINT `const_file_role` FOREIGN KEY (`role`) REFERENCES `test`.`create_role`(`Role_code`) ON DELETE SET NULL ON UPDATE SET NULL;
Its important to make a child column Null for setting null reference option.
the above queries work if role is declared as NULL
CREATE TABLE IF NOT EXISTS `bank_api_uat_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`bank_name` varchar(255) DEFAULT NULL,
`role` varchar(10) NULL,
`bank_code` char(10) NOT NULL,
`user_name` varchar(255) NOT NULL,
`password` varchar(20) NOT NULL,
`api_key` varchar(255) NOT NULL,
`Client_Secret` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_name` (`user_name`),
KEY `user_name_2` (`user_name`),
KEY `id` (`id`,`user_name`),
KEY `role` (`role`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=36 ;
Full explanation can be find here : https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html

mysql unique for multiple columns

When payment happen, sometimes its captured double entry in table.
I want to ignore double entry capture so i want to insert records when these created, user_id, amount fields should be unique.
How do i make it ? Below is my table.
CREATE TABLE `transactions` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`user_id` int(20) NOT NULL,
`project_id` int(20) DEFAULT NULL,
`foreign_id` int(20) NOT NULL,
`class` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`transaction_type_id` int(20) DEFAULT NULL,
`amount` float(10,2) NOT NULL,
`description` text COLLATE utf8_unicode_ci,
`payment_gateway_id` int(20) DEFAULT NULL,
`gateway_fees` float(10,2) NOT NULL,
`is_old` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=266 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
To strictly answer your question, you create a unique composite key on the combination of those 3 columns. That way no two rows can exist with a combination of the 3 of them in the composite index.
CREATE TABLE `transactions2` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`user_id` int(20) NOT NULL,
`project_id` int(20) DEFAULT NULL,
`foreign_id` int(20) NOT NULL,
`class` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`transaction_type_id` int(20) DEFAULT NULL,
`amount` float(10,2) NOT NULL,
`description` text COLLATE utf8_unicode_ci,
`payment_gateway_id` int(20) DEFAULT NULL,
`gateway_fees` float(10,2) NOT NULL,
`is_old` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
unique key(created,user_id,amount) -- <------------------- right here
);
insert some data to test it:
insert transactions2 (created,modified,user_id,project_id,foreign_id,class,
transaction_type_id,amount,description,payment_gateway_id,gateway_fees,is_old) values
('2009-01-01 12:00:00','2009-01-01 12:00:00',666,1,1,'a',1,100,'desc',1,12,1);
-- inserts fine (above)
Try it again with exactly the same data:
insert transactions2 (created,modified,user_id,project_id,foreign_id,class,
transaction_type_id,amount,description,payment_gateway_id,gateway_fees,is_old) values
('2009-01-01 12:00:00','2009-01-01 12:00:00',666,1,1,'a',1,100,'desc',1,12,1);
-- error 1062: Duplicate entry
-- change it barely:
insert transactions2 (created,modified,user_id,project_id,foreign_id,class,
transaction_type_id,amount,description,payment_gateway_id,gateway_fees,is_old) values
('2009-01-01 13:00:00','2009-01-01 12:00:00',666,1,1,'a',1,100,'desc',1,12,1);
-- inserts fine
Also, use ENGINE=INNODB. Read about that Here.
Please read Mysql multi column indexes a.k.a. composite indexes.
Lastly, the concept of what you are talking about is not far off from Insert on Duplicate Key Update. Just throwing that reference out there for you.
You can achieve the same using ,handling at the time of inserting,
You can try WHERE NOT EXISTS with INSERT.
Something like this.(You need to specify column name who has NOT NULL constraint,i missed all those columns)
INSERT INTO table_name(`created`,`user_id`,`amount`) VALUES =
'$created','$user_id','$amount'
WHERE NOT EXISTS
(SELECT *
FROM table_name
WHERE created ='$created' AND user_id='$user_id' AND amount='$amount')
Hope this helps.

trying to make a foreign key but MySql won't allow me, is there any way?

i have these 3 tables
CREATE TABLE IF NOT EXISTS `enrollment` (
`STUDENT_NUM` varchar(10) NOT NULL,
`SUBJECT_NUM` varchar(10) NOT NULL,
`UNITS` int(10) NOT NULL,
`DAYS` varchar(50) NOT NULL,
`TIME_START` time NOT NULL,
`TIME_END` time NOT NULL,
`ROOM_ID` int(11) DEFAULT NULL,
`PRELIM` float(10,2) DEFAULT NULL,
`MIDTERM` float(10,2) DEFAULT NULL,
`FINALS` float(10,2) DEFAULT NULL,
`FINAL_GRADE` float(10,2) DEFAULT NULL,
`SEMESTER` varchar(50) NOT NULL,
`SCHOOL_YEAR` varchar(50) NOT NULL,
`DATE_ADDED` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`STUDENT_NUM`,`SUBJECT_NUM`),
KEY `SUBJECT_NUM` (`SUBJECT_NUM`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `subjects` (
`SUBJECT_NUM` varchar(10) NOT NULL,
`EMPLOYEE_NUM` varchar(10) NOT NULL,
`SUBJECT_TITLE` varchar(100) DEFAULT NULL,
`DEPARTMENT` varchar(100) DEFAULT NULL,
`UNITS` int(10) NOT NULL,
`DAYS` varchar(50) NOT NULL,
`TIME_START` time NOT NULL,
`TIME_END` time NOT NULL,
`room_id` int(11) DEFAULT NULL,
`SEMESTER` varchar(50) NOT NULL,
`SCHOOL_YEAR` varchar(50) NOT NULL,
`COUNT` int(10) DEFAULT NULL,
`STATUS` varchar(50) DEFAULT NULL,
`FLAG` varchar(50) NOT NULL,
`DATE_ADDED` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`SUBJECT_NUM`),
UNIQUE KEY `SUBJECT_NUM` (`SUBJECT_NUM`),
KEY `EMPLOYEE_NUM` (`EMPLOYEE_NUM`),
KEY `EMPLOYEE_NUM_2` (`EMPLOYEE_NUM`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `room` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`room` varchar(255) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `room` (`room`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
what i am trying to do is make the field ROOM_ID from enrollment and subjects foreign key and the reference be the ID from room.. the ROOM_ID must not be unique...
i am getting this error
#1452 - Cannot add or update a child row: a foreign key constraint fails (`enrollmentdb`.`#sql-277_164`, CONSTRAINT `#sql-277_164_ibfk_3` FOREIGN KEY (`ROOM_ID`) REFERENCES `room` (`ID`))
when i am using this SQL command:
ALTER TABLE enrollment
ADD FOREIGN KEY (room_id)
REFERENCES room(ID)
Try below code if its working :
ALTER TABLE enrollment
ADD CONSTRAINT ROOM_ID_fk
FOREIGN KEY(ROOM_ID)
REFERENCES room(ID);
Thanks!
room_id is capitalised in your table. Try:
ALTER TABLE enrollment
ADD FOREIGN KEY (ROOM_ID)
REFERENCES room(ID)
replace 'room_id' with 'ROOM_ID'

Categories