update some rows in code igniter - sql

i'm new to codeigniter.
i need some help to update some rows.
here is my model:
public function change()
{
$aa = $this->input->post('id');
$bb = $this->input->post('app');
$query = $this->db->query('select kodeunit from user where email = "hehe#gmail.com"');
foreach ($query->result() as $row)
{
$kode = $row->kodeunit;
}
for($i=0;$i<sizeof($aa);$i++)
{
$data = array(
'approval' => $bb[$i]
);
$this->db->where('id_team', $aa[$i]);
$this->db->where('kodeunit', $kode);
$this->db->update('detail_tim', $data);
}
}
when i tried to update only one row, it worked with this way. but when im trying to update some rows, it doesnt change at all.
please help me to fix this problem thanks

Don't use sizeof() in your for loop, instead use $aa directly if it's an integer or count($aa) if it's an array
for($i=0;$i<count($aa);$i++)
it'll be better if you make it to other variable
$max = count($aa);
for($i=0;$i<$max;$i++)

Related

Magento resource: custom selects with OR in where (select orders by status)

I'm building a custom module and i'm trying get all orders with specific status:
$canceledQuery = Mage::getSingleton('core/resource')->getConnection('core_read')->select()
->from('mage_sales_flat_order', 'entity_id')
->where('status = ?', 'canceled');
This works very well. But now i'm trying use OR in where, without success.
I have been try this:
$whereCanceled = array();
foreach ($_status as $statusCode => $value) {
$whereCanceled[] = sprintf('%s=:%s', 'status', $statusCode);
}
$ordersQuery = Mage::getSingleton('core/resource')->getConnection('core_read')->select()
->from('mage_sales_flat_order', 'entity_id')
->where(implode(' OR ', $whereCanceled));
So, I don't know how use OR right in this case. I found no use for this with OR. Any idea?
instead of implode use join. magento use join itself.
->where(join(' OR ', $orWhere));//$orWhere array of condition
you can see in below function magento use join for OR condition in where clause
public function getSystemConfigByPathsAndTemplateId($paths, $templateId)
{
$orWhere = array();
$pathesCounter = 1;
$bind = array();
foreach ($paths as $path) {
$pathAlias = 'path_' . $pathesCounter;
$orWhere[] = 'path = :' . $pathAlias;
$bind[$pathAlias] = $path;
$pathesCounter++;
}
$bind['template_id'] = $templateId;
$select = $this->_getReadAdapter()->select()
->from($this->getTable('core/config_data'), array('scope', 'scope_id', 'path'))
->where('value LIKE :template_id')
->where(join(' OR ', $orWhere));
return $this->_getReadAdapter()->fetchAll($select, $bind);
}
for more reference open file located at [magento]/app/code/core/Mage/Core/Model/Resource/Email/Template.php
Hope this help you

$data = $query->row(); returns only one row

