I want to update members_roosevelt table ACCOUNT column starting with 3000+ value I also want to update ACCOUNT column on loan_roosevelt table that is related to my member_roosevelt. What's wrong with my query? Thank you!
$query1 = "SELECT ACCOUNT
FROM
`members_roosevelt`";
$result_q1 = $link->query($query1) or die($link->error);
while ($obj = $result_q1->fetch_object()) {
$members[] = $obj->ACCOUNT;
}
$ids = implode(',', $members);
$sql = "UPDATE `members_roosevelt` as `memb`
JOIN `loan_roosevelt` as `loan`
ON `memb`.`ACCOUNT` = `loan`.`ACCOUNT`
SET
(`memb`.`ACCOUNT`,
`loan`.`ACCOUNT`) = CASE ACCOUNT";
foreach ($members as $id => $ordinal) {
$sql .= sprintf("WHEN %d THEN %d ", $ordinal, (3000+$id));
}
$sql .= "END WHERE memb.ACCOUNT IN ($ids)";
$link->query($sql) or die($link->error);
SET (`memb`.`ACCOUNT`, `loan`.`ACCOUNT`) = CASE ACCOUNT...
This is simply not part of SQL syntax. You can't set two columns at a time like this. The left side of an assignment operator must be one column.
A better solution is to use a session variable.
SET #acct = 3000;
UPDATE members_roosevelt as memb
JOIN loan_roosevelt as loan
ON memb.ACCOUNT = loan.ACCOUNT
SET memb.ACCOUNT = (#acct:=#acct+1),
loan.ACCOUNT = (#acct);
This way you don't have to run the SELECT query at all, and you don't have to create a huge UPDATE statement with potentially thousands of WHEN clauses.
Demo: SQLFiddle
Related
I have a get parameter and I want to select from my table based on this get parameter, But I have to check the two conditions after where if the first was not equal then move to the next one. But the main problem is I want to know which condition was executed the first one or the second one.
$sql = $db_->prepare("Select * from table_x where url_en = ? Or url_fr = ?");
Instead of doing this:
$sql = $DB_->prepare("select * from tbl_items where `url_ar`= ?");
$sql->bind_param("s", $_GET["url"]);
$sql->execute();
$result = $sql->get_result();
if($result->num_rows == true){$lang = "ar";}else{
$sql = $DB_->prepare("select * from tbl_items where `url_fr`= ?");
$sql->bind_param("s", $_GET["url"]);
$sql->execute();
$result = $sql->get_result();
if($result->num_rows == true){$lang = "fr";}else{
echo "unfound";exit;
}
}
I want something short by using just SQL
Try searching up each value independently or try bringing them up together in a list and see where they reside when trying to organize it with ORDER BY.
You can use UNION and execute each condition separately. Using some kind of label you can then find out which condition was true.
SELECT 'EN' as label, * FROM table_x WHERE url_en = ?
UNION
SELECT 'FR' as label, * FROM table_x WHERE url_fr = ?
I am working on a query that has an optional filter, so lets assume the table name is products and the filter is the id (primary key)
If the filter is not present I would do something like this:
SELECT * FROM products;
If the filter is present I would need to do something like this:
SELECT * FROM products WHERE id = ?;
I have found some potential solutions that can mix the 2 in sql rather than doing conditions in the back-end code itself
SELECT * FROM products WHERE id = IF(? = '', id, ?);
OR
SELECT * FROM products WHERE IF(? = '',1, id = ?);
I was just wondering which one would be faster (In the case of multiple filters or a very big table) Or is there a better solution to handle this kind of situation?
A better approach is to construct the WHERE clause from the parameters available. This allows the Optimizer to do a much better job.
$wheres = array();
// Add on each filter that the user specified:
if (! empty($col)) { $s = $db->db_res->real_escape_string($col);
$wheres[] = "collection = '$s'"; }
if (! empty($theme)) { $s = $db->db_res->real_escape_string($theme);
$wheres[] = "theme = '$s'"; }
if (! empty($city)) { $s = $db->db_res->real_escape_string($city);
$wheres[] = "city = '$s'"; }
if (! empty($tripday)) { $s = $db->db_res->real_escape_string($tripday);
$wheres[] = "tripday = '$s'"; }
// Prefix with WHERE (unless nothing specified):
$where = empty($wheres) ? '' :
'WHERE ' . implode(' AND ', $wheres);
// Use the WHERE clause in the query:
$sql = "SELECT ...
$where
...";
Simplest approach is OR:
SELECT *
FROM products
WHERE (? IS NULL OR id = ?);
Please note that as you will add more and more conditions with AND, generated plan will be at least poor. There is no fit-them-all solution. If possible you should build your query using conditional logic.
More info: The “Kitchen Sink” Procedure (SQL Server - but idea is the same)
I am very confused about this (returning false):
$sql = "SELECT * from tbl_user WHERE group = 'abc'";
$res = mysql_query($sql);
if(mysql_num_rows($res) > 0) {
$response = array('status' => '1');
} else {
$response = array('status' => '0'); // ---> what I get back
die("Query failed");
}
...despite the fact the field group is present in mySQL database. Even more strange is that the following return the value of group:
$SQL = "SELECT * FROM tbl_user";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['group']; // ---> returns 'abc'
When I execute a WHERE clause with every other fields of my table excepting group (for example WHERE name = 'ex1' AND ID=1 AND isAllowed=0 (and so on...), everything is fine. As soon as I insert group = 'abc', I get nothing...
This makes me mad. If anyone could help... (I am running a local server with MAMP).
Thanks a lot!
The issue is that group is a reserved word in SQL.
For MySql you need to escape it with backticks
`group`
So your query would be
$sql = "SELECT * from tbl_user WHERE `group` = 'abc'";
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.
The update statement in example is not working all the time even though the where clause is true. The database is MYSQL innodb. Would that cause some sort of locking ?? This is so weird.
<?php
$query = 'SELECT id FROM TABLE1';
$result = db_query($query);
while($row = db_fetch_array($result)) {
//do some processing
db_query('UPDATE {TABLE1} SET updated = "1" WHERE id = "%s"',$row['id']);
}
?>
The syntax is wrong - MySQL doesn't use curly brackets:
db_query('UPDATE `TABLE1` SET updated = "1" WHERE id = "%s"',$row['id']);