Creating and filling database from a Controller (Symfony 2, Doctrine) - mysql

I am trying to create an installation Bundle for my Symfony 2.2.3 application.
Therefore I want to drop/create a database (mysql) and then create the schema via Controller Actions.
My Code:
$kernel = $this->get('kernel');
$application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
$application->setAutoExit(false);
// drop old database
$options = array('command' => 'doctrine:database:drop', '--force' => true);
$application->run(new \Symfony\Component\Console\Input\ArrayInput($options));
// create new database
$options = array('command' => 'doctrine:database:create');
$result = $application->run(new \Symfony\Component\Console\Input\ArrayInput($options));
// check if database:create was successful, then create schema
if($result == 0) {
$options = array('command' => 'doctrine:schema:create');
$result = $application->run(new \Symfony\Component\Console\Input\ArrayInput($options));
}
database:drop and database:create work fine (both commands return 0), but creating the schema then fails.
However, when I comment the first 2 commands out so that only doctrine:schema:create will be executed (if clause removed, of course) and reload the page without changing anything else the database schema will be created properly.
Can anyone tell me what the problem is?

This code works (Symfony 2.7)
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
/**
* #Route("/resetDB", name="adminResetDB")
*/
public function resetDBAction()
{
$application = new Application($this->get('kernel'));
$application->setAutoExit(false);
// Drop old database
$options = array('command' => 'doctrine:database:drop', '--force' => true);
$application->run(new ArrayInput($options));
// Make sure we close the original connection because it lost the reference to the database
$this->getDoctrine()->getManager()->getConnection()->close();
// Create new database
$options = array('command' => 'doctrine:database:create');
$application->run(new ArrayInput($options));
// Update schema
$options = array('command' => 'doctrine:schema:update','--force' => true);
$application->run(new ArrayInput($options));
// Loading Fixtures, --append option prevent confirmation message
$options = array('command' => 'doctrine:fixtures:load','--append' => true);
$application->run(new ArrayInput($options));
return $this->redirect($this->generateUrl('index'));
}

Related

not responding while login

I am new to CodeIgniter, and am trying to write code to log in after registering using a username and password in registration form using a PHPMyAdmin database. I am not getting anything when I try to log in, and it doesn't display an error or any message.
public function login() {
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password' , 'Password');
if($this->form_validation->run() == TRUE){
//check user in database
$this->db->select('username' , 'password');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
$user = $query->row();
if($user->email){
$this->session->set_flashdata("Successful login");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user->username;
} else {
$this->session->set_flashdata("Error No such record found");
}
}
// load view and showing login form
$this->load->view('login');
}
First, you should read the documentation, looks like you skip that part, but it's very important!
Let's code a little bit and fix the bugs!
User data
Well, users will enter their data and we will check, if evertyhing is correct, we can redirect user to the protected page. You call for variables (see Query:) but you I'm not seeing on your code. You should put like that, before your query job
$username = $this->input->post("username");
$password = $this->input->post("password");
Now, you will be able to use the where to get the user data. =)
Query:
If read about OOP with PHP, you know that when you pass parameters to a method, each parameter have their own "action". In case of the select method, you should keep the data you want to select, on the same quote, because you the way you do, it's like you passing multiple parameters to the method.
$this->db->select('username, password');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
First, to decide if the record exist or not, I prefer this way:
if($query->num_rows() > 0) {
$user_data = $query->row();
// We should verify if the user entered the password that correspond to the account.
// If not, we tell them that the password is incorrect.
if($password != $user_data->password) {
$this->session->set_flashdata("error", "Wrong password!");
return redirect(site_url());
}
// You can use the CI built in methods to work with sessions
$this->session->set_userdata(array(
'username' => $user_data->username,
));
$this->session->set_flashdata("success", "You are logged in!");
return redirect(site_url());
} else {
$this->session->set_flashdata("Error: No such record found");
redirect(site_url());
}
Flash data
Yeah, we use flashdata to show a message for the user. But, you should pass an item and the value of this item. Like that:
$this->session->set_flashdata('success', 'Successfully logged in!");
And, to retrieve the data on your views, you can do like...
<?php
$success = $this->session->flashdata("success");
$error = $this->session->flashdata("error");
if(!empty($success)) {
echo $success;
}
if(!empty($success)) {
echo $error;
}
?>
Recommendations
Sessions: https://codeigniter.com/userguide3/libraries/sessions.html
Database: https://www.codeigniter.com/userguide3/database/query_builder.html
Also, I recommed you, to take a minute on YouTube, to understand CodeIgniter.
If I forgot something, let me know! =)
Great Suggestion by webmasterdro's Answer.
I would like to extend it a little bit.
Looking at your code it looks like you have added the query to the controller.
And as a suggestion, if you are using an MVC framework then try to follow some basic MVC flow. because if you are not following that then it will be useless to use a framework.
User Controller to handle the post data and validations.
Use model to do the database query.
Use __construct for loading the common model or libraries.
Do not save plane password use md5 or other encryption technique.
Store User detail to the session which you can use further in after login.
Codeigniter has a great user guide. Try to follow that.
So, your code Should be your like this below.
Controller:
public function __construct() {
parent::__construct();
// Load model
$this->load->model('login_database');
}
public function your_controller_function_name() {
// Check validation for user input in SignUp form
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_form_view');
} else {
$username = $this->input->post("username");
$password = $this->input->post("password");
$result = $this->login_database->registration_insert($username, $password);
//You can do this also if($result != FALSE)
if (!empty($result)) {
// You can set other data to the session also form here
$session_data = array(
'username' => $result['user_name']
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
// You can set flash data here
$this->load->view('your_view');
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('your_login_form_view', $data);
}
}
}
Model:
// Read data using username and password
public function login($username, $password) {
$this->db->select('username');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
$user_data = $query->row_array();
if ($query->num_rows() == 1) {
return user_data;
} else {
return false;
}
}
I have not added detail related to flash data because the previous answer has explained it properly.

