Joomla - insert multiple rows using single query - mysql

At this specific moment, I want to know how to insert two records into DB. Both are almost the same, except only one single column value changes.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$columns = array('col1','col2', 'col3', 'col4', 'col5');
$values = array(
$db->quote(A),
$db->quote(x1),
$db->quote(x2),
$db->quote(x3),
$db->quote(x4)
);
$values = array(
$db->quote(B),
$db->quote(x1),
$db->quote(x2),
$db->quote(x3),
$db->quote(x4)
);
...
As you can see, only first value changes. Is there some elegant way to do this?

You code seems to be incomplete since it does not assign your values to the query.
Try this instead. It shows how to add the content of $foo to the column myColumn in the table #__mytable.
$query->insert($db->quoteName('#__mytable'))
->columns('myColumn');
->values(implode(',', array(
$db->quote($foo)
)));
$query->execute();
For multiple values this would help:
foreach($myValues as $myValue) {
$query->values(implode(',', array(
$db->quote($myValue),
)));
}
While there is just one value in my example, it is ready to add multiple columns if needed. Just extend the columns() and values() methods.

Related

PDO prepared statements binding

i have a data array e.g. this:
$data = ['ver_weather' => $post["weathercondition"],
'ver_flash' => $post["flashintense"],
'ver_earth' => $post["earthrumble"]]
these data i use in my sql like this:
$sql = "INSERT INTO `database`.`table` (`weather`, `flash`, `earth`)
VALUES (:ver_weather, :ver_flash, :ver_eart)";
$pdo->prepare($sql)->execute($data);
The result is something like:
INSERT INTO `database`.`table` (`weather`, 'flash', `earth')
VALUES ('1'weather, '1'flash, '1'earth)
So is pdo replacing parts of my keys with the value ?
what is wrong there ?
thanks for helping me out.
edit: Execute does work with named bindings so you could just edit your $data array like this:
$data = [':ver_weather' => $post["weathercondition"],
':ver_flash' => $post["flashintense"],
':ver_earth' => $post["earthrumble"]]
Note the : at the beginning of each key
Original answer below...
I think the issue is that you're trying to bind by name and I don't think PDOStatement supports named bindings. I'd recommend trying the following:
$data = [$post["weathercondition"], $post["flashintense"], $post["earthrumble"]];
$sql = "INSERT INTO `database`.`table` (`weather`, `flash`, `earth`)
VALUES (?, ?, ?)";
$pdo->prepare($sql)->execute($data);

Yii2 Matching all values in IN clause

Im trying to get a query which matches all values within an IN clause. This is what I have right now in UsersSearch.php model:
$categoryIdsMatching = UsersCategoriesAssn::find()
->select('userID')
->distinct(true)
->joinWith('userCategory')
->andWhere(['IN', 'usersCategories.id', $this->catNameSearch])
->column();
$query->andWhere(['userID'=>$categoryIdsMatching]);
But it gets records matching at least one of the values... How can I set that andWhere clause to match all values instead of some of them?
This could be something similiar to:
$categoryIdsMatching = UsersCategoriesAssn::find()
->select('userID')
->distinct(true)
->joinWith('userCategory')
->andWhere(['IN', 'usersCategories.id', $this->catNameSearch])
->groupBy('userTable.userID')
->having('COUNT(userTable.userID) ='.count($this->catNameSearch));
There is propably no other way to filter IN operator to match all values in MySQL.
Yii2 where in clause
Model :
//GET MULTIPLE AREA
public function getAreaSelected() {
//GET SAVE COMMA SEPERARED VALUE CONVERT IN TO ARRAY
$areaArray = explode(",", $this->attributes['selected_area']);
$query = AreaMaster::find()->where(['IN', 'id', $areaArray])->all();
return $query; //$this->hasMany(AreaMaster::className(), ['IN', 'id', $pks]);
}
VIEW FILE :
<?php
print '<pre>';
print_r($model->areaSelected);
exit;
?>

Novice: How to do update with id in cakephp2 mysql?

I'm new to cakephp2 and mysql and I want to create a mysql query to update the data with a id that has been passed in.I'm a very slow learner so I would want some help.
$this->User->updateAll(
array(
'User.checked_count' => '`User`.`checked_count` + 1',
'User.modified' => "'" . date('Y-m-d H:i:s') . "'"
),
array(
'User.username' => $username,
)
);
PS. How to get the results from the query above and use foreach loop? It doesn't work, so Im having a little trouble with it .
In cakePhp 2.x you can do it like that:
1) Below is simple update using save() function, where you pass id as reference and cake automatically updates the table when id is set else will insert the data in new row:
$this->User->id = $Id;
$this->User->save($this->request->data);
2) If you want one or more records in a single call to get updated use updateAll() function:
$this->User->updateAll(
array('User.checked_count' => $count),
array('User.id ' => $userId)
);
Try this code
$this->User->id = $passedId;
$this->User->save($this->data);
In above code If user_id is present then It update user data other wise it save userData.

Codeigniter - How to get records from database where one fields value is more than another?

In my database I have two columns named 'amount_raised' and 'funding_goal'.
I would like to get all records from my database where the 'amount_raised' is equal to or more than the 'funding_goal'.
I am using Codeigniters active record. This is what I have so far:
function get_recently_successful($limit, $offset){
$data = '';
$this->db->order_by('date','desc');
$this->db->where('published', '1');
$this->db->where('amount_raised >=', 'funding_goal');
$query = $this->db->limit($limit, $offset)->get('projects');
foreach ($query->result() as $row) {
$data[] = array(
'id' => $row->id,
'date' => $row->date,
'project_title' => $row->project_title,
);
}
return $data;
}
The code above just returns all values in the database. Not how I specified it with where. How can I make it work??
Try this instead.
$this->db->where('amount_raised >= funding_goal');
Right now you send the value 'funding_goal' through the query, thus making it:
WHERE amount_raised >= 'funding_goal'
You want it compare with a column and not a string:
WHERE amount_raised >= funding_goal
You can always troubleshoot your query by inserting:
echo $this->db->last_query();
After the $query = row.
If you are using multiple condition in array, you can try the below as well:
$this->db->where(array('status' => 'Active', 'category' => $catId));
You can use another condition as well like this:
$this->db->where('amount_raised >= funding_goal');
You can use the last_query() to see the sql query as well to understand it.

Filtering theme_table in Drupal

I just created a data table based on a query and displayed it successfully using theme_table().
Now, I'd like to add some filters to the table but have no idea how to proceed.
Is there a built-in feature that allow me to do this easily, or should I manually add a form and update the query/redisplay the results each time the user selects something?
Thanks for your help!
I think you want to use pager_query and tablesort_sql: it's especially made for creating tables of data with pagination and sorting capabilities (and themes usually theme such tables nicely out of the box).
Example:
<?php
// The regular query without sorting or pagination parameters
$sql = 'SELECT cid, first_name, last_name, company, city FROM {clients}';
// Number of rows per page
$limit = 20;
// List of table columns ("field" is the matching database column from the sql query)
$header = array(
array('data' => t('Name'), 'field' => 'last_name', 'sort' => 'asc'),
array('data' => t('Company'), 'field' => 'company'),
array('data' => t('City'), 'field' => 'city')
);
// Calculates how to modify the SQL query according to the current pagination and sorting settings
// Then performs the database query
$tablesort = tablesort_sql($header);
$result = pager_query($sql . $tablesort, $limit);
$rows = array();
while ($client = db_fetch_object($result)) {
$rows[] = array(l($client->last_name.', '.$client->first_name, 'client/'.$client->cid), $client->company, $client->city);
}
// A message in case no results were found
if (!$rows) {
$rows[] = array(array('data' => t('No client accounts created yet.'), 'colspan' => 3));
}
// Then you can pass the data to the theme functions
$output .= theme('table', $header, $rows);
$output .= theme('pager', NULL, $limit, 0);
// And return the HTML output
print $output;
?>
(I added comments, but the original version of the example comes from this page)
Alternatively, maybe you don't need to make a module at all if you're just trying to make a page that displays a list of data, you may prefer using the Views module.