I have very strange situation.
The following code is working on my localhost, but on my server it is not working.
I got the error "Base table or view not found: 1146 Table 'beteu.bets' doesn't exist". The Model is looking not in the right database, that's why it cannot find the table. But he is not supposed to look in that database.
In the function, where I am calling the method i have made following test to check what is the active database:
DB::connection()->getPdo();
if(DB::connection()->getDatabaseName()){
echo "Yes! Successfully connected to the DB: " . DB::connection()->getDatabaseName();
}
die();
So here as a result I got the correct database "soccerbets", but than I try to output all results in the "bets" table like that:
DB::connection()->getPdo();
if(DB::connection()->getDatabaseName()){
echo "Yes! Successfully connected to the DB: " . DB::connection()->getDatabaseName();
print_r(Bet::get());
}
die();
And here I got again the strange error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'beteu.bets' doesn't exist
Here is the code of the Bet model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Bet extends Model {
protected $fillable = [
'ip', 'site',
];
}
I have tried also to define explicit the database in that Model, but nothing happens.
Please help me find that stupid error :)
The variable you are looking for in your model is
protected $connection = "connection of your second db name";
You also have to define a new connection (database) in your /config/database.php
If you don't want to expose your credentials in versioning, you also have to add at least one new .env variable to set the connection.
So similar to your default "mysql" connection, you can add a new connection, you can set the default connection in your .env
Related
I'm facing an issue to do insert query into the database.
Not sure is a setting issue or a connection issue. The setting I did at .env file while the query I did at controller site
Here is my setting at env file:
CI_ENVIRONMENT = development
app.baseURL = 'http://localhost:8080/'
database.default.hostname = 127.0.0.1 #localhost:8080
database.default.database = learn_ci4_tutorial
database.default.username = root
database.default.password =
database.default.DBDriver = MySQLi
here my code at controller site:
public function __construct(){
this->db = \Config\Database::connect();
}
public function insertRaw(){
echo "<h1>Test connection</h1>";
$insert_query = "Insert into tbl_user(name,email,phone_no) values('Alyah','aliyah#gmail.com','123456')";
$this->db->query($insert_query);
if($this->db->query($insert_query)){
echo "<h1>Insert record successful.</h1>";
}else{
echo "<h1>Insert record failed.</h1>";
}
}
here the error come out:
ErrorException #1
Uncaught ErrorException: print_r(): Property access is not allowed yet in C:\xampp\htdocs\ci4\app\Views\errors\html\error_exception.php:96
Which part should I fix so I can do insert query to database?
I am trying to update the column with some other data but database table is not letting me update the table because of the NOT NULL constraints in it. I have this option of setting all the fields to NULL but I dont think that will be a good practice. Please I need a solution to it if anyone can help. I get the following error
Illuminate \ Database \ QueryException (HY000)
SQLSTATE[HY000]: General error: 1364 Field 'first_name' doesn't have a default value (SQL: insert into users (subject_id, updated_at, created_at) values (?, 2019-07-30 13:46:42, 2019-07-30 13:46:42))
Previous exceptions
SQLSTATE[HY000]: General error: 1364 Field 'first_name' doesn't have a default value (HY000)`
I have tried setting all the values to NULL and it worked but I want to work with some fields setting as NOT NULL and update the ones which are NULL and also if we can fetch or set the fields automatically to what we have ?
This is my controller where I am trying to update the field if this is required or help you understand my problem
public function deleteSubject($id) {
echo $id;
// die();
if(Auth::check()) {
$findSubject = Auth::user()->where('subject_id', $id);
$users = new User();
$users->subject_id = null;
$users->save();
// echo($findSubject);
// die();
Session::flash("message", "You subject has been deleted. You can add a new Subject now.");
return redirect('/subjects');
} else {
Session::flash("message", "Please sign in to access this page");
return redirect('/signup');
}
}
The following should work for your code. As it was said in the previous comment, it's because you try to create a new instance of a user without inserting value.
It look like you are trying to delete the subject associate with the authenticated user, so I suppose that you don't really need to create a new user, instead I think you should dissociate the user and the subject. So, the following should work for your code.
The purpose of that variant is to take the authenticated user and put a null value for the subject_id.
public function deleteSubject($id) {
echo $id;
// die();
if(Auth::check()) {
$user = User::where('subject_id', $id)->first(); // This will get the user that have the subect_id, but it's assuming that only one user have this subject_id.
// You can also do this just uncomment the first line below and comment the other one above.
// $user = User::find(Auth::user->id);
$user->subject_id = null;
$user->save()
Session::flash("message", "You subject has been deleted. You can add a new Subject now.");
return redirect('/subjects');
} else {
Session::flash("message", "Please sign in to access this page");
return redirect('/signup');
}
}
I think that you should take a look about how MVC work.
https://selftaughtcoders.com/from-idea-to-launch/lesson-17/laravel-5-mvc-application-in-10-minutes/
You should also take a look at relationship in Laravel: https://laravel.com/docs/5.8/eloquent-relationships
MVC and Eloquent-Relationships will help you understand some function in laravel to achieve this kind of goal really quickly.
If you get a User model and a Subject model, you can simply do something like this:
$user = User->find(Auth::user()->id);
$user->subjects()->dissociate($id);
I'm not sure, but I think the Auth facade let you use the user model function, so maybe this could work to:
Auth::user()->subjects()->dissociate($id);
You should also take a look at middleware: https://laravel.com/docs/5.8/middleware
With middleware, you can put rules like the one you are using to send a message to the user saying that he/she need to be log in to access the page into the middleware and reusing it whenever you need.
I am developing a document archive system and i want the user to be able to upload a file to a specific folder that should be linked to an existing user in the database. what do i need to do?
This is for xampp server running PHP 7.0.3 and with Laravel 5.4. I am able to upload a file but it has no owner.
No code to display.
I expect to be able to search for a user according to their name and retrieve their files
You may want to use one to many relationships for this.
First create a document model and migration with below command.
php artisan make:model Document -m // -m option for migration file
Configure user and document models for one to many relation
User Model
public function documents()
{
return $this->hasMany('App\Document');
}
Document Model
public function user()
{
return $this->belongsTo('App\User');
}
create_documents_table Migration
Edit migration file and add name, path,type etc.. columns..
public function up()
{
Schema::create('documents', function(Blueprint $table)
{
$table->increments('id');
$table->string("name");
$table->string("path");
$table->string("type");
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
then run php artisan:migrate command.
Done! So let upload a file..
public function upload(Request $request){
// get file from request
$file = $request->file("document");
// get username for file path (if user directory doesn't exist, Storage gonna create it)
$username = $request->user()->username;
// make file name unique
$file_name = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$realName = str_slug($file_name); // it makes seo frendly
$extension = $file->getClientOriginalExtension();
$newFileName = $username."/".$realName . "-" . time() . "." . $extension;
// store document on db (make sure these columns fillable on model or it throws error)
$request->user()->documents()->create([
"name"=>$file_name
"path"=>$newFileName
"type"=>"document"
]);
// move uploaded file
Storage::disk("locale")->put($newFileName,file_get_contents($file));
}
For more further I strongly to suggest you to read documents. It makes you to understand how eloquent handle with the relational queries
File uploads should not be handled by folders. When you upload a file, give it a unique name. Save this name in a database files for example, where you have columns user_id, and file_name. Then when you want to get all files for a specific user you just send query to the database. Laravel already has most of this done and it looks like this:
$uploadedImage = $request->image->store('images');
This will return something like this:
"images/7UmX8yrOs2NYhpadt4Eacq4TFtpPGUCw6VTRJhfn.img"
then you do something like this:
$image = new Image();
$image->user_id = $user_id;
$image->path = $uploadedImage();
$image->save();
If you want to give the name for the image yourself you can use storeAs instead of store method like this:
$uploadedImage = $request->image->storeAs('images', $filename);
right now, I am kinda frustrated and I hope someone can help me and point me into the right direction.
I have an "old" project which uses the mysql statements for connection to database, etc.
Within this project I have the following:
An index file containing
*
* load configuration and connect to database
*/
$projectConfiguration = new projectConfiguration();
$dbconnect = $projectConfiguration->connect($projectConfiguration->databaseHost, $projectConfiguration->databaseName, $projectConfiguration->databaseUser, $projectConfiguration->databasePass);
// load controller
$ReqMod = FatFramework\Functions::getRequestParameter("mod");
if (!$ReqMod) {
$ReqMod = FatFramework\Functions::getRequestParameter("controller");
}
$module = ($ReqMod) ? $ReqMod : 'default';
In this style I call the views and actions in classes, like SaveAction()
Using mysql always made it very simple to use this database connection in the models called by the controllers like
public function loadCustomersList($sAdditionalWhere = false)
{
$sQuery = "SELECT * FROM customers WHERE 1 ";
if ($sAdditionalWhere) {
$sQuery .= "AND " . $sAdditionalWhere . " ";
}
$sQuery .= "ORDER BY company";
$sql = mysql_query($sQuery);
while (($customer = mysql_fetch_object($sql)) != false) {
$aCustomers[] = $customer;
}
return $aCustomers;
}
I want to totally refractor this project and use PDO. I tried for the last 4 hours to find a solution, but I can't figure out how to make it work.
I think I don't need an extra dbconnect class since PDO is a class itself, am I right?
In the new index file I tried the following:
$db = new database();
try{
$dbc = new PDO($db->get_DbConSettings());
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e)
{
echo 'Verbindung fehlgeschlagen: '.$e->getMessage();
}
But with this $dbc will not available in controllers or models. It there a way to make it available there? If not, what is the best solution?
Do I have to make a database connection in every model?
An other issue I have with this is:
$db->get_DbConSettings()
in
$dbc = new PDO
gives back
'mysql:host=127.0.0.1; dbname=c1virtbkk', 'root', '123'
($dbc = new PDO('mysql:host=127.0.0.1; dbname=c1virtbkk', 'root', '123');)
I cannot connect to the database. I get the following:
Verbindung fehlgeschlagen: could not find driver
If I don't use $db->get_DbConSettings and put the required information manually in, I don't get any error and can do queries. Any hints?
Help is really appreciated.
Thanks in advance!
Mark
Definitely don't create a new PDO connection in each model. Creating MySQL database connections is fairly quick, but there's still some overhead to doing so. You want to reuse a connection throughout your request. If nothing else, it allows you to share a transaction across multiple models.
Some frameworks store shared resource objects in a "registry" class which is a singleton key-value store. It's not really much more than a global hash array, but making it a class makes the registry itself more easily tested with PHPUnit. See https://framework.zend.com/manual/1.12/en/zend.registry.using.html for an example of a registry.
You're right that PDO is a class, even though it's implemented as a C extension instead of a PHP class. But it's a class, and new PDO(...) returns an object of that class.
One reason to create a db class of your own is to help you in unit-testing, because you could create a mock object for your db class so you can test your other classes (even model classes) without needing a live database connection. Your db class could extend or else contain a PDO object.
Your issue about the error "could not find driver" is probably because the PDO driver for mysql is not installed. PDO is one PHP extension, and then there's a separate extension for each brand of SQL database. You can confirm this with:
$ php -i
...lots of output...
PDO
PDO support => enabled
PDO drivers => mysql, odbc, sqlite
pdo_mysql
PDO Driver for MySQL => enabled
Client API version => mysqlnd 5.0.11-dev - 20120503 - $Id: 76b08b24596e12d4553bd41fc93cccd5bac2fe7a $
...more output for other extensions...
Note that PDO tells me which drivers I have installed: mysql, odbc, and sqlite.
So you need to install pdo_mysql. I'm not sure what OS you're on, but I'm often on CentOS Linux or Ubuntu Linux. The pdo_mysql is available as a separate package via yum or apt.
Re your comment:
Okay, here's an example of a registry:
class registry {
protected static $items = array();
public static get($key) {
return isset(self::$items[$key])?
self::$items[$key] : null;
}
public static set($key, $object) {
self::$items[$key] = $object;
}
}
In your controller initial code, you'd create a database object and store it in the registry:
$projectConfiguration = new projectConfiguration();
$dbconnect = $projectConfiguration->connect(
$projectConfiguration->databaseHost,
$projectConfiguration->databaseName,
$projectConfiguration->databaseUser,
$projectConfiguration->databasePass);
registry::set('db', $dbconnect);
Then in your model class methods (or anywhere you need the database), get the db object from the registry and use it:
public function loadCustomersList($sAdditionalWhere = false)
{
$sQuery = "SELECT * FROM customers WHERE 1 ";
if ($sAdditionalWhere) {
$sQuery .= "AND " . $sAdditionalWhere . " ";
}
$sQuery .= "ORDER BY company";
$db = registry::get('db');
$stmt = $db->query($sQuery);
$aCustomers = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $aCustomers;
}
Actually I working now in magento for developing a module to check the voucher code used or not. The details are stored in a new table. In my config.xml, I specified the observer page for fetching the details from db table. But I don't know the exact use of observer page in magento. Can I use observer page for this usage.
But it proceed to an error
I checked the log file
which is
a:5:{i:0;s:203:"SQLSTATE[42000]: Syntax error or access violation: 1064 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 '=' at line 1";i:1;s:1677:"#0 C:\wamp\www\Mymagento\lib\Varien\Db\Statement\Pdo\Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
My observer.php file is also shown below
class Module_Voucher_Model_Observer
{
public function __contruct()
{
$coupon_code = trim(Mage::getSingleton("core/session")->getData("coupon_code"));
}
public function getresultofVoucher($coupon_code)
{
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$table = "voucher_code_status_table";
$query = 'SELECT * FROM ' . $table. 'WHERE value='.$coupon_code;
$results = $readConnection->fetchAll($query);
return $results;
}
}
Please help what is the mysql error here. Please help as soon as possible
Thanks in advance
Observer.php is a model class file, like all models this also can be called any were we need its function.
Normally we use observers when using magento events. In config.xml we declare events and we use observer functions to handle the event when it occurs.
I have gone through your error and code. It seems the code doesn't get the value of coupon code. Please check whether there is any value coming in $coupon_code.
That may be the issue.
Thanks.
An observer is an EventListener, events are dispatched in Magento with:
Mage::dispatchEvent('event_name', array('item' => $this));
When an event is dispatched, Magento will check which observers are bound to it, and will call the function defined in the config with a Varien_Event_Observer object as its parameter.
You're function could be something like this:
public function getresultofVoucher(Varien_Event_Observer $observer)
{
$item = $observer->getItem();
// do something with it
}