Create custom url links in code igniter

I have searched all over the internet for information that would help me achieve this seemingly simple thing.
But I can't get my hands on any that is helpful.
What I want to do is to create a custom url link like http://mywebsite.com/users/username,
where
1) 'users' is a MySQL table name
2) 'username' is a column name.
I did some digging on the internet and found this code on github:
<?php
//check for referal links
function referal()
{
$CI =& get_instance();
$cookie_value_set = $CI->input->cookie('_tm_ref', TRUE) ? $CI->input->cookie('_tm_ref', TRUE) : '';
if ($CI->input->get('ref', TRUE) AND $cookie_value_set == '') {
// referred user so set cookie to ref=username
$cookie = array(
'name' => 'ref',
'value' => $CI->input->get('ref', TRUE),
'expire' => '7776000',
);
$CI->input->set_cookie($cookie);
return TRUE;
}elseif ($cookie_value_set == '') {
$cookie = array(
'name' => 'ref',
'value' => 'sso',
'expire' => '15552000',
);
$CI->input->set_cookie($cookie);
return TRUE;
}elseif ($cookie_value_set != '') {
//already referred so ignore
return TRUE;
}else{
return TRUE;
}
}
//end of hooks file
?>
The owner of the gist only mentioned saving the file as referral.php inside the hook folder. This is not helping me with what I want to achieve, I don't know how to use the code:
1. How do I pass the referrer field to the variable username from the users table?
2. How do I load the hook file to view (register.php)?
3. How and where do I call the hook file?
So can anybody give me an insight?

API Json in symfony form

i'm creating an application in symfony 2.8 (with php5.4) and in my form (that i'm building) i want to display a list of a projects through an API in json format.
Now i'm stuck, and i don't know how to do this.
I know the database of the API there is a table "projects" and i want target the column 'name' to display names of projects
here's my code:
/**
* #Route("/form")
*/
public function formAction(Request $request)
{
$url = 'https://website.com/projects.json';
$get_json = file_get_contents($url);
$json = json_decode($get_json);
$form = $this->createFormBuilder()
->add('Project', 'choice') // <-- ???
->add('send', 'submit' ,array('label' => 'Envoyer'))
->getForm();
$form->handleRequest($request);
return $this->render('StatBundle:Default:form.html.twig', array('form' => $form->createView(), 'project' => $json));
}
You can pass the choice as second argument as array as example:
$jsonAsArray = json_decode($get_json, true); // with true return an array
$builder->add('Project', 'choice', array(
'choices' => $jsonAsArray,
// *this line is important, depends of the data*
'choices_as_values' => false,
));
More info in the doc here.
Hope this help

Codeigniter Image uploading not working on live server

