MySQL Verify all colums and add if not exist - php

I try to check if all the column exist in a MySql ddb. I use this answer MySQL add column if not exist but i have a 1064 error. Anyboby can helps me ?
Thanks
foreach($source_bdd as $each_column)
{
$source_column = explode('***',$each_column);
$nullable = $source_column[4] == 'YES' ? 'DEFAULT NULL' : 'NOT NULL';
$verify_and_update_column .= '
DELIMITER $$
DROP PROCEDURE IF EXISTS Alter_Table_'.$source_column[0].''.$source_column[1].' $$
CREATE PROCEDURE Alter_Table_'.$source_column[0].''.$source_column[1].'()
BEGIN
DECLARE '.$source_column[0].''.$source_column[1].'_count INT;
SET '.$source_column[0].''.$source_column[1].'_count = ( SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = "'.$source_column[0].'" AND
COLUMN_NAME = "'.$source_column[1].'");
IF '.$source_column[0].''.$source_column[1].'_count = 0 THEN
ALTER TABLE '.$source_column[0].'
ADD COLUMN '.$source_column[1].' '.$source_column[9].' '.$nullable.';
END IF;
END $$
CALL Alter_Table_'.$source_column[0].''.$source_column[1].'() $$
DELIMITER ;
';
}
Here is an extract of the query and the error at the end :
DELIMITER $$
DROP PROCEDURE IF EXISTS Alter_Table_table_1_column_1 $$
CREATE PROCEDURE Alter_Table_table_1_column_1()
BEGIN
DECLARE table_1_column_1_count INT;
SET table_1_column_1_count = ( SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = "table_1" AND
COLUMN_NAME = "table_1");
IF table_1_column_1_count = 0 THEN
ALTER TABLE table_1
ADD COLUMN table_1 varchar(512) DEFAULT NULL;
END IF;
END $$
CALL Alter_Table_table_1_column_1() $$
DELIMITER ;
DELIMITER $$
DROP PROCEDURE IF EXISTS Alter_Table_table_1_column_2 $$
CREATE PROCEDURE Alter_Table_table_1_column_2()
BEGIN
DECLARE table_1_column_2_count INT;
SET table_1_column_2_count = ( SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = "table_1" AND
COLUMN_NAME = "table_1");
IF table_1_column_2_count = 0 THEN
ALTER TABLE table_1
ADD COLUMN table_1 varchar(512) DEFAULT NULL;
END IF;
END $$
CALL Alter_Table_table_1_column_2() $$
DELIMITER ;
….
DELIMITER $$
DROP PROCEDURE IF EXISTS Alter_Table_table_25_column_12 $$
CREATE PROCEDURE Alter_Table_table_25_column_12()
BEGIN
DECLARE table_25_column_12_count INT;
SET table_25_column_12_count = ( SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = "table_1" AND
COLUMN_NAME = "table_1");
IF table_25_column_12_count = 0 THEN
ALTER TABLE table_1
ADD COLUMN table_1 varchar(512) DEFAULT NULL;
END IF;
END $$
CALL Alter_Table_table_25_column_12() $$
DELIMITER ;
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 'DELIMITER $$
DROP PROCEDURE IF EXISTS Alter_Table_table_1_column_1 $$
CREATE PROC' at line 11064

Related

Q: Get ancestors with a node in mysql

Here is the reference link that I used to create procedures: https://dba.stackexchange.com/questions/7147/find-highest-level-of-a-hierarchical-field-with-vs-without-ctes/7161#7161?newreg=88de047579d242c98b8cfe0e17f0330f
Procedures are working well with the example. But not working in my own database. Seems I do something wrong while creating procedures.
Here is the procedure for my db:
DELIMITER $$
DROP FUNCTION IF EXISTS `demo`.`GetParentIDByID` $$
CREATE FUNCTION `demo`.`GetParentIDByID` (GivenID INT) RETURNS INT
DETERMINISTIC
BEGIN
DECLARE rv INT;
SELECT IFNULL(user_by,-1) INTO rv FROM
(SELECT user_by FROM users WHERE id = GivenID) A;
RETURN rv;
END $$
DELIMITER ;
Sql query for the following procedure is working fine. It is basically getting parent_id of the node:
SELECT id,GetParentIDByID(id) FROM users;
Issue occurs when I am try to get Ancestors. Here is the Procedure that I am using:
DELIMITER $$
DROP FUNCTION IF EXISTS `demo`.`GetAncestry` $$
CREATE FUNCTION `demo`.`GetAncestry` (GivenID INT) RETURNS VARCHAR(1024)
DETERMINISTIC
BEGIN
DECLARE rv VARCHAR(1024);
DECLARE cm CHAR(1);
DECLARE ch INT;
SET rv = '';
SET cm = '';
SET ch = GivenID;
WHILE ch > 0 DO
SELECT IFNULL(user_by,-1) INTO ch FROM
(SELECT user_by FROM users WHERE id = ch) A;
IF ch > 0 THEN
SET rv = CONCAT(rv,cm,ch);
SET cm = ',';
END IF;
END WHILE;
RETURN rv;
END $$
DELIMITER ;
SQL query:
SELECT id,GetAncestry(id) FROM users;
Phpmyadmin getting stuck, if I am using this query. It never returns me anything nor an error or success