Im trying to list the results of my sql query (picking up all the movies from a category), but I cannot figure out how to get all the rows instead of only one.
Here's the code :
$this->load->database();
$sql = 'SELECT * FROM movies WHERE category = "'.$movies_category.'";';
$query = $this->db->query($sql);
$data = $query->row();
$this->response($data, 200);
I've tried :
while($row = mysql_fetch_assoc($query)){
$data = $query->row();
}
$this->response($data, 200);
And it doesn't work. Any suggestion ? Thank you !
$this->load->database();
$sql = 'SELECT * FROM movies WHERE category = "'.$movies_category.'";';
$query = $this->db->query($sql);
$data = $query->result();
To traverse the $data array:
foreach($data AS $row)
{
//to retrieve the data from each row.
$col1 = $row->col1;
$col2 = $row->col2;
}
Use result() instead of row(). result() will return an array of objects that are your results. Alternatively, you can useresult_array() which will resturn an array of arrays keyed according to your columns. Please refer to here for a better outline of the result() and row() methods.
Do you have a database configuration file? the load->database() requires it. Where is $movies_category coming from? This will let you iterate over your results.
$this->load->database();
$sql = 'SELECT * FROM movies WHERE category = "'.$movies_category.'";';
$query = $this->db->query($sql);
foreach ($query->result() as $row)
{
echo $row->column;
}
Where column corresponds with one of the values in the movies table.
I'm surprised nobody has mentioned the potential hazards of using variables (possibly user input) in your SQL. You should seriously consider using query bindings or the active record features of CodeIgniter to build safer queries.
Consider the following solution to your problem:
$this->load->database();
$sql = 'SELECT * FROM movies WHERE category = ?';
$query = $this->db->query($sql, array($movies_category));
// $data = $query->result(); // returns result as an array of objects
$data = $query->result_array(); // returns result as array
$this->response($data, 200);
I'm assuming this is for some sort of API? If so, consider using the result_array() method as it will probably be better suited for your needed output, and also really easy to convert into JSON:
$json_data = json_encode($data);
Hope that helps,
Cheers.
For your question row() return only one value its good for checking in ID and if you want get all the rows use result_array() or simple result()
You can try this code....
Model:
function get_movies($movies_category){
$this->db->where("category",$movies_category);
$query = $this->db->get("movies");
return $query->result_array();
}
Controller:
$this->data['movies'] = $this->'name of model'->get_movies('here is the movie categories');
View:
foreach($movies as $m){
print_r($m);
}
exit();
Note you can directly add the code in function in model to controller add this in your controller if you want directly...
$this->data['movies] = $this->db->get('movies')->result_array();

How to output JSON from recordset in Dreamweaver with minimal manual code? [duplicate]

I have a basic MySQL database table People with 3 columns (ID, Name, Distance)
I am trying to output this with PHP as a JSON so my web app can pick it up. I tried using the solution from another answer:
$sth = mysql_query($con,"SELECT * FROM People");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
However I am just returning a blank array of [].
Update: Changed to mysqli and added dumps:
$sth = mysqli_query("SELECT * FROM Events",$con);
$rows = array();
var_dump($sth);
while($r = mysqli_fetch_assoc($sth)) {
var_dump($rows);
$rows[] = $r;
}
print json_encode($rows);
Returns:
NULL []
Swap your query and connection in the mysql_query-statement:
$sth = mysql_query("SELECT * FROM People", $con);
Besides that, the mysql-library is deprecated. If you're writing new code consider using mysqli_ or PDO.
Why no mysql_connect ?
var_dump($sth); // check the return of mysql_query()
var_dump($rows); // check the array of mysql_fetch_assoc result
I would check if your query is returning any rows first.
<?php
$rows = array();
array_push($rows, array("name" => "John"));
array_push($rows, array("name" => "Jack"));
array_push($rows, array("name" => "Peter"));
print json_encode($rows);
?>
Produces this output.
[{"name":"John"},{"name":"Jack"},{"name":"Peter"}]
Solved using a combination of answer to get:
$sth = mysqli_query($con,"SELECT * FROM Events");
$datarray = array();
while($row = mysqli_fetch_assoc($sth)) {
$datarray[] = $row;
}
print_r(json_encode($datarray));

sql update codeigniter

I am using codeIgniter..
I want to update a table column is_close when id=$ticket_id of my table= tbl_tickets.
I am doing this :-
$data=array(
'is_close'=>1
);
$this->db->where('id',$title_id);
$this->db->update('tbl_tickets',$data);
and I have also done this :-
$sql = "UPDATE tbl_tickets SET is_close={1} WHERE id='$title_id'";
$this->db->query($sql);
both are not working,i.e., my table is not updating the value to 1 and also no error is being shown in the broswer. :(
Edited: Included my model part :
function setClosePost($title_id){
$sql = "UPDATE tbl_tickets SET is_close=0 WHERE id='$title_id'";
$this->db->query($sql);
// $data=array(
// 'is_close'=>1
// );
// $this->db->where('id',$title_id);
// $this->db->update('tbl_tickets',$data);
}
My controller :-
function closePost(){
$this->load->model('helpdesk_model');
$this->helpdesk_model->setClosePost($this->input->post('title_id'));
}
first of all use a get method to check if ticket_id is exist or not.
another thing is always use return in your functions in models so you can check them by if(function_name){...}else{...}
then if your get method returned data correctly try
Model Method
public function set_closed($ticket_id){
$this->db->set(array(
'is_close'=>1
)); // pass fields in array
$this->db->where('id',$ticket_id);
$this->db->update('tbl_tickets'); // table name
return true;
}
then check that in your controller
if($this->Ticket_model->set_closed($ticket_id) == true){
echo 'ticket set to closed correctly';
}else{
echo 'there is some error on updating database'.$this->db->error(); // to checkout db error .
}
First, check $title_id before passing:
var_dump($title_id);
Then, try do "select a row with this id" before updating and after.
$query = $this->db->get_where('tbl_tickets', array('id' => $id));
foreach ($query->result() as $row)
{
var_dump($row->is_close);
}
$data=array(
'is_close'=>1
);
$this->db->where('id',$title_id);
$this->db->update('tbl_tickets',$data);
$query = $this->db->get_where('tbl_tickets', array('id' => $id));
foreach ($query->result() as $row)
{
var_dump($row->is_close);
}
Then, give your table structure.
Just try like this
$sql = "UPDATE tbl_tickets SET is_close='1' WHERE id=".$title_id;
$this->db->query($sql);
just try like this
**function edit($close,$id) {
$sql = "UPDATE tbl_tickets SET is_close= ? WHERE id = ? ";
$this->db->query($sql, array($close,$id));
}**
To handle this type of errors, i mean if reflection is not happen in database, then use below steps to resolve this type of error.
1) use $this->db->last_query() function to print query, using this we can make sure our variable have correct value (should not null or undefined), using that we can make sure also SQL query is valid or not.
2) If SQL query is valid then open phpmyadmin & fire same query into phpmyadmin, it will return error if query columns or table names are invalid.
Use this way, its best way to cross check our SQL queries issues.
I hope it will work.
Thanks
You are trying to update integer(INT) type value, just cross check with your column datatype if that is varchar then you have to put value in a single or double quote.
Like this
$data=array('is_close'=> '1');

