issue tabel_exist in pyrocms - codeigniter

i am using pyrocms for my web application.
i want create library for my module in addons.
when i use this code for tabel llist in my database.
$CI = & get_instance();
$all=$CI->db->list_tables();
i have "defualt_products" value in $all array. this means i have "default_products" table in my database. but when i use next code , result is false. why?
if(!$CI->db->table_exists("default_products"))
return false;
i use pyrocms 2.2.

You can use the dbprefix method to include you table prefix from database.php config file:
if ( !$CI->db->table_exists($CI->db->dbprefix('products')) ){
//there is no such table, products
echo "there is no table named ".$CI->db->dbprefix('products');
die();
}else{
//table found
echo "table found"; die();
}
In case it dose not work, then I think your problem is not this piece of code!

You aren't passing anything to table_exists. How is it supposed to know which table you are trying to check for? It takes one parameter...the table name you are checking for.
http://ellislab.com/codeigniter/user-guide/database/table_data.html
so, if you did this, and a table called "tablename" existed..then you would still get false, because table_exists returns TRUE if the table does exist.
if ($CI->db->table_exists('tablename')
{
return FALSE;
}

Related

How to get an ID from the collection in laravel?

I am writing one database query it's returning the matching record that's stored in one variable called $store,i want to get the id of the particular record which is stored in the $store variable.
$store=DB::table('books')->where('bookName','dummy')->get();
books migration table structure
$table->increments('id');
$table->string('bookName'); //it's uniqe
$table->int('price');
what i am trying is when i try to get the id of a particular book based on $store [$store->id]variable it's throwing an error called
Propert id doesnot exist on collection instance
Try this
$store=DB::table('books')->where('bookName','dummy')->get();
foreach($store as $str){
echo $id = $str->id;
}
it's showing clearly collection so you have to call the following way
$store[0]->id
If you need only the id, the common way will be use select.
Model::select('id')->get();
And in the view you can iterate the ModelCollection and use $item->id or '$item['id']'
foreaxample, getting first book id with specific price:
$id = $store->where('price', 100)->first()->id;

Laravel Eloquent ORM Soft delete and restore many items for me at the same time

i think there is a bug in softdelete and restore with Eloquent ORM in Laravel .
i have a table like these
My Table Image
UPDATED : i made a video now for the problem : VIDEO OF MY PROBLEM
and my code to softdelete is
try {
$p= Post::findOrFail($id);
} catch (Exception $e) {
return "error";
}
$p->delete();
return "Post deleted";
and my code for restore is :
`try {
$p= Post::withTrashed()->findOrFail($id);
} catch (Exception $e) {
return "error";
}
$p->restore();
return "Post restored";`
..
the problem is sometimes :
when i delete post number 3 , it delete number 3 and number 2 at the same time and sometimes work fine , n with restore same thing too sometimes i restore for example number 3 n it restore number 1 also at the same time.
i didnt understand why , i tried different code like 'where' statement n 'find' n 'destroy'.
like :
Post::withTrashed()->where('id', $id)->restore();
Post::find($id)->delete();
but same problem sometimes delete n restore work normally sometimes go crazy n delete or restore many items at the same time .
i tried also different version of laravel 5.2 n 5.4 .
i use mysql 5.6.35 , mamp server php 7.1.1.
I hope this code helpful for you.
$products = Product::onlyTrashed()
->whereIn('id', $request->product_ids)
->restore();
You can delete it by calling on Model instance:
$post = Post::find($id);
$post->delete();
Since you already know your model Id, you might do this:
Post::destroy($id)
Or delete it by Query:
$deletedPost = Post::where('id', $id)->delete();
Btw, i dont think you need those try/catch there. Try without it. Also, if you have problems, try to do dd($id) and see what it dumps. If its ok, move on and do dd($p) and see if you are getting the proper model.
Take a good look at your variables, dump them or if you can use debugger, go line by line to see where it goes wrong.
Hope this helped a bit :)
Good luck with problem!
You don't need try catch block to soft delete. Eloquent provides delete() and restore().
Add Illuminate\Database\Eloquent\SoftDeletes trait
and protected $dates = ['deleted_at'] to your model
add a deleted_at column to your database table(use helper/manually migrate).
Now you can call delete() and restore() method onto your model.
This will set current datetime value to the deleted_at column (initially they are null).
Hope this will help.
laravel-5.4 doc: soft-delete

MySQL/php: I created database and tables, when I try an INSERT I have #1146

