So, I have been creating migrations using Phinx. I want to be able to truncate all the tables(148 tables) before running the seed files. I am thinking about just creating a seed file that will be ran first and then it will truncate all the tables. The catch is that I don't want to have to ever change this file if we add more tables. How would I go about doing this. Maybe doing a Show tables and then looping through them, but not exactly sure how to do that. Any help would be great! This is what I have so far.
<?php
use Phinx\Seed\AbstractSeed;
class BonusRuleTypesSeeder extends AbstractSeed
{
public function run()
{
$this->execute('SET foreign_key_checks=0');
// some code here
$this->execute('SET foreign_key_checks=1');
}
}
If you have a migrations table, then this will truncate that table as well. This would work.
$this->execute('SET foreign_key_checks=0');
foreach($tables as $table){
$table = $table["Tables_in_".$database];
if ($table != $config->getProperty(['phinx', 'default_migration_table'])){
$sql = "TRUNCATE TABLE ".$table;
$this->execute($sql);
}
}
Here is the answer
$config = new Config(__DIR__.'/../../config/default.ini',true);
$host = $config->getProperty(['db', 'host']);
$database = $config->getProperty(['db', 'name']);
$username = $config->getProperty(['db', 'username']);
$password = $config->getProperty(['db', 'password']);
$mysqli = new mysqli($host, $username, $password, $database);
$query = "Show tables";
$tables = $mysqli->query($query);
$tables->fetch_all();
$mysqli->close();
$this->execute('SET foreign_key_checks=0');
foreach($tables as $table){
$table = $table["Tables_in_".$database];
$sql = "TRUNCATE TABLE ".$table;
$this->execute($sql);
}
$this->execute('SET foreign_key_checks=1');
Related
I have SQL code that executes CREATE TABLE and DROP TABLE in the same query. When I run it, it prints bool(false) meaning error. Can it be done in one query?
$dbh = new PDO("sqlite::memory:");
$stmt = $dbh->prepare("create table a ( i int, j int);drop table a");
var_dump($stmt);
I don't know why but it works if I try it again.
You need to execute your query
Like this :
$stmt ->execute();
And yes you can create and delete a table in the same query.
You can maybe try this to catch an error, it will help you
try
{
$db = new PDO('sqlite::memory');
echo "SQLite created in memory.";
}
catch(PDOException $e)
{
echo $e->getMessage();
}
I created a module and want to used core write and read function to insert,update,delete or select database value with condition, how can I do it without using SQL?
Example:
$customer_id=123
Model=(referral/referral)
SELECT
$collection3 = Mage::getModel('referral/referral')->getCollection();
$collection3->addFieldToFilter('customer_id', array('eq' => $customer_id));
foreach($collection3 as $data1)
{
$ref_cust_id.= $data1->getData('referral_customer_id');
}
INSERT
$collection1= Mage::getModel('referral/referral');
$collection1->setData('customer_id',$customer_id)->save();
DELETE,UPDATE(with condition)=???
Suppose, I have a module named mynews.
Here follows the code to select, insert, update, and delete data from the news table.
INSERT DATA
$data contains array of data to be inserted. The key of the array should be the database table’s field name and the value should be the value to be inserted.
$data = array('title'=>'hello there','content'=>'how are you? i am fine over here.','status'=>1);
$model = Mage::getModel('mynews/mynews')->setData($data);
try {
$insertId = $model->save()->getId();
echo "Data successfully inserted. Insert ID: ".$insertId;
} catch (Exception $e){
echo $e->getMessage();
}
SELECT DATA
$item->getData() prints array of data from ‘news’ table.
$item->getTitle() prints the only the title field.
Similarly, to print content, we need to write $item->getContent().
$model = Mage::getModel('mynews/mynews');
$collection = $model->getCollection();
foreach($collection as $item){
print_r($item->getData());
print_r($item->getTitle());
}
UPDATE DATA
$id is the database table row id to be updated.
$data contains array of data to be updated. The key of the array should be the database table’s field name and the value should be the value to be updated.
// $id = $this->getRequest()->getParam('id');
$id = 2;
$data = array('title'=>'hello test','content'=>'test how are you?','status'=>0);
$model = Mage::getModel('mynews/mynews')->load($id)->addData($data);
try {
$model->setId($id)->save();
echo "Data updated successfully.";
} catch (Exception $e){
echo $e->getMessage();
}
DELETE DATA
$id is the database table row id to be deleted.
// $id = $this->getRequest()->getParam('id');
$id = 3;
$model = Mage::getModel('mynews/mynews');
try {
$model->setId($id)->delete();
echo "Data deleted successfully.";
} catch (Exception $e){
echo $e->getMessage();
}
In this way you can perform select, insert, update and delete in your custom module and in any magento code.
Source: http://blog.chapagain.com.np/magento-how-to-select-insert-update-and-delete-data/
UPDATE is basically the combination of SELECT and INSERT. You load a collection, iterate over them setting the values as needed, then call ->save() on each model.
DELETE is handled directly via the ->delete() functon of models. So either load a single model or iterate over a SELECTed collection of them and call ->delete()
(Not that due to the iteration, this is not the 'fastest' way of doing these operations on collections (because each one is going to generate a new query, instead of a single query that handles multiple deletes at once), but the performance is fine for either small data sets/SELECTs (less than 1k?) or for things that you don't do very often (like importing or updating prices ok 10k products once per day).
FOR UPDATE
$new=$this->getRequest()->getParams();
$id=$new['id'];
$name=$new['name'];
$con=Mage::getModel('plugin/plugin')->load($id);
$con->setData('name',$name)->save();
echo "Update Success";
FOR DELETE
$id = $this->getRequest()->getParam('id');
$model = Mage::getModel('plugin/plugin');
$model->setId($id)->delete();
echo "Data deleted successfully.";
You can use select query like this also. its very easy.
$salesInvoiceCollection_sql = "SELECT `entity_id` , `increment_id`,`order_id`
FROM `sales_flat_invoice`
WHERE `erp_invoice_id` = 0
ORDER BY `entity_id`
DESC limit 1000";
$salesInvoiceCollection = Mage::getSingleton('core/resource')->getConnection('core_read')->fetchAll($salesInvoiceCollection_sql);
If you want to delete with condition based on collection you can use addFieldToFilter, addAttributeToFilter
$model = Mage::getModel('mynews/mynews')->getCollection();
try {
$model->addAttributeToFilter('status', array('eq' => 1));
$model->walk('delete');
echo "Data deleted successfully.";
} catch (Exception $e){
echo $e->getMessage();
}
I have a query that returns c.a 1800 records( not many) but It takes long time to ran (10 seconds) but I can not understand why?
this is my query that takes a long time:
SELECT tb_KonzeptFunktionen.Konzept AS KonzeptID, tb_KonzeptFunktionen.Funktion,
tb_KonzeptFunktionen.Version,
qryFunktionen_Übersicht.ID,
qryFunktionen_Übersicht.Fehlerpfad_Kommentar AS Kommentar,
qryFunktionen_Übersicht.Fehlerpfadname,
qryFunktionen_Übersicht.Fehlerpfad_CDT,
qryFunktionen_Übersicht.Fehlerpfad_Kommentar,
qryFunktionen_Übersicht.symptombasiert,
qryFunktionen_Übersicht.Beschreibung_vorhanden,
qryFunktionen_Übersicht.Max_Pfad,
qryFunktionen_Übersicht.Max_Info,
qryFunktionen_Übersicht.Max_Status,
qryFunktionen_Übersicht.Max_Strategie,
qryFunktionen_Übersicht.Max_Prüfplan,
qryFunktionen_Übersicht.Min_Pfad,
qryFunktionen_Übersicht.Min_Info,
qryFunktionen_Übersicht.Min_Status,
qryFunktionen_Übersicht.Min_Strategie,
qryFunktionen_Übersicht.Min_Prüfplan,
qryFunktionen_Übersicht.Sig_Pfad,
qryFunktionen_Übersicht.Sig_Info,
qryFunktionen_Übersicht.Sig_Status,
qryFunktionen_Übersicht.Sig_Strategie,
qryFunktionen_Übersicht.Sig_Prüfplan,
qryFunktionen_Übersicht.Plaus_Pfad,
qryFunktionen_Übersicht.Plaus_Info,
qryFunktionen_Übersicht.Plaus_Status,
qryFunktionen_Übersicht.Plaus_Strategie,
qryFunktionen_Übersicht.Plaus_Prüfplan,
qryFunktionen_Übersicht.Beschreibung_allgemein,
qryFunktionen_Übersicht.Funktionsname
FROM tb_KonzeptFunktionen RIGHT JOIN qryFunktionen_Übersicht
ON tb_KonzeptFunktionen.Funktion = qryFunktionen_Übersicht.Funktionsname
WHERE (((tb_KonzeptFunktionen.Konzept)=[Formulare]![frm_Fahrzeug]![ID]))
and this is another related query to above query:
SELECT tbFunktionen_Übersicht.*,
tbFunktionen.Funktionsname,
tbFunktionen.Funktionsbeschreibung,
tbFunktionen.diagnoserelevant,
tbFunktionen.ID AS FunktionsID
FROM tbFunktionen_Übersicht INNER JOIN tbFunktionen
ON tbFunktionen_Übersicht.Funktion = tbFunktionen.ID
ORDER BY tbFunktionen.Funktionsname, tbFunktionen_Übersicht.Fehlerpfadname;
I added an index to the fields that appear in ORDER oder JOINS but no effect
Would you please help me if possible?
Please refer to this post,hier you can find the answer
for me PDO brought improvement in my sql query's: http://www.php.net/manual/en/intro.pdo.php
//SQL-HANDLING*******************************************************//
//*********************************************************************//
//General Example-----------------
//$sqlHandling = new sqlHandling;
//$sqlHandling->connectSQL($sqlArray['host'], $sqlArray['user'],$sqlArray['pass'], $sqlArray['dbName']);
//$tableNameArray = $sqlHandling->showTablesSQL($sqlHandling->dbh);
class sqlHandling{
//PDO - Object/ callItOutside with: $sqlClass->dbh
public $dbh = null;
//connectDataBase-------------------//
//-----------------
//example: $dbh = connectSQL('localhost','admin','1admin','test');
//start transaction
//$dbh->beginTransaction();
//-----------------
//end transaction
//$dbh->commit();
//$dbh = null;
//-----------------
//1:SQL-Location
function connectSQL($host, $user, $pass, $dbname){
//endPrevTransaction
if($this->dbh != null){
$this->dbh->commit();
$this->dbh = null;
}
//establish connection
try{
$this->dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $pass);
$this->dbh->exec('SET CHARACTER SET utf8');
return $this->dbh;
}catch(PDOException $e){
print 'Error!: ' . $e->getMessage() . '<br/>';
die();
return FALSE;
}
}
//createColumnSQL-------------------//
//example: createColumnSQL($dbh, 'backupexample', array('SomeName1 VARCHAR(30)', 'SomeName2 VARCHAR(30)', 'SomeName3 VARCHAR(30)', 'SomeName4 VARCHAR(30)'));
//1:PDO connection/2:table/3:array holding columns
function createColumnSQL($dbh, $table, $columns){
//cicle through each array
foreach($columns as $tempColumn){
//set query
$query = 'ALTER TABLE `'.$table.'` ADD COLUMN '.$tempColumn;
//send the query
$stmt = $dbh->prepare($query);
//send the data
$stmt->execute();
}
}
}
This is only a working example for my PDO sqlHandling Class. I know retrieveAllValues won't help you further but you may adopt this code for your use.
MFG
I have this function that should just look in the database for a name similars to an user input. However I can't use Like with the param :uname.
Everyone I look in the web they suggest me to do something like this
$username = "$%username%";
However the query doesn't return any result.
I know the database is properly made because if I ask this, it returns the proper answer
SELECT * FROM $schema.pessoa WHERE nome LIKE %Mike%
However in my code $username contains "Mike" and yet it doesn't return anything, I assumed %username hadn't be properly made however if I make an echo of it, it indeed contains the string I want- "Mike".
So the problem seems to be in the way I am questioning it with the parameter but I have no idea
function SearchUser($username) {
global $dbh, $schema;
try {
$username = "$%username%";
$stmt = $dbh->prepare("SELECT * FROM $schema.pessoa WHERE nome LIKE :uname");
$stmt->bindParam(':uname', $username);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if(empty($result))
{echo 'empty';}
return $result;
}
catch(PDOException $e) {
$_SESSION["s_errors"]["generic"][] = "ERRO[32]: ".$e->getMessage();
header("Location: list.php");
die;
}
It does look right to me,
I could only suggest you try it this way and see if that makes any difference
$username = 'Mike';
$stmt->bindValue(":uname", "%".$username."%");
Edit.
Looking at it again, this doesn't look right to me..
$username = '$%username%';
Shouldn't it be
$username = '%'.$username.'%';
I want to optimize some of the SQL and just need an opinion on whether I should do it or leave it as is and why I should do it. SQL queries are executed via PHP & Java, I will show an example in PHP which will give an idea of what Im doing.
Main concerns are:
-Maintainability.
-Ease of altering tables without messing with all the legacy code
-Speed of SQL (is it a concern???)
-Readability
Example of what I have right now:
I take a LONG array from a customer (cant make it smaller unfortunately) and update the existing values with the new values provided by a customer in the following way:
$i = 0;
foreach($values as $value)
{
$sql = "UPDATE $someTable SET someItem$i = '$value' WHERE username='$username'";
mysql_query($sql, $con);
$i+=1;
}
Its easy to see from the above example that if the array of values is long, than I execute a lot of SQL statements.
Should I instead do something like:
$i = 0;
$j = count($values);
$sql = "UPDATE $someTable SET ";
foreach($values as $value)
{
if($i < $j) //append values to the sql string up to the last item
{
$sql .= "someItem$i = '$value', ";
}
$i+=1;
}
$sql .= "someItem$i = '$value' WHERE username='$username'"; //add the last item and finish the statement
mysql_query($sql, $con); //execute query once
OR which way should it be done / should I bother making these changes? (there a lot of the type and they all have 100+ items)
Thanks in advance.
The only way you'll get a definitive answer is to run both of these methods and profile it to see how long they take. With that said, I'm confident that running one UPDATE statement with a hundred name value pairs will be faster than running 100 UPDATE statements.
Don't run 100 seperate UPDATE statements!
Use a MySQL wrapper class which, when given an array of name => value pairs will return an SQL UPDATE statement. Its really simple. I'm just looking for the one we use now...
We use something like this (registration required) but adapted a little more to suit our needs. Really basic but very very handy.
For instance, the Update method is just this
/**
* Generate SQL Update Query
* #param string $table Target table name
* #param array $data SQL Data (ColumnName => ColumnValue)
* #param string $cond SQL Condition
* #return string
**/
function update($table,$data,$cond='')
{
$sql = "UPDATE $table SET ";
if (is_string($data)) {
$sql .= $data;
} else {
foreach ($data as $k => $v) {
$sql .= "`" . $k . "`" . " = " . SQL::quote($v) . ",";
}
$sql = SQL::trim($sql , ',');
}
if ($cond != '') $sql .= " WHERE $cond";
$sql .= ";";
return $sql;
}
If you can't change the code, make sure it is enclosed in transaction (if the storage engine is InnoDB) so no non-unique indexes will be updated before commiting transaction (this will speed up the write) and the new row won't be flushed to disk.
If this is MyISAM table, use UPDATE LOW_PRIORTY or lock table before the loop and unlock after read.
Of course, I'm sure you have index on the username column, but just to mention it - you need such index.