I want t make a zend update query.
I was looking at zend documentation but I didn't see any example like the one I want.
The question its if may someone could help me with the query.
I want to make the next query:
Update cars set active = 0
Where id in (SELECT idCar FROM UserCars Where idUser=3)
Simplest way to run any complex query. There can be some better ways to do same.
$sql = "Update cars set active = 0
Where id in (SELECT idCar FROM UserCars Where idUser=3)";
$query = $this->getDbTable()->getAdapter()->query($sql, $data);
$query->execute();
Try this too
$data = array { 'active' = '0' };
$where = "id in (SELECT idCar FROM UserCars Where idUser=3)";
$db->update($data, $where);
Perhaps more Zendy way:
$idUser = 3;
$sub_select
= $db->select()
->from('UserCars', array('id'))
->where('idUser = ?', $idUser);
$updated_rows
= $db->update('cars',
array('active' => 0),
"id IN ($sub_select)"
);
Related
I want to achieve doing ORDER BY task_status = 'Open'
but I am unable to get the result.
I did this
$this->db->from('session_tasks');
$this->db->order_by('task_status', 'OPEN', 'DESC');
$query = $this->db->get();
I hope anyone can help.
Try this,
$this->db->query("SELECT * FROM session_tasks
ORDER BY task_status = 'OPEN' DESC,task_status ASC");
Alternatively,
$this->db->query("SELECT * FROM session_tasks
ORDER BY CASE WHEN task_status = 'OPEN' THEN 0 ELSE 1 END ASC,
task_status ASC"); //Ordering starts with Open, then in Ascending order
Here is one more solution using Codeigniter active record that works. Note the usage of double quotes when using string literal.
$this->db->_protect_identifiers = FALSE;
$this->db->from('session_tasks');
$this->db->order_by("task_status = 'OPEN'", 'DESC');
$this->db->order_by('task_status');
$query = $this->db->get();
$this->db->_protect_identifiers = TRUE;
use this code
$this->db->order_by("task_status", "desc");
$query = $this->db->get_where('session_tasks', array('task_status'=>'open'));
to check the documentation click here
You can do this like this:
// set this to false so that _protect_identifiers skips escaping:
$this->db->_protect_identifiers = FALSE;
// your order_by line:
$this -> db -> order_by('FIELD ( products.country_id, 2, 0, 1 )');
// important to set this back to TRUE or ALL of your queries from now on will be non-escaped:
$this->db->_protect_identifiers = TRUE;
Source
Im trying to do a select in my table posts where my categories can be action, adventure, comedy, scify.
First Im trying to find if there is something like "All" in sql to use in where clause:
$where = 'ALL';
$limit = '16';
SELECT * FROM posts WHERE category = '$where' ORDER BY visits ASC LIMIT $limit
But I dont see any information about, and ALL its not definitely working, so Im trying to write all my categories:
$where = 'action OR category = adventure OR category = comedy OR category= scifi';
$limit = '16';
SELECT * FROM posts WHERE category = '$where' ORDER BY visits ASC LIMIT $limit
But its not working, because I need to use '' in my categories name, but how I can do this in my example?
How can I use quotes in my categories here:
$where = 'action OR category = adventure OR category = comedy OR category= scifi';
My full code for this example:
if($type == 'action'){
$limit = '0,3';
$where = "category = 'action'";
}
else if($type == 'adventure'){
$limit = '0,5';
$where = "category = 'adventure'";
}
else if($type == 'comedy'){
$limit = '0,3';
$where = "category = 'comedy'";
}
else if($type == 'scifi'){
$where = "category = 'accao' OR category = 'adventure' OR category = 'comedy' OR category = 'scifi'";
$limit = '16';
}
$posts=
mysql_query("SELECT * FROM posts WHERE '$where' ORDER BY visits ASC LIMIT $limit")
or die(mysql_error());
If you EVERY category, then simply don't define the WHERE. Easy. Also it is not working because you are missing single quotes around every value.
Without defining WHERE you aren't comparing anything, so every row will be returned.
SELECT * FROM posts ORDER BY visits ASC LIMIT $limit
Also, fixed your code if i misunderstood you:
$where = "category = 'action' OR category = 'adventure' OR category = 'comedy' OR category= 'scifi'";
$limit = '16';
$sql = "SELECT * FROM posts WHERE $where ORDER BY visits ASC LIMIT $limit";
First of all, as already mentioned, it doesn't make sense to set a criteria to the query if all possible values are ok.
Secondly, I've added a possible improvement to your code:
<?php
$genres = array(
"action" => "0,3",
"adventure" => "0,5",
"comedy" => "0,3",
"scifi" => "16"
);
$type = "action";
if(!in_array($type, array_keys($genres))) {
//handle invalid input
}
$query = sprintf("SELECT * FROM `posts` WHERE `category` = '%s' LIMIT %s", $type, $genres[$type]);
echo $query;
?>
Last note: do not use mysql_* as they are deprecated. Look into PDO or mysqli_*.
If you stick to mysql_* functions, which you shouldn't, escape user input with e.g. mysql_real_escape_string -- notice the warning.
Good luck!
I'm trying my best here to find a solution for my issue, but with no luck.
I have a SELECT in my PHP to retrieve some products information like their IDs.
mysql_query("SELECT id_item FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
Every time I run this SELECT, I get 5 rows as result. After that I need to run a DELETE to kill those 5 rows using their id_item in my WHERE condition. When I run, manually, something like:
DELETE FROM mytable WHERE id_item IN (1,2,3,4,5);
It works! But my issue is that I don't know how to make an array in PHP to return (1,2,3,4,5) as this kind of array from my SELECT up there, because those 2 other conditions may vary and I have more "status = 0" in my db that can't be killed together. How am I suppose to do so? Please, I appreciate any help.
Unless there is more going on than what is shown, you should never have to select just to determine what to delete. Just form the DELETE query WHERE condition as you would in the SELECT:
DELETE FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'
But to answer how to get the IDs:
$result = mysqli_query($link, "SELECT id_item FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
while($row = mysqli_fetch_assoc($result)) {
$ids[] = $row['id_item'];
}
$ids = implode(',', $ids);
Move to PDO or MySQLi now.
First of all you shouldn't be using mysql_query anymore as the function is deprecated - see php.net
If this is a legacy application and you MUST use mysql_query you'll need to loop through the resource that's returned by mysql_query, which should look something like this
$result = mysql_query("SELECT id_item FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
$idArray = array();
while ($row = mysql_fetch_assoc($result)) {
$idArray[] = $row['id_item'];
}
if(count($idArray) > 0) {
mysql_query("DELETE FROM mytable WHERE id_item IN (" . implode(',' $idArray) . ")");
}
As said before, probably you don't even need a select. But you can do a select, grouping all ids together, and then put it in the delete IN.
$result = mysql_query("SELECT GROUP_CONCAT(DISTINCT id_item) AS ids FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
$ids = mysql_result( $result , 0, 'ids') ; // 1,2,3,4,5
if ($ids != ""){
mysql_query("DELETE FROM mytable WHERE id_item IN (" . $ids . ")");
}
GROUP_CONCAT
I have following PHP script. I want to count and print comments for each article.
The id for each article can be "recalled" by this: <?php echo $listing['Listing']['listing_id'];?> (this return the contentid number)
Now, I have this script:
<?php
$db =& JFactory::getDBO();
$query = "SELECT COUNT(comments) AS totalcount WHERE contentid = ????? ";
$db->setQuery($query);
$count = $db->loadResult();
echo ($count); ?>
I tried to add in WHERE clause this:
"... WHERE contentid = {$listing['Listing']['listing_id']}"
but $count returns "0" zero.
How can I add this variable in the WHERE clause?
Thanks in advance!
In the case of an integer:
$query = "SELECT
COUNT(comments) AS totalcount
WHERE
contentid = " . ((int) $listing['Listing']['listing_id']);
In the case of a string:
$query = "SELECT
COUNT(comments) AS totalcount
WHERE
contentid = " . mysql_real_escape_string($listing['Listing']['listing_id']);
The biggest thing to be weary of is SQL injection. This makes your queries safe. The explicit cast to int will ensure an int value is passed, even if the value is erroneous, at least you wont be open to any attack.
Use sprintf and escape the string.
$query = sprintf("SELECT COUNT(comments) AS totalcount WHERE contentid = '%s'",mysql_real_escape_string($listing['Listing']['listing_id']));
try
$query = "SELECT COUNT(comments) AS totalcount WHERE contentid = '".mysql_real_escape_string($listing['Listing']['listing_id'])."'";
or
$query = "SELECT COUNT(comments) AS totalcount WHERE contentid = ".mysql_real_escape_string($listing['Listing']['listing_id']);
depending on the data type.
Try to select use "where" clause in a mysql statement:
e.g.
Table: X with a ID column which is BINARY data type. Then save in a variable in php
$aid = $row["id"];
How do i use this variable later when I try to select from table
$where = "where `ID` = '$aid'";
$query = "SELECT * FROM X ".$where;
Return 0 row.
Does anyone know why?
Answering my own question.
Just figured out:
$where = "where HEX(ID) = 'bin2hex($aid)'";
$query = "SELECT * FROM X ".$where;
Does anyone know better solution?
Try below :
add BINARY in where clause.
$where = "where BINARY ID = '$aid'";
$query = "SELECT * FROM X ".$where;