I have a situation where a user uploads his/her trip photos. They are saved in a folder and also supposed to be in database. Situation is: my code is working perfectly on localhost, and many other servers, but not on the server I want. Though it uploads files successfully, but the query is not executed which is supposed to save file path in database. I am stuck in this problem from more than a week. The same code works in other places. Here is my controller:
public function trip_photos(){
$this->load->model('UserModel');
$this->load->model('CommentModel');
$this->load->library('session');
print_r($_FILES);
$logged_session = $this->session->userdata('login');
if($logged_session == 1) {
$this->load->model('TripModel');
$this->load->model('UserActivityModel');
$uid = $this->session->userdata('uid');
$tid = $this->input->post('tid');
foreach($_FILES as $key => $image_upload){
$upload = self::upload_trip_photo($key);
if($upload['status']){
$this->TripModel->add_trip_photo($uid, $tid, $upload['file']);
}
}
$this->UserctivityModel->add_user_photo($uid, $tid);
}else{
redirect('/');
}
}
private function upload_trip_photo($image){
$msg = '';
$config['upload_path'] = './assets/images/trip/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['file_name'] = parent::getGUID();
$this->load->library('upload', $config);
if ($this->upload->do_upload($image))
{
$data = $this->upload->data();
$resize['image_library'] = 'gd2';
$resize['source_image'] = "./assets/images/trip/" . $data['file_name'];
$resize['create_thumb'] = TRUE;
$resize['maintain_ratio'] = TRUE;
$resize['width'] = 222;
$resize['thumb_marker'] = '';
$resize['new_image'] = "./assets/images/trip/thumbnails/" . $data['file_name'];
$this->image_lib->resize();
$this->image_lib->clear();
$this->image_lib->initialize($resize);
if($this->image_lib->resize()){
$status = true;
$msg = $data['file_name'];
}else{
$status = false;
}
}
else
{
$status = false;
}
#unlink($_FILES[$image]);
return array('status' => $status, 'file' => $msg);
}
when I enabled CI_Profiler, it says that only 2 out of 3 query executed on the server I want it to work. But the same profiler suggests that 3 of 3 queries executed on localhost or other servers. Its so confusing.
Please note that I already have checked the following:
File Upload: On
upload_raw_post_data: On
selinux permissions: disables (mine is centos)
File permissions: 777
php memory_limit: 128 MB
max_size: 8 MB
var_dump, print_r, echo all not working or displaying any information from controller.
somehow, this in above code: $upload = self::upload_trip_photo($key); is not giving it back the file path it requires. Can anybody help please? #DFriend
UPDATED Turns out that in the localhost are other servers where its working, this array is returned by the function upload_trip_photo to the $upload variable:
Array ( [image0] => Array ( [name] => maintour3.jpg [type] => image/jpeg
[tmp_name] => D:\xampp\tmp\php2539.tmp [error] => 0 [size] => 200491 ) )
array(2) { ["status"]=> bool(true) ["file"]=> string(36)
"E3965DFC8B265CEFF522A1EC43B33E34.jpg" }
while in the server where its not working, only this array is returned:
Array ( [image0] => Array ( [name] => mg7.jpg [type] => image/jpeg
[tmp_name] => /tmp/phpNcCnX0 [error] => 0 [size] => 28460 ) )
It means this statement in the upload_trip_photo() function:
return array('status' => $status, 'file' => $msg);
is not returning the requested array, with file name and status. And why? I am totally clueless.
Help Please!
Thankfully this worked after extensive debugging. The line
if($this->image_lib->resize()){
$status = true;
$msg = $data['file_name'];
}else{
$status = false;
}
was not working. Later when I set it to display_error() method, it showed that my server did not support GD library. This is an essential library to manipulate Graphics. So, the query was not being executed, as the $status variable was set to false.
I recompiled my php with GD Library module. And bigno! its working now.
Thanks for staying with me. :)

Zend framework complains that "There is already an active transaction"