Yii: adding custom fields

Is there a simple way of adding custom fields to a model? Say I have a table "user" with 3 fields: id, name and surname. I want this:
$user = User::model()->findByPk(1);
$echo $user->fullName; // echoes name and surname
Please note: I want this custom field to be added via sql, smth like
$c = new CDbCriteria();
$c->select = 'CONCAT("user".name, "user".surname) as fullName';
$user = User::model()->find($c);
Problem is that fullName property is not set.
UPD:
here is the code for a little bit trickier problem -- custom field from another table. This is how it's done:
$model = Application::model();
$model->getMetaData()->columns = array_merge($model->getMetaData()->columns, array('fullName' => 'CONCAT("u".name, "u".surname)'));
$c = new CDbCriteria();
$c->select = 'CONCAT("u".name, "u".surname) as fullName';
$c->join = ' left join "user" "u" on "t".responsible_manager_id = "u".id';
$model->getDbCriteria()->mergeWith($c);
foreach ($model->findAll() as $o) {
echo '<pre>';
print_r($o->fullName);
echo '</pre>';
}
You can add a function to the User class:
public function getFullName() { return $this->name.' '.$this->surname; }
This will return the full name as if it were an attribute from the database. This is much easier than adding a calculated column to the SQL.
In model
public function getMetaData(){
$data = parent::getMetaData();
$data->columns['fullName'] = array('name' => 'fullName');
return $data;
}
Thus not recommended

Categories