I am using Zend Framework. I have tree tables. Users and Groups and one table linking them.
I want to increment a field from users of a given group. To increment one User I do:
$table = 'users';
$update = array(
'ACLVersion' => new Zend_Db_Expr('ACLVersion + 1')
);
$where[] = $db->quoteInto('id = ?', $user);
$db->update($table, $update, $where);
I tried to use multiple wheres.
I have no clue how to join the tables in a where with Zend.
To use a JOIN with Zend_Db_Table, you have to disable the integrity check.
See example #27 in the ZF Reference Guide for Zend_Db_Table:
$table = new Bugs();
// retrieve with from part set, important when joining
$select = $table->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
$select->setIntegrityCheck(false)
->where('bug_status = ?', 'NEW')
->join('accounts', 'accounts.account_name = bugs.reported_by')
->where('accounts.account_name = ?', 'Bob');
$rows = $table->fetchAll($select);
Note that disabling the integrity check will also disable some of the automagic of the resulting recordset:
The resulting row or rowset will be
returned as a 'locked' row (meaning
the save(), delete() and any
field-setting methods will throw an
exception).
Load $num with a array of id's from a given group
The following code will do the job
$table = 'users';
$update = array(
'ACLVersion' => new Zend_Db_Expr('ACLVersion + 1')
);
$where = $db->quoteInto('id IN (?)', $num);
$db->update($table, $update, $where);
Related
Just got one doubt while performing insert operation. I want to keep records to be unique. So while inserting record currently I am executing delete() function to delete same record if exists and then using insert() function. But just thought that if I check that record is exists and insert only if that record not found. So I can avoid delete() operation. So which is better option?
This is my code.
public function insertPostLike($postId = null, $userId = null) {
//This is to avoid duplicate entry for same user.
$this->_db->delete($this->_name, array(
'post_id = ?' => $postId,
'user_id = ?' => $userId));
$result = '';
$arrData = array(
'post_id' => $postId,
'user_id' => $userId,
'liked_date' => Zend_Date::now()->toString('yyyy:MM:dd HH:mm:ss')
);
if (!is_null($postId)) {
$result = $this->insert($arrData);
}
return $result;
}
I am using zend framework.
In MySql using InnoDB, in the context of one transaction, are the inserts supposed to be visible by the following selects?
Example :
$connect = new PDO('mysql:host='. getConfig()->get('DB_HOST').';dbname='. getConfig()- >get('DB_NAME'), getConfig()->get('DB_USER'), getConfig()->get('DB_PASSWORD'), array(PDO::ATTR_PERSISTENT => true));
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connect->beginTransaction();
$sql = 'INSERT INTO t_table (label) VALUES ("test") WHERE id = "1"';
$query = $connect->prepare($sql);
$query ->execute();
$sql2='SELECT * FROM t_table';
$query2=$connect->prepare($sql2);
$query2->execute();
$result = $query2->fetch();
$connect->commit();
In this case, should 'test' be in $result? if not, how could I make it do so?
Precision: the column 'label' is not the primary key but has an index.
Yes, 'test' must be in $result.All operations in a single transaction are visible to each other.
I have two query:
$select1 = $this->select()
->from(array('o'=>'table1'), array('*', 'o.field2 AS shared'))
->where('field4= ?', $input);
$select2 = $this->select()
->from(array('i'=>'table2'), array('*', 'ch.field1 AS shared'))
->where('ch.field5= ?', $input);
Both query works successfully. However, it does not work with the following union function even with shared parameter name. How come?
//Merge both query
$selectboth = $this->select()
->union(array($select1, $select2))
->order('shared');
$obj = $this->dbo->fetchRow($selectboth);
I am suspecting my fetchRow is the one causing this error in fetching.
if you have number of column same in both sql so you can ran into this issue:
http://framework.zend.com/issues/browse/ZF-4338
for example:
$select_q1 = $db->select()->...;
$select_q2 = $db->select()->...;
$main_select = $db->select()->union( array( '('.$select_q1 .')', '('.$select_q2 .')' ) );
I'm having a problem with running this function. When it runs, it does exactly what I want, except that within my like_requests table the request_id is not the mysql query result linked to the variable $select but Resource Id #22. I thought that resource id's appear when you are trying to echo out a result, but I'm not using echo. What's wrong with the code?
function update_likes($band_requested, $new_likes, $session_user_id) {
$select = mysql_query("SELECT `primary_id` FROM `requests` WHERE
`user_requester_id` = '$session_user_id' AND `person_requested` =
'$band_requested'");
$sql_2 = "INSERT INTO `like_requests` (user_id, request_id) VALUES
('$session_user_id', '$select')";
mysql_query($sql_2);
}
$band_requested = 'rally done';
$new_likes = 239;
$the_session_user_id = 3;
update_likes($band_requested, $new_likes, $the_session_user_id);
UPDATE WITH CORRECTED ANSWER
Here is the code corrected with help from David.
function update_likes($band_requested, $new_likes, $session_user_id)
{
$select = mysql_query("SELECT `primary_id` FROM `requests` WHERE `user_requester_id` =
'$session_user_id' AND `person_requested` = '$band_requested'");
$row = mysql_fetch_row($select);
$request_id = $row[0];
$sql_2 = "INSERT INTO `like_requests` (user_id, request_id) VALUES ('$session_user_id',
'$request_id')";
mysql_query($sql_2);
}
mysql_query returns a resource (http://php.net/manual/en/function.mysql-query.php) not just a scalar value. You'd need to use a function like mysql_fetch_row() to get the, presumably, one row you want, assign that row to a variable $row, then retrieve the primary_id with array syntax like $row['primary_id']. By the way, apparently mysql_query is being eased out and we should use the MySQLi API with the mysqli_query() method.
I am having an issue with inserting an array of information into a mysql database. Basically I built a sortable gallery similar to Facebook's photo albums that can be arranged by moving the div to a new spot with jquery's sortable function.
I am using Ajax to call a php file which will inser the new order of the div's into the DB. The information is being passed correctly, it is just not being inserted correctly.
The error I am receiving is:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Array' at line 1
The Php code is:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) {
$sql[] = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";
mysql_query($sql) or die(mysql_error());
}
}
If I remove the mysql_query function and just do a print_r, I get:
Array
(
[0] => UPDATE table SET order = '0' WHERE id = '2'
[1] => UPDATE table SET order = '1' WHERE id = '4'
[2] => UPDATE table SET order = '2' WHERE id = '3'
[3] => UPDATE table SET order = '3' WHERE id = '1'
[4] => UPDATE table SET order = '4' WHERE id = '5'
[5] => UPDATE table SET order = '5' WHERE id = '6'
)
This is the first time I have tried to do something like this. Any help would be great.
Thank you in advance for the help!
In mysql_query($sql) $sql is an array, therefore it's value is simply Array. When you assign $sql[] = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'"; simply make this line $sql = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";. That should solve your problem.
EDIT:
You can leave the [] and simply remove the mysql_query from where it is. After your foreach list item, add this:
foreach($sql as $query) {
mysql_query($query);
}
Sounds like there is some confusion about what the [] operator does. You use [] when you want to append an element to the end of an existing array.
For example:
$sql = array();
$sql[] = 'UPDATE table SET order = "0" WHERE id = "2"';
mysql_query($sql); // this will produce the error you are seeing
Versus:
$sql = 'UPDATE table SET order = "0" WHERE id = "2"';
mysql_query($sql); // this will work
You should rewrite your code as such:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) {
$sql = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";
mysql_query($sql) or die(mysql_error());
}
}
That will do what you are intending. However, this is still not a good idea, since you are passing untrusted $_GET data directly to the database. I could, for example, call your script with a string like:
http://yoursite.com/yourscript.php?listItem=1'%3B%20DROP%20TABLE%20yourtable%3B
Since the value of listItem is going directly to the database -- and the $item >= 1 check is insufficient, since PHP will evaluate a string as an integer if it begins with numeric data -- all I have to do is add a single quote to terminate the previous query, and I am then free to inject whatever SQL command I'd like; this is a basic SQL injection attack. Whenever you write database-touching code, you should cleanse any input that might be going to the database. A final version of your code might look like:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) { // this check may or may not be needed depending on its purpose
$sql = 'UPDATE table SET order = "' . mysql_real_escape_string($position) . '" WHERE id = "' . mysql_real_escape_string($item) . '"';
mysql_query($sql) or die(mysql_error());
}
}
There are other ways to cleanse input data as well, that is just one of them. Hope that helps.