I am trying to move data from one table to another in my model. In the first two lines I am getting all of the rows in my 'cart' table that match the username. I am now trying to iterate through all of these and match the product ID to the product ID in my 'product' table. I am then trying to format the data to fit my new table called 'sold'. However I am getting an error. I think the syntax of $q->id, $q->product_name etc is wrong. I know you can usually use that in the view but it does not work in the model. Do you know what the correct syntax would be to do this?
function checkout($username){
$this->db->where('username', $username);
$query = $this->db->get('cart');
//$data = array();
foreach ($query as $q){
$product = $this->db->get_where('product', array('id' => $q->id));
$arr['product_id'] = $product->id;
$arr['product_brand'] = $product->item_brand;
$arr['product_name'] = $product->item_name;
$arr['product_image'] = $product->item_image_url;
$arr['product_price'] = $product->item_price;
$arr['product_size'] = $product->item_size;
$arr['name_of_seller'] = $product->name_of_lister;
$arr['name_of_buyer'] = $this->session->userdata('username');
$this->db->insert('sold', $arr);
}
//Deletes the items out of the cart
// $this->db->delete('cart');
}
This is the error message I am getting
You have to use result() to get the data in the the $query variable.
$query = $this->db->get('cart')->result();
In the same way, also change the second query.
$product = $this->db->get_where('product', array('id' => $q->id))->result();
See if this helps you.
function checkout($username){
$this->db->where('username', $username);
$query = $this->db->get('cart');
if ($query->num_rows()>0) {
$qdata = $query->result_array();
foreach ($qdata as $key => $qdvalue) {
$this->db->where('id', $qdvalue['id']);
$product = $this->db->get('product');
$pdata = $product->row_array()
$inarray = array(
'product_id' => $pdata['id'],
'product_brand' => $pdata['item_brand'],
'product_name' => $pdata['item_name'],
'product_image' => $pdata['item_image_url'],
'product_price' => $pdata['item_price'],
'product_size' => $pdata['item_size'],
'name_of_seller' => $pdata['name_of_lister'],
'name_of_buyer' => $this->session->userdata('username')
);
$this->db->insert('sold', $inarray);
}//end of foreach
}//end of if query
}//end of checkout function
I rewrite your function if all the column values right then It will work.
And I will suggest you to use transactions for this type of db events.
Related
I'm trying to select rows from my DB table based on information I get from the other rows(previous query). The trouble I'm having is converting the $query->result_array(); in the controller to use it in the model again and subsequently the view.
I've tried to do a foreach loop and returning the $query->result_array(); from the model, this turned out to be problematic as it didn't fit the different stages I have on my website(I have several stages of content).
controller.php
public function firststage() {
$this->load->model('Model');
$get_stage = $_GET["stg"];
$get_results = $this->Model->get_stage_id($get_stage);
foreach ($get_results as $results) {
$id = $results["id"];
}
$data['result'] = $this->Model->stage_results($get_stage, $id);
$this->load->view('stage_view', $data);
}
model.php
public function get_stage_id($get_stage) {
$this->db->where('stage_parent', $get_stage);
$query = $this->db->get('stages');
return $query->result_array();
}
public function stage_results($get_stage, $id) {
$this->db->where('stage_id', $get_stage);
$this->db->where('stage_id', $id);
$query = $this->db->get('stage_contents');
foreach ($query->result_array() as $row) {
$rows[] = array(
'id' => $row["id"],
'name' => $row["name"]
);
}
return $rows;
}
Expected the output selection to be based on the first query result, instead I get the Undefined variable: rows when I run all of it. I don't think my view is relevant to this question, but please let me know if you think otherwise!
you get the error
Undefined variable: $rows
because your query doesn't return any result, therefore $rows is not defined
you can resolve this checking if there are rows returned:
if($query->num_rows()){
foreach ($query->result_array() as $row) {
$rows[] = array(
'id' => $row["ID"],
'name' => $row["name"]
);
}
}else {$rows='no records found';}
print_r($rows);die;
this prints either the array (if there are results), or 'no records'
or simply do:
$rows = array();
foreach ($query->result_array() as $row) {
$rows[] = array(
'id' => $row["ID"],
'name' => $row["name"]
);
}
then you get an empty array if there are no results
I wrote an api call in my Symfony project that returns all fields from my entity with the query defined below..
Now, I need to define just three fields like 'id', 'name', 'value' and to pull values from that fields that are currently stored in a database.
public function getChartData() {
$myResults = $this->getMyRepository()
->createQueryBuilder('s')
->groupBy('s.totalCollected')
->orderBy('s.id', 'ASC')
->getQuery()
->getArrayResult();
$result = array("data" => array());
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult] = $label["id"];
$result['data'][$schoolResult] = $label["name"];
$result['data'][$schoolResult] = $label["totalCollected"];
}
}
The problem is it return just totalCollected field.
One of errors are Call to a member function getId() on array and so on, and I can't figure out a way to pull data from db...
I cannot see in your code where $schoolResult come from but lets guess it string key of some sort.
Notice you trying to set 3 value on the same key so only the last one remains.
Look at:
$a = array();
$a["key"] = 4;
$a["key"] = 6;
It is simple to see that $a["key"] will contains 6 and not 4 or both.
When you do:
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult] = $label["id"];
$result['data'][$schoolResult] = $label["name"];
$result['data'][$schoolResult] = $label["totalCollected"];
}
You override the data in $result['data'][$schoolResult] therefor only try totalCollected is there as the last one to set.
In order to fix that you can use:
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult]["id] = $label["id"];
$result['data'][$schoolResult]["name"] = $label["name"];
$result['data'][$schoolResult]["totalCollected"] = $label["totalCollected"];
}
Hope that helps!
For some reason this isn't working. The error I get is "Undefined index: cu_id" for the line
$cu_id = $rows['cu_id'];
I think I'm just totally using the querybuilder wrong with the foreach loop. Any help with the proper syntax for this? Thanks!
$query = new Query;
$query->select('cu_id')->from('cu_emails')->where(['creator_id' => $user_id, 'email' => $email]);
foreach ($query as $rows) {
$cu_id = $rows['cu_id'];
echo"CU ID: $cu_id<br /><br />";
}
Also I'm on the Yii 2 framework in case anyone missed that.
You should add all() or one() for getting the rows
$query = new Query;
$myModels= $query->select('cu_id')
->from('cu_emails')
->where(['creator_id' => $user_id, 'email' => $email])
->all();
and obtained the models in $myModels
foreach ($myModels as $rows) {
$cu_id = $rows['cu_id'];
echo"CU ID: $cu_id<br /><br />";
}
You query not run.
$query->all()
and then foreach records
or
$query->one()
and get data from one record
$query = new Query;
$query->select('cu_id')->from('cu_emails')->where(['creator_id' => $user_id, 'email' => $email])
$results = $query->all();
foreach ($results as $rows) {
$cu_id = $rows['cu_id'];
echo"CU ID: $cu_id<br /><br />";
}
I try insert some articles from a PHP script but i don´t get it. I need to know what fields are required and how I can create the query to do it.
Now, I´m write the next code:
foreach($RSS_DOC->channel->item as $RSSitem){
$alias = md5($RSSitem->title);
$fetch_date = date("Y-m-j G:i:s"); //NOTE: we don't use a DB SQL function so its database independent
$item_title = $RSSitem->title;
$item_description = $RSSitem->description;
$item_date = date("Y-m-j G:i:s", strtotime($RSSitem->pubDate));
$item_url = $RSSitem->link;
// Does record already exist? Only insert if new item...
$item_exists_sql = "SELECT alias FROM jos_content where alias = ".$alias;
$item_exists = mysqli_query($enlace,$item_exists_sql);
if(mysqli_num_rows($item_exists)<1){
$mensaje = "<p>".$item_description."</p>Publicado: ".$item_date."<br/><a href='".$item_url."'>Ver noticia original</a>";
$item_insert_sql = "INSERT INTO jos_content(title, alias, introtext, state, catid, created, created_by, access,featured) VALUES ('" .$item_title. "', '" . $alias. "', '" . $mensaje. "',1, 10,'".$fetch_date."',448,1,1)";
$insert_item = mysqli_query($enlace,$item_insert_sql);
}
}
First order of business is to create the article data object. I use a method to scrub out an existing id or asset_id references in case I'm migrating article data from one instance to another. This could be replaced by your logic to build out the article data object as well. Just be sure to use an associative array:
function processArticleData($obj) {
$data = array();
foreach ($obj as $key => $value) {
$data[$key] = $value;
}
$data['id'] = 0;
unset($data['asset_id']);
return $data;
}
Next you load the JTable content class, bind the data and save. Joomla does all the rest:
function addArticle($obj) {
// Initialise variables;
$data = processModuleData($obj);
$table = &JTable::getInstance('content');
// Bind the data.
if (!$table->bind($data))
{
echo "<h1>Error Binding Article Data</h1>";
return false;
}
// Check the data.
if (!$table->check())
{
echo "<h1>Error Checking Article Data</h1>";
return false;
}
// Store the data.
if (!$table->store())
{
echo "<h1>Error Storing Article Data</h1>";
return false;
}
return $table->get('id');
}
The benefits of this approach is it removes any "guessing" about required fields or potential errors, as if there is an issue with the data Joomla will throw an exception or error stating what the issue was. If you wanted/needed to get real fancy, you could even load the JForm object for content, bind your data to it and then validate before binding to the JTable object.
Creating the data object has only two requirements. The first is to use an associative array and the second all key names match columns in the #__content table. An example data object would look like this:
$data = array(
'title' => $title,
'alias' => $alias,
'introtext' => $introtext,
'fulltext' => $fulltext,
'catid' => $catid,
'images' => '',
'urls' => '',
'attribs' => '',
'metakey' => '',
'metadesc' => '',
'metadata' => '',
'language' => '',
'xreference' => '',
'created' => JFactory::getDate()->toSql(),
'created_by' => JFactory::getUser()->id,
'publish_up' => JFactory::getDate()->toSql(),
'publish_down' => JFactory::getDbo()->getNullDate(),
'state' => 1
);
I use some more Joomla helper functions to make my job easier, but this should provide a good starting point for you to get the ball rolling.
* EDIT *
Noticed a typo which I corrected. Not sure if you copy/pasted but switch the below line for the array declaration above and test again:
$data = processModuleData($obj);
This script should do it....assuming it exists in the root of your site:
if (!defined('_JEXEC')) {
define( '_JEXEC', 1 );
define ('JPATH_BASE', 'c:\\wamp\\www\\mysiteroot');
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
$mainframe = JFactory::getApplication('site');
}
function getContentTable($type = 'Content', $prefix = 'JTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
function addArticle($title, $alias)
{
$table = getContentTable();
$table->title = $title;
$table->alias = $alias;
$table->catid = 2;
$table->state = 1;
// and so on!
// then save it
$table->store();
}
$result = addArticle("foo", "bar");
I would like to insert some records into my DB table and using the insertgetid feature, return those results to my blade view.
Controller
$grids[] = array();
foreach($c as $key) {
$grids[] = DB::table('infile')->insertGetId(
array( 'href' => $key,
'creator_id' => $id,
'random' => substr(str_shuffle("aBcEeFgHiJkLmNoPqRstUvWxYz0123456789"),0, 9))
);
}
$name[] = array();
foreach($grids as $id){
$name = DB::table('infile')->where('id', '=', $id)->first();
}
return View::make('Home')->withName($name);
Blade View
#if(isset($name) && $name != '')
{{dd($name)}}
#endif
I'm getting this error
ErrorException
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
You can use whereIn to make exact query. between should work, but it's error prone, since there might be another row inserted in the meantime:
$ids = [];
foreach (..)
{
$ids[] = DB::table('infile')->insertGetId(...);
}
$data = DB::table('infile')->whereIn('id', $ids)->get();
I ended up using a different approach
I found the max id before I performed the insert and then found the max id after the insert and then used a wherebetween to grab the data.
$max = DB::table('infile')->max('id');
foreach($c as $key) {
DB::table('infile')->insertGetId(
array(
'href' => $key,
'creator_id' => $id,
'random' => substr(str_shuffle("aBcEeFgHiJkLmNoPqRstUvWxYz0123456789"),0, 9)
)
);
}
$max2 = DB::table('infile')->max('id');
$data = DB::table('infile')->whereBetween('id', array($max, $max2))->get();
$id = DB::table('user')->insertGetId(['name'=>"test"]);