I'm writing an installation script in php, this script has to ask the user some data and then store them in a XML file and on a database.
Here is the procedure:
1) Insert data;
2) Save configuration data (such as database name,user,password,host,port) in a XML file
3) Using those data to install a database (I have an empty dump I use to create it)
4) Insert in the "admin" table the first user data (taken from the form in point 1)
Now, everything works fine until point 4.
When I try to access the database MySql always returns my an error #1146 saying that the table doesn't not exists.
This is my custom JSON log:
{
"Status":"KO",
"Reason":"SELECT * FROM bbscp_admin_user; || Table 'adb.bbscp_admin_user' doesn't exist",
"Errno":1146
}
Obviously I checked both with phpMyAdmin and mysql (from cli) and I can say that both DB and Table DO exists.
Here is the part where I create the DB: [this works fine]
$Install = Install::getInstance();
$sqlscript = str_replace("__DBNAME__",
$config_info['dbname'],
file_get_contents('../config/bbscp-base-db.sql')
);
$connection = mysqli_connect($config_info['dbhost'],
$config_info['dbuser'],
$config_info['dbpwd']
) or die("Unable to connect! Error: ".mysql_error());
if(mysqli_query($connection,'CREATE DATABASE '.$config_info['dbname'].';')){
echo 'Database successfully createad';
mysqli_close($connection);
}else{
die('ERROR CREATING DATABASE!');
}
Here the part where I populate the database from the dump (it only add the tables)
$connection = mysqli_connect($config_info['dbhost'],
$config_info['dbuser'],
$config_info['dbpwd'],
$config_info['dbname']
) or die("Unable to connect! Error: ".mysql_error());
if(mysqli_multi_query($connection, $sqlscript)){
echo 'Database successfully imported';
mysqli_close($connection);
}else{
die('ERROR IMPORTING DATABASE');
}
Now the decisive part, I open a connection with the database (using a library that I've developed in the past years and has always worked fine)
$DB = new Database(Install::getInstance());
$Q = new Query();
$DB->connect();
$query = $Q->addNewUser($config_info['nickname'],
$config_info['password'],
$config_info['firstname'],
$config_info['lastname'],
$config_info['email'],
0); // this just returns the query string I need
// the query in this case is:
// INSERT INTO bbscp_admin_user
// (nickname,password,firstname,lastname,mail,confirmed)
// VALUES (the ones above);"
$res=$DB->startQuery($query); // THIS IS WHERE THE ERROR IS RETURNED
// this function only wraps the mysqli_query and returns a custom JSON
I've tried a lot of solution.. The tables DO exists but every query I try to invoke at this point doesn't work because apparently "table doesn't exist" (even using mysqli function instead of mines).
Thanks in advance and sorry for the long question! :-)
EDIT 1
During this days I've changed a lot of code, I tried using different implementation using functions, objects, redirects but none of them seems to work.
The thing is always the same:
It creates the database
Returns the error code when trying to add the user
If I refresh the page it correctly adds the user

Error in SetData() in magento?

I am trying to update a custom field of customer_entity in magento I am using the following code:
$customer = Mage::getModel('customer/customer')->load($customerId);
print_r($customer->getData());
try {
$customer->setData('field', $flag);
$insertId = $customer->save()->getId();
echo "Data successfully inserted. Insert ID: ".$insertId;
print_r($customer->getData());
} catch (Exception $e){
echo $e->getMessage();
}
Now I does not get why it is not saving in a database, when i write the log customer data has the updated value, but when i try to see in the database it is not reflecting.
Any Idea?
Edited:
$write = Mage::getSingleton("core/resource")->getConnection("core_write");
$sql = "update `customer_entity` set `field` = ".$flag." where`entity_id` =".$customerId;
$write->query($sql);
This code is working with charm but the above code nention at the top does work.
Does any body have any idea?
Try clearing your cache once and reindexing from magento admin! Hope it works
first check the following
1. check you made the database table defined in the config.xml in the resource model.
2.get the value for $flag and check whether the field is present or not.
Step1:- Check your resource table name in config.xml file,and Clear your cache folder inside /var folder and than check.
Step2:- If step 1 is not working than reindex your project and than check.
Step3:- If step 1 and 2 is not working, than check your table Engine type if it's InnoDB than change it to MyISAM and than check.
For more Info click here

Short table name for SQL Query with Codeigniter database library

I'm using CodeIgniter, I want to using short table name for my SQL Query like that:
select pr.name from product pr where pr.id=12;
by using db class, I supposed to do:
$this->db->select('pr.name')->from('product pr')->where('pr.id', 12)->get();
This works perfect on CI 2.1.3. Don't forget to use result().
Example works for me:
function test(){
$this->load->database();
$sql = $this->db->select('pr.order_id')->from('items_table pr')->where('pr.order_id', 2)->get();
foreach($sql->result() as $item){
echo $item->order_id;
}
}
You can do it in this form:
$this->db->select('pr.name');
$this->db->from('product as pr');
$this->db->where('pr.id', 4);
return $this->db->get()->row_array();
with row_array() you will get one row, with result_array() you will get result of array.
There are so many solutions.. I prefer HMVC, but for demo purpose to explain "how it works", solutions inside controller (terrible,sucks!!!!)
Answer for using shorts table as alias, pls read rtfm or use simple query and generating results
For join methods,you can use too. Happy coding

Resources