I know this is quite simple but I've been looking at this for awhile and can't seem to identify what the issue is. I want to update a row in a table using two criteria. When I use either criteria, the table updates fine but when I combine them, it doesn't work.
This is the query
$updatequery = "UPDATE query SET audio='$finalpath' WHERE content='$title' AND WHERE userid LIKE '%$regID%'";
An example of the reg id:
APA91bGHS59rrpM0sbX9PIYT3SzXs-W1yEtGa2xGMGJXi8O1vW2SrgN7koHDj2o6ZwKvkd3TxtzhktsiVtQNSYQRa4uNDF7Yy0VOf0BJfQOnJWMtN2WBQjmVDsuU-0GxmceNLd8SWqOM
An example of content :
Where can I find a car
You only need to use the where keyword once:
$updatequery =
"UPDATE query SET audio='$finalpath' WHERE content='$title' AND userid LIKE '%$regID%'";
# "WHERE" removed here ------------------------------------^
Mandatory comment:
Using string manipulation like this leaves your code vulnerable to SQL-injection attacks. You should really consider using prepared statements instead.
WHERE content='$title' AND userid LIKE '%$regID%'
Where is needed only once
You can have only one WHERE clause, so this is a syntax error:
WHERE content='$title' AND WHERE userid LIKE '%$regID%'
Combine the logic in a single clause:
WHERE content='$title' AND userid LIKE '%$regID%'
The WHERE clause essentially works like conditionals in any other language. You can build up as complex a tree of boolean conditions as you like, as long as the whole thing resolves down to a boolean then it's fine.
Your query is wrong.
Try this:
$updatequery = "UPDATE query SET audio='$finalpath' WHERE content='$title' AND userid LIKE '%$regID%'";
EDIT:
Where is needed only once.
Related
Okay, basically I have a table that contains statements like:
incident.client_category = 1
incident.client_category = 8
incident.severity = 1
etc.
I would like to use the contents from this table to generate other tables that fulfill the conditions expressed in this one. So I would need to make it something like
SELECT * FROM incident WHERE incident.client_category = 1
But the last part of the where has to come from the first table. Right now what I'm trying to do is something like
SELECT * FROM incident WHERE (SELECT condition FROM condition WHERE id = 1)
id = 1 stands for the condition's id. Right now I only want to work with ONE condition for testing purposes. Is there a way to achieve this? Because if there isn't, I might have to just parse the first query's results through PHP into my incident query.
Table schemas:
Engineering Suggestion - Normalize the DB
Storing a WHERE clause, like id = 10, in a field in a MySQL table, is not a good idea. I recommend taking a look at MySQL Normalization. You shouldn't store id = 10 as a varchar, but rather, you should store something like OtherTableid. This allows you to use indices, to optimize your DB, and to get a ton of other features that you are deprived of by using fields as WHERE clauses.
But sometimes we need a solution asap, and we can't re-engineer everything! So let's take a look at making one...
Solution
Here is a solution that will work even on very old, v. 5.0 versions of MySQL. Set the variable using SET, prepare a statement using PREPARE, and execute it using EXECUTE. Let's set our query into a variable...
SET #query = CONCAT(
"SELECT * FROM incident WHERE ",
(SELECT condition FROM condition WHERE id = 1)
);
I know for a fact that this should work, because the following definitely works for me on my system (which doesn't require building any new tables or schema changes)...
SET #query = CONCAT("SELECT id FROM myTable WHERE id = ", (SELECT MAX(id) FROM myTable));
If I SELECT #query;, I get: SELECT id FROM myTable WHERE id = 1737901. Now, all we need to do is run this query!
PREPARE stmt1 FROM #query;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
Here we use a prepare to build the query, execute to execute it, and deallocate to be ready for the next prepared statement. On my own example above, which can be tested by anyone without DB schema changes, I got good, positive results: EXECUTE stmt1; gives me...
| id | 1737901 | .
here is one way to achieve your goal by using what is called dynamic sql, be ware that this works only select from condition table returns only one record.
declare #SQLSTRING varchar(4000)
, #condition VARCHAR(500) -- change the size to whatever condition column size is
SELECT #condition = condition
FROM
condition
WHERE
id = 1
SET #SQLSTRING= 'SELECT * FROM incident WHERE ' + #condition
exec sp_executesql(#SQLSTRING)
Since you have also tagged the question with PHP, I would suggest using that. Simply select the string from the condition table and use the result to build up a SQL query (as a string in PHP) including it. Then run the second query. Psudo-code (skipping over what library/framework you re using to call the db):
$query = "select condition from condition where id = :id";
$condition = callDbAndReturnString($query, $id);
$query = "select * from incident where " . $condition;
$result = callDb($query);
However, be very careful. Where and how are you populating the possible values in the condition table? Even how is your user choosing which one to use? You run the risk of opening yourself up to a secondary SQL injection attack if you allow the user to generate values and store them there. Since you are using the value from the condition table as a string, you cannot parametrise the query using it as you (hopefully!) normally would. Depending on the queries you run and the possible values there as conditions, there might also be risk even if you just let them pick from a pre-built list. I would seriously ask myself if this (saving parts of SQL queries as strings in another table) is the best approach. But, if you decide it is, this should work.
Im wondering if something like this is possible?
$joinguild = "UPDATE guild SET '.$rank.'='.$receiver.' WHERE name ='"$dupecheckinfo["guild"]"'";
Im trying to SET '.$rank.'='.$receiver.', but I dont know if I can use a variable where $rank is. Is there a proper way to write this. Is it even possible? If not how would you approach it? Thanks!
Here is my SQL table im working with
Edit: See how my table has Rank1 Rank2 Rank3 etc. Well I am passing the rank value that I want to set so for example
$rank = $_POST["rank"];
$joinguild = "UPDATE guild SET '.$rank.'='.$username.' WHERE name ='"$dupecheckinfo["guild"]"'";
Your question in not clear but you have some problems in your PHP statement. I think you are trying to create your SQL UPDATE query using PHP variables.
Try this:
$joinguild = "UPDATE guild SET $rank='$receiver' WHERE name='" . $dupecheckinfo["guild"] . "'";
Here $rank should have valid column name in your table. Also read about SQL injection.
Your question is quite unclear but to update records from a table you can use this line of code:
$sql=mysqli_query($conn, "UPDATE `table` SET option1='$op1', option2='$op2', option3='$op3', option4='$op4' where id='$id'");
If this is unclear please let me know.
Yes, you can use variables for table and field names in your queries. However, you should avoid it whenever possible, because it generally leads to SQL injection vulnerabilities. Instead of building queries with string concatenation, use prepared statements with bound parameters. See this page and this post for some good examples.
Unfortunately, the bind mechanism works only for values and not for table names or field names, so it's best to try avoiding variable table/field names. If you find that you absolutely must, the best approach would be to ensure that the contents of the variable matches with a pre-set whitelist of allowed table/field names.
I am trying to refer to a column name to order a query in an application communicating with an Oracle database. I want to use a bind variable so that I can dynamically change what to order the query by.
The problem that I am having is that the database seems to be ignoring the order by column.
Does anyone know if there is a particular way to refer to a database column via a bind variable or if it is even possible?
e.g my query is
SELECT * FROM PERSON ORDER BY :1
(where :1 will be bound to PERSON.NAME)
The query is not returning results in alphabetical order, I am worried that the database is interpreting this as:-
SELECT * FROM PERSON ORDER BY 'PERSON.NAME'
which will obviously not work.
Any suggestions are much appreciated.
No. You cannot use bind variables for table or column names.
This information is needed to create the execution plan. Without knowing what you want to order by, it would be impossible to figure out what index to use, for example.
Instead of bind variables, you have to directly interpolate the column name into the SQL statement when your program creates it. Assuming that you take precautions against SQL injection, there is no downside to that.
Update: If you really wanted to jump through hoops, you could probably do something like
order by decode(?, 'colA', colA, 'colB', colB)
but that is just silly. And slow. Don't.
As you are using JDBC. You can rewrite your code, to something without bind variables. This way you can also dynamically change the order-by e.g.:
String query = "SELECT * FROM PERS ";
if (condition1){
query = query+ " order by name ";
// insert more if/else or case statements
} else {
query = query+ " order by other_column ";
}
Statement select = conn.createStatement();
ResultSet result = select.executeQuery(query);
Or even:
String columnName = getColumnName(input);
Statement select = conn.createStatement();
ResultSet result = select.executeQuery("SELECT * FROM PERS ORDER BY "+columnName);
ResultSet result = select.executeQuery(
"SELECT * FROM PERS ORDER BY " + columnName
);
will always be a new statement to the database.
That means it is, like Thilo already explained, impossible to "reorder" an already bound, calculated, prepared, parsed statement. When using this result set over and over in your application and the only thing, which changes over time is the order of the presentation, try to order the set in your client code.
Otherwise, dynamic SQL is fine, but comes with a huge footprint.
This is quite a basic question, but have not found that much on-line to support.
I need to use a simple update statement in mysql (I know i should use mysqli but not yet ready for this update)
Given That I am working with a database made of a fixed number of items I want that the update apllies only when 2 conditions together are true.
my idea is something like
$sql ="update `members` set `description`='$description[$index]' WHERE id='1' AND fruit = 'banana'";
Is this the proper way of selecting the record to be updated?
Many thanks
Manu
That's how you'd do it more or less, here's a refined one:
$sql ="update `members` set `description`=? WHERE `id`='1' AND `fruit` = 'banana'";
1) See how I put the ? instead of the array? There are smart objects in PHP (read about "Prepared Statements") which allow you to put a parameter "spot" in the query and later have a value instead of it. This makes your query much more secure.
2) I added '`' around your columns. It's not mandatory, but it makes sure that your columns aren't mistaken for something else.
Yes that should work but it's safer to wrap array values in a string in brackets:
$sql ="UPDATE `members` SET `description`='{$description[$index]}' WHERE id='1' AND fruit = 'banana'";
Also make sure $description is somehow filtered or validated, before plugging it directly into the string.
NOTE: Best practice dictates that you use all caps for all SQL keywords, allowing easier differentiation between keywords and your values. Yours has half and half update and set lowercase; WHERE and AND caps, which is worse than going with all lowercase.
[edit] I agree with Daniel Saad that you should be using prepared statements here as well.
I'm trying to write a function that can alter the value of a column in a table, where the table, column, and values are not predetermined. Is it possible to do something like this:
UPDATE :tbl SET :column = :value;
to accomplish this, or can parameters only be bound for values?
EDIT:
Or is this the only way to accomplish this:
$query = "UPDATE".$tbl." SET ".$column." = ".$value.";";
It is not possible to do that. Prepared statements allow the database to optimize a query plan for the particular query. If it doesn't know what table or column, it cannot create the query plan.
Parameters can only be bound to values and not tables/columns.