Hello i wish someone can help me it's my presentation tomorrow i would like to ask why does my values does not have lashes? ``` when i backup my database in php? i'm using codeigniter can someone please help me whenever i back up it it turns
INSERT INTO `discount` (`id`, `name`, `discount_percent`, `active`) VALUES (3, Student, 10, 1);
and it's giving me an error i think he want the value have lashes like this
INSERT INTO `discount` (`id`, `name`, `discount_percent`, `active`) VALUES ('3', 'Student', '10', '1');`
i tried the first one in my localhost but failed and the second one with lashes is successful so how can i backup with lashes?
my code is:
public function create()
{
// Load the DB utility class
$this->load->dbutil();
$test = date('YmdS-His');
// Backup your entire database and assign it to a variable
$config = array (
'format' => 'zip', // gzip, zip, txt
'filename' => 'bubblebee_'.$test.'_db.sql', // File name - NEEDED ONLY WITH ZIP FILES
'add_drop' => TRUE, // Whether to add DROP TABLE statements to backup file
'add_insert' => TRUE, // Whether to add INSERT data to backup file
'newline' => "\n", // Newline character used in backup file
'foreign_key_checks' => FALSE,
);
$backup =& $this->dbutil->backup($config);
$db_name ='bubblebee_'.$test.'.zip';
$this->load->helper('download');
force_download($db_name, $backup);
}
Related
I am trying to export the database from Codeigniter 3 the insert query is not bulk.
it crease each row as a new query using $this->load->dbutil(); and The format agr is
$format = array(
'ignore' => array($this->ignore_directories),
'format' => 'zip',
'filename' => 'db_backup_' . $date . '.sql',
'add_insert' => TRUE,
'newline' => "\n"
);
backup Statement
$backup = $this->dbutil->backup($format);
The problem is that exported data is not in the bulk import format. it simply creates each import as a query which is slow and time-consuming also sometimes it failed to import because PHP time limit.
Try this
$this->load->dbutil();
$db_format=array('format'=>'zip','filename'=>'YOUR DB NAME.sql');
$backup=& $this->dbutil->backup($db_format);
$dbname='backup-on-'.date('Y-m-d').'.zip';
$save='YOUR FOLDER PATH'.$dbname;
write_file($save,$backup);
force_download($dbname,$backup);
This will help you to export the db in zip file.When you import the extracted file,the db imported fully or bulky.Hope it will helps!!
In config/database.php (Laravel 8) this is configured:
'connections' => [
'my_db' => [
'driver' => 'mysql',
'host' => 'xx.xx.xxx.xxx',
'port' => '3306',
'database' => 'Sqlxxx',
'username' => 'Sqlxxxx',
'password' => 'passxxx',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
],
'other_db' => [
...
],
],
I try to save some data, but it doesn't work.
DB::connection('my_db')->beginTransaction();
$data = [];
$data["A"] = "a";
$data["B"] = "b";
$pdo = DB::connection('my_db')->getPdo();
if ($pdo) {
DB::connection('my_db')
->table('my_table')
->insert($data);
}
DB::connection('my_db')->commit();
I specify that the connection to the DB my_db works, because I can get data from it. I have the impression that it can read data but not save them.
EDIT:
I have multiple connections defined in config/database.php
my_db is a database outside of my project
There is no error message; just a blank page (APP_DEBUG is set to true and APP_ENV to "local")
I added DB::connection('my_db')->beginTransaction(); to the beginning of the script, to no avail.
It doesn't work in the following way either: DB::connection('my_db')->insert('insert into my_table (A, B) values (?, ?)', ['a', 'b']);
I'm freaking out. Updating works, inserting doesn't. This works: DB::connection('my_db')->table('my_table')->where('id', '1')->update(['a' => '111']);
There are a couple of spots in the documentation on how to do an insert:
The DB Facade's insert() method:
DB::insert('insert into example_table values (col_1, col_2), (?, ?)', ['col_1_value', 'col_2_value']);
This uses a bound parameterized query to directly insert into the default Connection's example_table table. This doesn't appear to be compatible with DB::connection(...)->insert(), as the insert() method used while chaining is not the same method as above, but rather the Builder's method (see below).
The Query Builder's insert() method:
DB::table('example_table')->insert(['col_1' => 'col_1_value', 'col_2' => 'col_2_value']);
The Query Builder in Laravel is a Database-Agnostic wrapper for allowing communication with the database based on the driver (MySQL, PostGres, etc.). It expects a simple associative array representation of the columns being inserted, like ['a' => 'a', 'b' => 'b', ...], and performs the insert based on the supplied or default Connection and specified table (i.e. this is compatible with DB::connection()).
An additional approach would be to use a Model, with the specified Connection defined. For example, let's define an Example.php Model, with the my_db connection:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Example extends Model {
protected $connection = 'my_db';
...
}
Because we're setting protected $connection = 'my_db';, any calls to this model with automatically use the my_db connection defined in config/database.php's connections array. Examples:
$example = Example::create(['a' => 'a', 'b' => 'b']);
This would run INSERT into examples (a, b) VALUES ('a', 'b'); using the correct database syntax (MySQL, Postgres, etc.). Additional calls to Example::update(), Example::delete(), etc. would all know to use the proper connection.
I would recommend this approach over the DB::connection()->table() method, and would highly recommend not using the DB::insert() method at all.
SOLVED: It was my mistake. I was trying to create a new record forgetting to indicate all the NOT NULLABLE ones. I could have figured it out by the fact that the update worked while the insertion did not. I confirm that DB::connection('my_db')->table('my_table')->insert($data); works perfectly.
Since you don't get any errors upon inserting data it seem to be either of two cases:
Your transaction somehow reverts
Your data doesn't get flushed (only cached somewhere in unit of work or something similar)
Try removing the DB::connection('my_db')->beginTransaction(); and DB::connection('my_db')->commit(); statements.
i am creating backup using codigniter library "dbutil" and i have fields in my mysql database which having datatype bit when using below given code
public function run_backup()
{
$filename="MembersPro_database_$this->curr_date.sql";
$filepath="application/upload/DatabaseBackup/$filename";
$dbfilepath="MembersPro/application/upload/DatabaseBackup/$filename";
$prefs = array(
'ignore' => array(), // List of tables to omit from the backup
'format' => 'sql', // gzip, zip, txt
'filename' =>$filepath, // File name - NEEDED ONLY WITH ZIP FILES
'add_drop' => TRUE, // Whether to add DROP TABLE statements to backup file
'add_insert' => TRUE,
"foreign_key_checks" =>FALSE
/* 'newline' => "\n",*/
// Newline character used in backup file
);
$backup="CREATE DATABASE IF NOT EXISTS `MembersManagmentSystem`; USE `MembersManagmentSystem` ";
$backup .= $this->dbutil->backup($prefs);
if(!write_file($filepath, $backup))
{
echo "Error";die;
}
else
{
$_SESSION['sucessmsgbackup']="true";
}
$this->insert_into_datbase($filename,$dbfilepath);
redirect("ViewDatabaseBackup");
}
getting wrong output insert query
INSERT INTO `User` (`userId`, `userRoleId`,`userActive`, `userIsDelete`) VALUES ('20000046', '20001','1', '0');
in above given query "userActive" and "userIsDelete" fields having datatype "bit" and the query create by DbUtil library is treating it as string so i am getting warning error in mysql
"out of range column value"
Read Here Why you should not use BIT columns in MySQL
Issue reported Here in Github
Look into folder and modify core classes so that it will not escape, for example for mysqli driver
system/database/drivers/mysqli
https://github.com/bcit-ci/CodeIgniter/blob/develop/system/database/drivers/mysqli/mysqli_utility.php#L159
and find file mysqli_utility.php
locate line
$is_int[$i] = in_array(strtolower($field->type),
array('tinyint', 'smallint', 'mediumint', 'int', 'bigint'), //, 'timestamp'),
TRUE);
Type numbers
numerics
-------------
BIT: 16
TINYINT: 1
BOOL: 1
SMALLINT: 2
MEDIUMINT: 9
INTEGER: 3
BIGINT: 8
SERIAL: 8
FLOAT: 4
DOUBLE: 5
DECIMAL: 246
NUMERIC: 246
FIXED: 246
and add your datatype to above array like below
$is_int[$i] = in_array($field->type,
array(16, 1, 2, 9, 3, 8),
TRUE);
I am writing a PHPUnit test for my Yii application. I read here:
Tip: Having too many fixture files could increase the test time
dramatically. For this reason, you should only provide fixture files
for those tables whose content may change during the test. Tables that
serve as look-ups do not change and thus do not need fixture files.
I indeed have a large fixture (180 records, which takes >20 seconds to load), which is only used as a look-up. However, I do need to transform it easily from an associative array into a Model object, like you can usually do with the fixture syntax below. The tip suggests that there is also a way to create a Model object without the use of a fixture, but does not mention how this is done. Can anyone help out?
Creation of Model object with a fixture:
// tests/fixtures/Order.php
return array(
'row_id' => array(
'id' => 1,
'name' => 'hello',
)
)
// tests/unit/AbcTest.php
public $fixtures = array(
'orders' => 'Order',
)
public test_abc()
{
$order = $this->orders('row_id');
....
}
Another option:
when you create db migration you should apply it on production db and on test db moreover you should populate test tables with test data.
Benefits of this approach:
You will run populate sql just once (not like
fixture - each time invokes test).
Your test will executes fast, because db will be prepared.
When you commit new feature that need new test with new data in db -
you create db migration, and it will be executed just once, in
explicit way.
For example:
<?php
class m150608_110143_init extends CDbMigration
{
public function safeUp()
{
$sql1 = "
CREATE TABLE brand (
id INT AUTO_INCREMENT,
name VARCHAR(100) NOT NULL DEFAULT '',
country VARCHAR(50) NOT NULL DEFAULT '',
PRIMARY KEY (id)
);
";
$sql2 = "
INSERT INTO brand VALUES
(null, 'aston martin', 'UK'),
(null, 'audi', 'Germany'),
(null, 'bmw', 'Germany'),
(null, 'citroen', 'France'),
(null, 'peugeot', 'France'),
(null, 'porsche', 'Germany'),
(null, 'toyota', 'Japan'),
(null, 'ferrari', 'Italy')
;
";
// Production db.
$this->setDbConnection(Yii::app()->db);
$this->execute($sql1);
// Test db.
$this->setDbConnection(Yii::app()->dbUnitTest);
$this->execute($sql1);
// Populate test db with fixtures.
$this->execute($sql2);
return true;
}
public function down()
{
$sql = 'DROP TABLE brand;';
// Test db.
$this->setDbConnection(Yii::app()->dbUnitTest);
$this->execute($sql);
// Production db.
$this->setDbConnection(Yii::app()->db);
$this->execute($sql);
return true;
}
}
And in test you don't have to think about fixtures.
Yes, it's possible to reach what you wish.
For example: i have model brand that have own fixture:
<?php
// protected/tests/fixtures/brand.php
return [
1 => [
'name' => 'Lexus',
'country' => 'JPN',
],
2 => [
'name' => 'Acura',
'country' => 'JPNE',
],
];
and i have next code:
$brand = new Brand;
$allBrands = $brand->findAll();
This code will return array with 2 CActiveRecord objects. And everything what we need - it's just build the same array with 2 CActiveRecord objects:
public function testGetAllAvailableBrands()
{
// Get brands from fixture.
$brand = new Brand;
$allBrandsFromFixture = $brand->findAll();
// Generate brands.
$lexus = new Brand;
$lexus->scenario = 'update';
$lexus->name = 'Lexus';
$lexus->country = 'JPN';
$lexus->id = 1;
$lexus->setPrimaryKey(1);
$lexus->setIsNewRecord(false);
$allBrandsGeneratedAtRuntime[] = $lexus;
$acura = new Brand;
$acura->scenario = 'update';
$acura->name = 'Acura';
$acura->country = 'JPNE';
$acura->id = 2;
$acura->setPrimaryKey(2);
$acura->setIsNewRecord(false);
$allBrandsGeneratedAtRuntime[] = $acura;
// Brands from fixture should be equals to generated brands.
$this->assertEquals($allBrandsFromFixture, $allBrandsGeneratedAtRuntime);
}
This test will be green because our brands exactly the same. You cat try something like this.
But i think that native yii fixtures looks much better, and to avoid increase the test time you should use .init.php files...
I have a function for a forum that I'm working on. One of the things it does is return a result back to the ajax call and redirect
function inv_post_create_topic() {
global $db;
if($_POST['postas']=='support') {
$author = '0';
}
else { $author = $_POST['poster']; }
$query = <<<SQL
INSERT INTO inv_forums(parent,subject,body,author,replies,views,enabled,posted,posttype)
VALUES(:parent,:subject,:body,:author,:replies,:views,:enabled,:posted,:posttype)
SQL;
$resource = $db->db->prepare( $query );
$resource->execute( array (
':parent' => $_POST['cat'],
':subject' => $_POST['title'],
':body' => $_POST['post'],
':author' => $author,
':replies' => '0',
':views' => '0',
':enabled' => '1',
':posted' => date('F j, Y | h:i A'),
':posttype' => $_POST['flag'],
));
echo "viewPage.php?id=".inv_get_post_redirect()."&forum=".$db->db->lastInsertId()."";
}
With this function it pulls the id with the view posts function and the last inserted ID (IE The forum just created) and then returns that data and redirects you to the newly created forum. What I was wondering is if it is at all possible to create a temporary persistent connection. It was working fine on my server,but always returned forum=0 on my live server.After some research it has to do with persistent connections being allowed. My webhost said that's something I can set up within my config.php file, but they also let me know that the server only allows 24 concurrent connections, so what I'm trying to find out is if I can take that connection, make it persistent to pull the last id submitted and then close up afterwards.