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?
Related
I want to get data from another DB in MySQL except the defualt DB. I added the following line into my model in addition to the excisting code. Another DB as 'storesDB'.
$this->load->database('storesDB', TRUE);
My model as follows :
public function getEquipment($id = null)
{
$this->db->select('*');
$this->db->from('tbl_equipment');
$this->db->join('tbl_equipment_category', 'tbl_equipment.eq_cat=tbl_equipment_category.id_cat');
$this->db->where("tbl_equipment.status", '1');
if ($id)
$this->db->where("tbl_equipment.id", $id);
$query = $this->db->get();
return $query->result();
}
The code is working properly. But the code got data from defualt DB not the by the 'storesDB'.
Modified code is as follows :
public function getEquipment($id = null)
{
$this->load->database('storesDB', TRUE);
$this->db->select('*');
$this->db->from('tbl_equipment');
$this->db->join('tbl_equipment_category', 'tbl_equipment.eq_cat=tbl_equipment_category.id_cat');
$this->db->where("tbl_equipment.status", '1');
if ($id)
$this->db->where("tbl_equipment.id", $id);
$query = $this->db->get();
return $query->result();
}
What may be the reason?
The reason is that you don't assign the second database properly. You also need to setup the correct config for the 2nd database
$config['hostname'] = "host";
$config['username'] = "user";
$config['password'] = "pass";
$config['database'] = "storesDB";
// etc..
then you load the database:
$this->db2 = load->database($config, TRUE);
now you have $this->db, the default database and $this->db2, the second database
and continue your code like:
$this->db2->select('*');
$this->db2->from('tbl_equipment');
// etc...
I have no experience in Codeigniter, but in a standar sql query you can add the database name in front of the table to get info from another db like:
SELECT * FROM sakila.actor;
Assuming you are not connected to sakila db.
Using this aproach both databases must have same credentials
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;
}
i m trying to save data to my base and everything is ok and suddenly when i click at add button in form this screen appears
my output
i havent understand why and where is the problem causing that
in my controller action i have tried to dump my object that i want to add in my database and i got this output so everything is ok object data
this is my controller action
public function addAction(Request $request)
{
if($request->isMethod("post")){
$title = $request->get('title');
$image = $request->get('image');
$genre = $request->get('genre');
$date = $request->get('date');
$director = $request->get('director');
$stars = $request->get('stars');
$trailer = $request->get('trailer');
$synopsis = $request->get('synopsis');
$movie = new Movie();
$movie->setTitle($title);
$movie->setImage($image);
$movie->setGenre($genre);
$movie->setDate($date);
$movie->setDirector($director);
$movie->setStars($stars);
$movie->setTrailer($trailer);
$movie->setSynopsis($synopsis);
dump($movie);
die();
$em= $this->getDoctrine()->getManager();
$em->persist($movie);
$em->flush();
return new Response("film added");
}
return $this->render('FilmsFilmsBundle:Pages:add.html.twig');
}
i have found that my input date is causing this problem
so i changed it by <input type="text"> and i changed the annotation for my date variable in my entity from date to string and everything is working fine
There is obviously a code error there. If you are using apache, you can check the error log on linux using
tail -f /var/log/apache2/error-log.txt
on windows it's usually <base path to apache install>\logs
I'm migrating an old web app based on SQL Server and ASP to Symfony2 and MySQL. I made some queries and export old data to individual SQL files.
How can I execute thoses files in my fixtures, when I run the command
$php app/console doctrine:fixtures:load
Now I have some fixtures that works directly with Doctrine ORM and entities, but I have a lot of data to import.
I find a good solution. I didn't find an exec method in class ObjectManager, so... this work very well for me.
public function load(ObjectManager $manager)
{
// Bundle to manage file and directories
$finder = new Finder();
$finder->in('web/sql');
$finder->name('categories.sql');
foreach( $finder as $file ){
$content = $file->getContents();
$stmt = $this->container->get('doctrine.orm.entity_manager')->getConnection()->prepare($content);
$stmt->execute();
}
}
In this solution your fixture class has to implement the ContainerAwareInterface with the method
public function setContainer( ContainerInterface $container = null )
{
$this->container = $container;
}
You can load the file contents as a string, and execute native SQL using the EntityManager:
class SQLFixtures extends AbstractFixture implements OrderedFixtureInterface
{
$filename = '/path/to/sql/file.sql';
public function load(ObjectManager $manager) {
$sql = file_get_contents($filename); // Read file contents
$manager->getConnection()->exec($sql); // Execute native SQL
$manager->flush();
}
public function getOrder() {
return 99; // Order in which this fixture will be executed
}
}
Answer for Zend Framework 2.5.3 using Doctrine Data-Fixtures.
Not sure if this applies to the given answers, but they are trying a bit too hard. If you inspect the given $manager object, you'll find that it already is the EntityManager (of interface ObjectManager) (at least, in ZF2). As such you're able to get the Connection directly and it's possible to execute without using $this->container->get('doctrine.orm.entity_manager')
Below a snippet which I use for creating the first user "system", with a createdBy FK reference to itself.
public function load(ObjectManager $manager)
{
$sql = 'INSERT INTO users (
id, username, email, display_name, `password`, created_by)
VALUES (:id, :username, :email, :display_name, :password, :created_by)';
$password = $this->createSuperDuperEncryptedPassword();
// $manager === `EntityManager|ObjectManager`, `->getConnection()` is available
$stmt = $manager->getConnection()->prepare($sql);
$stmt->bindValue(':id', 1);
$stmt->bindValue(':username', 'system');
$stmt->bindValue(':email', 'system#system.test');
$stmt->bindValue(':display_name', 'system');
$stmt->bindValue(':password', password );
$stmt->bindValue(':created_by', 1); // Self reference
$stmt->execute();
}
I have a local and a remote connection with my mysql database. The local connection works just fine. But the remote connection, while it makes a connection, it does not return anything. I usually get the following:
Fatal error: Call to a member function result() on a non-object
I use for the remote connection the following configuration:
$db['mydb']['hostname'] = "ip_address_of_database";
$db['mydb']['username'] = "username";
$db['mydb']['password'] = "password";
$db['mydb']['database'] = "database";
$db['mydb']['dbdriver'] = "mysql";
$db['mydb']['dbprefix'] = "";
$db['mydb']['pconnect'] = FALSE;
$db['mydb']['db_debug'] = FALSE;
$db['mydb']['cache_on'] = FALSE;
$db['mydb']['cachedir'] = "";
$db['mydb']['char_set'] = "utf8";
$db['mydb']['dbcollat'] = "utf8_general_ci";
In my function that accesses the database I check if there is a connection with the remote server and then I try to retrieve data.
$mydb = $this->load->database('mydb', TRUE);
if (!isset($mydb->conn_id) && !is_resource($mydb->conn_id)) {
$error = 'database is not connected';
return $error;
}else{
$query = $mydb->query("SELECT * FROM database LIMIT 1;");
return $query->result();
}
This works fine in the localhost database but not in the remote database. I allways get the error
Fatal error: Call to a member function result() on a non-object
Can you please help? What am I doing wrong? I stuck on this.
Finally, I found the solution after contacting my web hosting provider. The issue had to do with the Remote database access and their servers. The IP address exception and the domain name that I had added didn’t do the job. I had to add an internal domain name that my host was using in order the Remote database access to be allowed. I spent 2-3 hours chatting with them in order to find a solution.
Anyway now is solved. I am posting that FYI.