Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
What I am trying to do is to get a telephone contact list from a page content.
All my pages are stored in a database, which I have successfully accessed using Code Igniter.
I want to output a telephone contact list as HTML table. This list is located on one of the pages. The content of this page is saved as BLOB type in the old_text column of the table text in my MySQL database.
I know the old_id value of my page in the table text. I think it might be useful.
How can I find this contact list using MYSQL commands in php script?
Here is my code how I have selected the old_text value of the page where the telephone contact list is.
Code Igniter Controller:
class Site extends CI_Controller{
public function index(){
$data['record'] = $this->db->query('SELECT old_text FROM text WHERE old_id = 862');
$this->load->view('home',$data);
}
}
Code Igniter View home.php:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="container">
<?php print_r($record);?>
</div>
</body>
</html>
And I have got as an output:
CI_DB_mysql_result Object ( [conn_id] => Resource id #28 [result_id] => Resource id #29 [result_array] => Array ( ) [result_object] => Array ( ) [custom_result_object] => Array ( ) [current_row] => 0 [num_rows] => 1 [row_data] => )
The reason for this output in my oppinion might be the fact that the old_text content as BLOB type encoded is.
I have also tried the following command in order to return BLOB field as a varchar, but I have got the same output.
SELECT cast(old_text AS char) FROM text WHERE old_id = 862
As you can see in the output, $data['record'] is a CI_DB_mysql_result Object.
So you will "get" data from this object. Assuming you only have 1 result you have to do:
class Site extends CI_Controller
{
public function index()
{
$res = $this->db->query('SELECT old_text FROM text WHERE old_id = 862');
if ($res->num_rows() > 0)
{
$data['record'] = $res->row();
}
else
{
$data['record'] = "no result";
}
$this->load->view('home',$data);
}
}
If you have multiple result you have to loop on the $res.
You can take a look at http://ellislab.com/codeigniter/user-guide/database/results.html
Related
My app's goal is to schedule posts through a franchise to its franchised.
The HQ schedules a post for a certain date and time, with text and potential image.
It creates the post with all necessary information in the database for each franchised(id, franchise_id, user_id, text, image, network, post_id)
post_id contains an id that is the same for each row that are completely identical besides the franchise_id.
When I add a post, it works well. But when editing, since it gets the ID of the post, it'll only edit the post that matches the id.
And that is fine when it is a franchised, it will then change the post_id to a custom value, and will be independent to the others.
But when it's the HQ(superadmin)logged in, I want him to edit all that matches the selected one by post_id.
Query builder is not something I'm used to and sometimes I thought about dropping it for standard SQL, but if it's there it's for a reason, so I would like your help in solving this with Cakephp's query builder.
public function edit($id = null){
$event = $this->Events->get($id);
if ($this->request->is(['post', 'put'])) {
$event = $this->Events->patchEntity($event, $this->request->data,['associated' => ['Networks'], ]);
if($isuper == 'true'){//if logged in user is superadmin
}else{
$event->user_id = $this->Auth->user('id');
}
if ($this->Events->save($event)) {
$this->Flash->success(__('your post has been updated'));
return $this->redirect(
[
'action' => 'index',
date('Y', $event->date->getTimestamp()),
date('m', $event->date->getTimestamp()),
$event->company_id
]
);
}
$this->Flash->error(__('unable to update your post'));
}
$this->set('event', $event);
$this->layout = 'ajax';
}
You could try making bulk updates using updateAll
Something like:
$this->Events->updateAll(
['field' => true], // whatever fields you are updating
['post_id' => 'some_id'] // the selected post_id
);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to create an online directory, where, for example, people can search through the website and find all takeaways that have a specific type. For example:
"Indian",
"Chinese"
etc..
I have 3 tables:
Business
Tags
Business Tags
And my model is as follows:
class Business extends Model
{
protected $table = 'businesses';
protected $fillable = [
'business_name', 'postcode'
];
public function tags()
{
return $this->belongsToMany('App\Tags');
}
}
The issue is, whenever I come to do the search, and try to do a whereIn the issue is that it takes forever to load, in fact, it doesn't even load. For example:
$business = Business::whereHas('tags', function($tag) use ($request) {
if($request->get('terms'))
{
$tag->whereIn('tags.name', ['chinese']);
}
})->get();
So my question is this:
I have just over 10k rows of data stored inside the table. This table is split into three "Business", "Tags", "Business Tags". The process above is taking so long to complete, probably because I use the whereHas('tags') and whereIn therefore, how do I go about using the following syntax:
$business = Business::where( function ($business) use ($request) {
// Search for businesses with a specific tag, passed from request
});
Is this possible?
I'm just wild guessing here, but try to pull the condition outside of the function and don't specify the name of the table:
if($request->get('terms'))
{
$business = Business::whereHas('tags', function($tag) use ($request) {
$tag->whereIn('name', ['chinese']);
})->get();
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm creating a form, and I would like to allow the user to choose their country, and their city. What is the most effective way to do it?
For things like state and country, the possible number is reasonably small enough that you can build dropdowns for this without too much hassle. Here is a plugin for jQuery that has a "country picker" pre-made, and you can easily find the same for State on Google.
When you start talking about cities, there are a vastly large number of them. In my opinion, you're far better off using a simple textbox for this and letting the user fill it in themselves.
EDIT
Here is an example of building a country list from a database in MVC:
Country class (Model)
//This class represents a Country
public class Country
{
public int CountryID { get; set; }
public string CountryName {get; set; }
public Country(int countryID, string countryName)
{
this.CountryID = countryID;
this.CountryName = countryName;
}
}
Controller
List<Country> countries = new List<Country>(); //Create a list of Country objects
IEnumerable<SelectListItem> countryList; //List to hold the values for the dropdownlist
SqlConnection connection = new SqlConnection(connectionString); //build a connection with your connection string
connection.Open();
SqlCommand query = new SqlCommand("SELECT CountryID, CountryName FROM Country", connection); //query the table
query.CommandType = CommandType.Text;
SqlDataReader reader = query.ExecuteReader(); //execute the query
while (reader.Read()) //read out the results, set each result to a Country object
{
Country country = new Country(
Convert.ToInt32(reader["CountryID"]),
reader["CountryName"].ToString());
countries.Add(country); //add to the initial list
}
connection.Close();
//build the list of <SelectListItem>s to pass to the view
countryList = countries.Select(c => new System.Web.Mvc.SelectListItem
{
Text = c.CountryName,
Value = c.CountryID.ToString()
});
ViewBag.CountryList = countryList; //add the list to ViewBag
And the View
#Html.DropDownListFor(x => x.ID, new SelectList(ViewBag.CountryList, "Value", "Text"), new { #class = "formItem" })
This code hits your database for the list of countries and builds a List<Country> from the SqlDataReader. Then we turn these results into a List<SelectListItem> to pass into the view.
The result is a dropdown list that will always contain whatever records are in your database. If you add/remove items, the list will be representative of this.
The #Html.DropDownListFor(x => x.ID) binds the selected Value to the model's ID property, so you simply select this value on POST. (Note that your model will need to contain an ID property for this to work!
EDIT to emphasize the "fun" of making a city selector:
I really, really advise against trying to build a city selector. Check out the list of cities in Kansas (something I picked at random). I didn't bother to count these, but this is a pretty big list, and that alone is one state in one country in the world.
If you went with a database, you'd easily have thousands of records for the United States alone, and that only leaves you with 195 other countries to build data for.
Perhaps you can find a repository that already has this information available, but the amount of work required to make this happen seems prohibitive.
i did these two tasks separately but now i am not being able to use both of these tasks at a single place.
Problem statement:
I have a table name Business_items having foreign keys of table business and items. In model class here is the relation function.
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'business' => array(self::BELONGS_TO, 'Business', 'business_id'),
'items' => array(self::BELONGS_TO, 'Items', 'items_id'),
'itemReviews' => array(self::HAS_MANY, 'ItemReview', 'business_items_id'),
);
}
ok, in create business page, i have two fields, business name, items name and a third thing which is upload image. Both of the fields are searchable drop downs. I am taking business name and items name with the help of foreign keys. so i can see the values inside my business_items which were used to be keys. i did this by changing this code.
public function actionCreate()
{
$model=new PackageItems;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['PackageItems']))
{
$temp=$model->items_id=$_POST['PackageItems']['items_id']; //items_id is a multiple list field
foreach($temp as $t)
{
$model->unsetAttributes();
$model->setIsNewRecord(true);
$model->package_id=$_POST['PackageItems']['package_id']; //package_id is a repeated field
$model->items_id=$t;
$model->insert();
}
if($model->save())
$this->redirect(array('admin','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
so what i wanted i actually accomplished which was
id----items----package
1------cake-----buy one get one free
2----- pastry-----buy one get one free
second part:
I know how to upload image in yii, i followed this link and it worked http://www.yiiframework.com/wiki/349/how-to-upload-image-photo-and-path-entry-in-database-with-update-functionality/
separately now the problem is i want something like that
id----items----package-----------------------image
1------cake-----buy one get one free------1.jpg
2----- pastry-----buy one get one free------1.jpg
but the problem is
public function actionCreate()
{
$model=new Banner; // this is my model related to table
if(isset($_POST['Banner']))
{
$rnd = rand(0,9999); // generate random number between 0-9999
$model->attributes=$_POST['Banner'];
$uploadedFile=CUploadedFile::getInstance($model,'image');
$fileName = "{$rnd}-{$uploadedFile}"; // random number + file name
$model->image = $fileName;
if($model->save())
{
$uploadedFile->saveAs(Yii::app()->basePath.'/../banner/'.$fileName); // image will uplode to rootDirectory/banner/
$this->redirect(array('admin'));
}
}
$this->render('create',array(
'model'=>$model,
));
}
how can i use both of these codes (getting value using foreign key code and picture uploading code) i want to upload pictures as well as get the value from some other table using foreign key with my code.
I know its complicated but i need help.
Thanks and sorry in advance.
I'm not sure if I get your problem right, but as far as I understood, you want to upload a file and insert the name of this file in one of your database tables. If that's the case, a solution could be as follows:
First, add a new field to your database table in which you will store the file name, also add it to your ActiveRecord class and to your view.
Then add your code to save your related records (I think your foreach loop is for that).
Next add a the necessary code to upload the image. In the code to upload the image you can see that Yii will treat the file field like a normal text field, in which you will store the uploaded file name.
Finally you should save your model and, if it succeded, then proceed to save the file in the server.
Hope this helps.
UPDATE
I'll put some code in order to clarify my answer.
You say that the first part works for you, then I'll begin with that.
Your model PackageItems needs a new field, let it be image.
Next, I'm assuming that the user filled the form, so I'll skip the if and the render parts
$temp=$model->items_id=$_POST['PackageItems']['items_id'];
$uploadedFile=CUploadedFile::getInstance($model,'image');//get uploaded image info
$rnd = rand(0,9999);
$fileName = "{$rnd}-{$uploadedFile}"; // random number + file name
$model->image = $fileName;//store the new file name in the model
foreach($temp as $t){
$model->unsetAttributes();
$model->setIsNewRecord(true);
$model->package_id=$_POST['PackageItems']['package_id'];
$model->items_id=$t;
$model->insert();
}
if($model->save()){
$uploadedFile->saveAs(Yii::app()->basePath.'/../yourPath/'.$fileName);//if the record was saved in the database, then proceed to save the image in the server
$this->redirect(array('admin','id'=>$model->id));
}
If you want to upload multiple files check this link Yii 1.1: Uploading multiple images with CMultiFileUpload
I have a view model property to hold a list of dropdown selection values like:
private ListDictionary _claimDropdownValueCollection = new ListDictionary();
public ListDictionary ClaimDropdownValueCollection { get { return _claimDropdownValueCollection; } set { _claimDropdownValueCollection = value; } }
On doing the GET, I am looping over a different ListDictionary also in my view model which contains "dropdown type" names:
#foreach (System.Collections.DictionaryEntry de in Model.CCSetting_ClaimDropdownTypeCollection) {
<div class="formRow">
<label>#EverythingToDoWith_CCSetting_ClaimDropdownTypes.getDropdownTypeName(Model.ccClaim.clientID, Convert.ToInt32(de.Key))</label>
<div class="formRight searchDrop">
#Html.DropDownListFor(m => m.ClaimDropdownValueCollection[#de.Key], (IEnumerable<SelectListItem>) #de.Value, new { #class = "chzn-select", #data_placeholder="Choose an option...", #style="width: 350px;" })
</div>
<div class="clear"></div>
</div>
}
So basically, this loads a bunch of dropdowns, their 'label' is printed as per the key in the dictionary. The 'values' for EACH dropdown are obtained from the VALUE of each dictionary, which contains an IENUMERABLE each.
All good so far. Now the user makes his selection on each dropdown and I do an HTTP POST. In the browser developer tools, I see the following data being posted back:
ClaimDropdownValueCollection[1]:2
ClaimDropdownValueCollection[2]:5
ClaimDropdownValueCollection[3]:
ClaimDropdownValueCollection[4]:11
So that is 4 dropdowns with keys 1,2,3,4 (my keys will be more complicated, simple keys here for my example's sake) and three of the four have selections so I pass back the selected ID's 2, 5 and 11.
But the problem is, I am unable to see this data as part of the view model listdictionary object when I debug inside the [HttpPost] controller method that receives the posted data. That is showing the "ClaimDropdownValueCollection" property to be empty.
I am expecting to be able to say something like:
foreach (DictionaryEntry de in vm.ClaimDropdownValueCollection) {
//do something here with de.Key and de.Value
}
So what am I doing wrong in the RAZOR code?... Help!
The issue was with the HTML helpers and how I was posting back. Here's how I resolved it (thanks to my CTO at work!):
Created my view model property that will serve as the resource to populate from as:
Dictionary<int, List<SelectListItem>> CCSetting_ClaimDropdownTypeCollection
Created another dictionary with the SAME KEYS, whose VALUE will be the users selection:
Dictionary<int, int> ClaimDropdownValueCollection
Now on the RAZOR side, I am doing something like this (note the use of HTML.Hidden, and HTML.Dropdown instead of HTML.DropdownFor):
#foreach (var de in Model.CCSetting_ClaimDropdownTypeCollection) {
<div class="formRow">
<div class="formRight searchDrop">
#Html.Hidden("ClaimDropdownValueCollection[" + #de.Key + "]", #de.Key)
#Html.DropDownList("ClaimDropdownValueCollection[" + #de.Value + "]", #de.Value, new { #class = "chzn-select", #data_placeholder="Choose an option...", #style="width: 350px;" })
</div>
<div class="clear"></div>
</div>
}
Sorry about not wording my question in a better way perhaps, I perhaps posted after hours of frustration and ended up doing a bad job at phrasing it. Getting the 'Tumbleweed' badge for this question motivated me to come back and post the solution. OK to close, hope someone someday runs into this!