How do I CALL mysql TEMPORARY TABLE from CodeIgniter?

I have written a stored procedure in mysql which will create a TEMPORARY TABLE, I want to access the data of TEMPORARY TABLE using Codeigniter.But when I call "$this->db->query()" it returns empty data.
$data=array();
$call_procedure = "CALL sp_Stock()";
$query = $this->db->query($call_procedure);
$sql="SELECT * FROM StockTable";
$query1 = $this->db->query($sql);
I have changed my way to show the data. And I do changes it on stored procedure.
DELIMITER $$
CREATE PROCEDURE sp_Stock()
BEGIN
DECLARE cursor_finish INTEGER DEFAULT 0;
DECLARE m_numofpurchaseBag DECIMAL(10,2)DEFAULT 0;
DECLARE m_purchasedKg DECIMAL(10,2)DEFAULT 0;
DECLARE m_purBagDtlId INTEGER DEFAULT 0;
DECLARE stockCursor CURSOR FOR
SELECT purchase_bag_details.`actual_bags`,
(purchase_bag_details.`net`*purchase_bag_details.`actual_bags`) AS PurchasedKg,
purchase_bag_details.`id` AS PurchaseBagDtlId
FROM
purchase_invoice_detail
INNER JOIN
purchase_bag_details
ON purchase_invoice_detail.`id`= purchase_bag_details.`purchasedtlid`
INNER JOIN
`do_to_transporter`
ON purchase_invoice_detail.`id` = do_to_transporter.`purchase_inv_dtlid`
WHERE purchase_invoice_detail.`teagroup_master_id`=6
AND purchase_invoice_detail.`id`=1481
AND do_to_transporter.`in_Stock`='Y';
-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET cursor_finish = 1;
DROP TEMPORARY TABLE IF EXISTS StockTable;
#temptable creation
CREATE TEMPORARY TABLE IF NOT EXISTS StockTable
(
purchaseBagDtlId INT,
purchasedBag NUMERIC(10,2),
purchasedKg NUMERIC(10,2),
blendedBag NUMERIC(10,2),
blendedKg NUMERIC(10,2),
stockBag NUMERIC(10,2),
stockKg NUMERIC(10,2)
);
#temptable creation
OPEN stockCursor ;
get_stock : LOOP
FETCH stockCursor INTO m_numofpurchaseBag,m_purchasedKg,m_purBagDtlId;
IF cursor_finish = 1 THEN
LEAVE get_stock;
END IF;
/*SELECT m_numofpurchaseBag,m_purchasedKg,m_purBagDtlId; */
/* Blending bag query*/
SET #m_numberofBlndBag:=0;
SET #m_BlndKg:=0;
/* Blend bag*/
SELECT #m_numberofBlndBag:=SUM(blending_details.`number_of_blended_bag`) AS belendedBag INTO #m_numberofBlndBag
FROM blending_details
WHERE blending_details.`purchasebag_id`= m_purBagDtlId
GROUP BY
blending_details.`purchasebag_id`;
#Blend Bag
#Blend Kgs
SELECT #m_BlndKg:=SUM(blending_details.`qty_of_bag` * blending_details.`number_of_blended_bag`) AS blendkg INTO #m_BlndKg
FROM blending_details
WHERE blending_details.`purchasebag_id`= m_purBagDtlId
GROUP BY
blending_details.`purchasebag_id`;
SET #m_StockBag:=(m_numofpurchaseBag - #m_numberofBlndBag);
SET #m_StockKg:=(m_purchasedKg - #m_BlndKg);
INSERT INTO StockTable
(
purchaseBagDtlId ,
purchasedBag ,
purchasedKg ,
blendedBag ,
blendedKg ,
stockBag ,
stockKg
)VALUES(m_purBagDtlId,m_numofpurchaseBag,m_purchasedKg,#m_numberofBlndBag,#m_BlndKg,#m_StockBag,#m_StockKg);
END LOOP get_stock;
CLOSE stockCursor;
SELECT * FROM StockTable;
#DROP TABLE StockTable;
END$$
DELIMITER ;
#CALL sp_Stock();
Anywhere I am using a temp table I am executing this before the temp table is created:
$this->db->query('DROP TABLE IF EXISTS StockTable');
I seem to remember reading someone having the same problem as you and for some reason you have to execute the above first.
So try:
$data=array();
$call_procedure = "CALL sp_Stock()";
$this->db->query('DROP TABLE IF EXISTS StockTable');
$query = $this->db->query($call_procedure);
$sql="SELECT * FROM StockTable";
$query1 = $this->db->query($sql);

Unable to create mysql trigger from php

How do I use php and mysql to create the following trigger for each table created.
I want to convert the following code to be used as a sql query from php.
DELIMITER $$
CREATE TRIGGER trigger1
BEFORE INSERT
ON table1
FOR EACH ROW
BEGIN
SELECT COUNT(*) INTO #cnt FROM table1;
IF #cnt >= 25 THEN
CALL sth();
END IF;
END
$$
DELIMITER ;
I tried to use the following but it does not work.
if ($method == "T")// method is activated if $_GET["method'] = T method is set to T in script to allways return true
{
$sql = "CREATE TRIGGER TRIGGER1
BEFORE INSERT
ON 49a64d6512
FOR EACH ROW
BEGIN
SELECT COUNT(*) INTO #cnt FROM 49a64d6512;
IF #cnt >=25 THEN
CALL sth();
END IF;
END";
echo '1';
}
Is what i am trying to do even possible?

Wordpress and mysql procedure

I'm trying to alt WP tables with the function. Mysql code works fine if I call it from mysql client (adds columns), but when I called it via $wpdb->query() it gave me error pointing to DELIMITER line. Upon some googling, I found out that I should use mysqli for this purpose. Now the error log is empty but columns are still not created. Anyone got an idea of what I'm doing wrong? Function code is below
global $wpdb;
$tables=array(
'wp_users',
'wp_usermeta',
'wp_term_taxonomy',
'wp_term_relationships',
'wp_terms',
'wp_taxonomymeta',
'wp_posts',
'wp_postmeta',
'wp_p2p',
'wp_p2pmeta',
'wp_options',
'wp_fb_user_timezone',
'wp_fb_coaching_call_report_team_user',
'wp_fb_coaching_call_report_team',
'wp_fb_3d_notes',
'wp_comments',
'wp_commentmeta',
'wp_coaching_teams_student',
'wp_coaching_teams_coach',
'wp_coaching_teams',
'wp_coaching_call_count'
);
if (is_array($tables)&&count($tables)>0)
{
foreach ($tables as $table)
{
$aaa=mysqli_multi_query($wpdb->dbh,'DELIMITER $$
DROP PROCEDURE IF EXISTS add_createdat_and_updatedat_fields $$
CREATE PROCEDURE add_createdat_and_updatedat_fields()
BEGIN
IF EXISTS(SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema=DATABASE() AND table_name=\''.$table.'\') THEN
IF NOT EXISTS ((SELECT * FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=\''.$table.'\' AND column_name=\'created_at\')) THEN
ALTER TABLE `'.$table.'` ADD `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP;
END IF;
IF NOT EXISTS ((SELECT * FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=\''.$table.'\' AND column_name=\'updated_at\')) THEN
ALTER TABLE `'.$table.'` ADD `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP;
END IF;
END IF;
END $$
CALL add_createdat_and_updatedat_fields() $$
DROP PROCEDURE IF EXISTS add_createdat_and_updatedat_fields $$
DELIMITER;');
}
}
Do not use multiquery, run each command separately with mysqli_query() instead, that way you don't need manipulating separators at all.

trigger error with null output

here is my trigger:
create trigger wyplacamy before insert on `skladki_wyplaty`
for each row
BEGIN
SELECT p.wysokosc_skladki, p.ilosc_miesiecy INTO #wysokosc_skladki, #ilosc_miesiecy
FROM skladki_aktualne p
WHERE p.pesel = NEW.pesel AND p.id_ubezpieczenia = NEW.id_ubezpieczenia;
SET NEW.wyoskosc_wyplaty = #wysokosc_skladki / #ilosc_miesiecy *75;
END
$$
This works, but the iutpput of "wyoskosc_wyplaty" is NULL, even wysokosc_skladki = 8000, and ilosc_miesiecy = 8.
You need to declare the variables before using them.
delimiter $$
create trigger wyplacamy before insert on `skladki_wyplaty`
for each row
BEGIN
DECLARE var_wysokosc_skladki INT;
DECLARE var_ilosc_miesiecy INT;
SELECT p.wysokosc_skladki, p.ilosc_miesiecy INTO var_wysokosc_skladki, var_ilosc_miesiecy
FROM skladki_aktualne p
WHERE p.pesel = NEW.pesel
AND p.id_ubezpieczenia = NEW.id_ubezpieczenia;
SET NEW.wyoskosc_wyplaty = var_wysokosc_skladki / var_ilosc_miesiecy * 75;
END
$$

Categories