we are using zend_db_table and we are having some issues since Zend Framework is complaining about two transactions being active:
[message:protected] => There is already an active transaction
[string:Exception:private] =>
[code:protected] => 0
[file:protected] => /var/www/vhosts/test.local/private/library/Zend/Db/Adapter/Pdo/Abstract.php
[line:protected] => 305
[trace:Exception:private] => Array
This is the code in the Controller:
public function convertAction()
{
$this->setNoRender();
// If the quote is a copy of a previous one, fetch all the datas
$quoteId = Zend_Filter::filterStatic($this->getRequest()->getParam('qte_id'), 'int');
$quoteTable = new Model_QuotesTable();
$quoteRow = $quoteTable->findById($quoteId);
if (count($quoteRow)) {
$clonedId = $quoteRow->convertToJob();
$this->flashMessageRedirect('Quotation successfully converted', '/jobs/edit/job_id/' . $clonedId);
} else {
$this->flashMessageRedirect('Unable to find the quote to be converted', '/quotes');
}
}
which is recalling this function in QuotesTableRow which extends zend_db_table_abstract:
public function convertToJob()
{
$db = $this->_getTable()->getAdapter();
$db->beginTransaction();
$jobsTable = new Model_JobsTable();
try {
/*
* Update the status of the old row to match the $status passed into this function
*/
$this->qte_status = "Accepted";
$this->save();
/*
* Create new row with the same details as above
*/
$newRow = $jobsTable->createRow();
$newRow->job_title = $this->qte_title;
$newRow->job_cus_id = $this->qte_cus_id;
$newRow->job_enq_id = $this->qte_enq_id;
$newRow->job_qte_id = $this->qte_id;
$newRow->job_title = $this->qte_title;
$newRow->job_description = $this->qte_description;
$newRow->job_work_location_id = $this->qte_work_location_id;
$newRow->job_work_category_id = $this->qte_work_category_id;
$newRow->job_work_type_id = $this->qte_work_type_id;
$newRow->job_cus_code = $this->qte_cus_code;
$newRow->job_cus_name = $this->qte_cus_name;
$newRow->job_wt_ref_code = $this->qte_wt_ref_code;
$newRow->job_wt_description = $this->qte_wt_description;
$newRow->job_wl_code = $this->qte_wl_code;
$newRow->job_wl_description = $this->qte_wl_description;
$newRow->job_wc_ref_code = $this->qte_wc_ref_code;
$newRow->job_wc_description = $this->qte_wc_description;
$newRow->job_qte_title = $this->qte_title;
$newRow->job_datetime_created = date('Y-m-d H:i:s');
$newRowId = $newRow->save();
$db->commit();
return $newRowId;
}
catch (Exception $e) {
$db->rollback();
echo('<pre>');
print_r($e);
echo('</pre>');
exit();
throw new Exception($e->getMessage());
return false;
}
}
in addition, it seems to be related to the model we are not in since if we comment the row with the save() function related to the Model_JobsTable() the script is working, while it returns the same error when we comment the other save().
This error is being returned from MySQL and ZF is only telling you the error message.
Are you starting two transactions in the same request? That can explain why you got this error message, or you could have had an aborted connection that was in the middle of a transaction and it didn't get rolled back or auto-committed.
You should only start one transaction per database connection. If you need two models to have an active transaction in a single request, then you need to get 2 separate database connections.
See this (great) answer by Bill Karwin in regards to this issue.
You can run the query SHOW ENGINE InnoDB STATUS; to get a list of active transactions. If you have one that is open and you have no active transactions from PHP/ZF, then try closing that transaction, otherwise you'll have to look into your code and see how two transactions are getting started in the same request.
Thanks for your answer, we found a solution.
The problem was that, we were using the save() function twice; changing the first save() with an insert(), solved the problem:
public function convertToJob()
{
$db = $this->_getTable()->getAdapter();
$db->beginTransaction();
$jobsTable = new Model_JobsTable();
try {
/*
* Create new row with the same details as above
*/
$data = array(
'job_cus_id' => $this->qte_cus_id,
'job_enq_id' => $this->qte_enq_id,
'job_qte_id' => $this->qte_id,
'job_title' => $this->qte_title,
'job_description' => $this->qte_description,
'job_work_location_id' => $this->qte_work_location_id,
'job_work_category_id' => $this->qte_work_category_id,
'job_work_type_id' => $this->qte_work_type_id,
'job_cus_code' => $this->qte_cus_code,
'job_cus_name' => $this->qte_cus_name,
'job_wt_ref_code' => $this->qte_wt_ref_code,
'job_wt_description' => $this->qte_wt_description,
'job_wl_code' => $this->qte_wl_code,
'job_wl_description' => $this->qte_wl_description,
'job_wc_ref_code' => $this->qte_wc_ref_code,
'job_wc_description' => $this->qte_wc_description,
'job_qte_title' => $this->qte_title,
'job_datetime_created' => date('Y-m-d H:i:s')
);
$newRowId = $jobsTable->insert($data);
/*
* Update the status of the old row to match the $status passed into this function
*/
$this->qte_status = "Accepted";
$this->save();
$db->commit();
return $newRowId;
}
catch (Exception $e) {
throw new Exception($e->getMessage());
return false;
}
}